Android 2048 small game source

Source: Internet
Author: User


Http://git.oschina.net/scimence/sci_2048/wikis/home

Package Com.example.sci_2048;import Java.util.random;import Android.app.activity;import android.app.AlertDialog; Import Android.content.dialoginterface;import Android.graphics.color;import Android.os.bundle;import Android.view.gravity;import Android.view.menu;import Android.view.motionevent;import Android.view.View;import Android.view.view.ontouchlistener;import Android.view.windowmanager;import android.view.animation.Animation; Import Android.view.animation.animationset;import Android.view.animation.scaleanimation;import Android.widget.button;import Android.widget.relativelayout;import Android.widget.textview;public Class Mainactivity extends Activity implements Ontouchlistener, Android.view.view.onclicklistener{textview Maxview, scoreview;//current maximum value, cumulative score value display text box int maxint=0, scoreint=0;//maximum value, cumulative score numeric form TextView cell[][] = new textview[4][4];// Create 16 cells of the game as a text box int num[][] = new int[4][4];//stores 16 cells corresponding to the numeric value int count = 0;//counts the number of values greater than 0 in the current 16 cells button again;// Re-start public enum Direction {left, RIght, up, down; }//direction Direction Direction = null;//marks the slide direction of the screen float x1=-1, y1=-1, x2=-1, y2=-1;//sign Touch Press and touch release coordinates int cellwidth;// Set the size of the squares in the game @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (Savedinstancesta                TE); View main = Creatmainview ();//Create the Game View Setcontentview (main);//Set as Game views Main.setontouchlistener (this);//Add Touch Event Monitor Listen, used to respond to touch sliding event again.setonclicklistener (this);//Restart button Add Event Response, Response button click Randomsite ();//randomly generate number at empty position                Value 2 randomsite (); Refresh ();//Refreshes the display value of the interface}//create the main view of the game, including 3 parts: Top info, middle 4*4 square, bottom button @SuppressWarnings ("deprecation") public see Creatmai        NView () {//Gets the width and height of the screen windowmanager wm = This.getwindowmanager ();        int screenwidth = Wm.getdefaultdisplay (). GetWidth ();              int screenheight = Wm.getdefaultdisplay (). GetHeight (); According to the width of the screen to set the size of the game box, when the screen width is greater than the height, according to the new proportion of width and height, so tall than wide cellwidth = screenwidth <= screenheight? (screenwidth-Ten)/4: (SCREENHEIGHT*SCREENHEIGHT/SCREENWIDTH-10)/4; float rat = ScreenWidth <= screenheight?  screenwidth/480:screenwidth/480 * screenheight/screenwidth;//relative to 480 screen size proportional value int size1 = (int) (28*rat), size2 = (int)            (42*rat), size3 = (int) (22*rat);        Relativelayout main = new Relativelayout (this);    Game Information Display section Relativelayout info = new Relativelayout (this);    Info.setbackgroundcolor (0xff074747);    Maximum and score display information, the first two for the two parts of the label to display the value TextView label[] = new TEXTVIEW[4];        String ltext[] = new string[]{"Max", "Score", "0", "0"};    Relativelayout.layoutparams paramsl[] = new RELATIVELAYOUT.LAYOUTPARAMS[4]; int paramsnum[][] = new int[][]//four text box layout parameter {{relativelayout.align_parent_top, relativelayout.align_parent_left}, { Relativelayout.align_parent_top, Relativelayout.align_parent_right}, {relativelayout.align_parent_bottom,   Relativelayout.align_parent_left}, {relativelayout.align_parent_bottom, relativelayout.align_parent_right} };        Sets the layout for the display information for (int i=0; i<4; i++) {Label[i] = new TextView (this);    Label[i].settext (Ltext[i]);    Label[i].settextsize (SIZE1);    Label[i].settextcolor (Color.White);        Label[i].setgravity (Gravity.center);    Paramsl[i] = new Relativelayout.layoutparams ((int) (cellwidth*1.1), (int) (cellwidth*0.4));    Paramsl[i].addrule (Paramsnum[i][0]);            Paramsl[i].addrule (paramsnum[i][1], relativelayout.true);    Info.addview (Label[i], paramsl[i]); } Maxview = label[2];                 Map the most value to the global variable for next access Scoreview = Label[3]; The body of the game 4*4 the relativelayout BODY = new Relativelayout (this);//Create a view of the relative layout Body.setbackgroundcolor (Color.bla CK);//Set background color for (int i=0; i<4; i++) for (int j=0; j<4; J + +) {Cell[i][j] = new T Extview (this);//create num[i][j] = 0;//Initial, the value in each square is 0 relativelayout.layoutparams params = new Relative        Layout.layoutparams (Cellwidth, cellwidth); int left = 2 + J * (2 + cellwidth), top = 2 + I * (2 + cellwidth), right = left + cellwidth, bottom = top + Cellwidth;//top property values are determined by row position I, le FT is determined by the column position J Params.setmargins (left, top, right, bottom);//Set the layout position of each square body.addview (cell[i][j], params) ;//The text box that represents the grid is added to the form cell[i][j].settextsize (SIZE2);//Set the font size cell[i][j].setgravity (gravity.center);//Set the text This layout way}//Add information Display section to main interface relativelayout.layoutparams Paramsinfo = new Relativelayout.layoutpara        MS ((int) (cellwidth*2.2), (int) (cellwidth*0.8)); int right = (int.) (SCREENWIDTH/2 + (CELLWIDTH*4+10)/2), left = right-(int) (cellwidth*2.2), top = 0, bottom = (int) (Cellwidt        h*0.8); Paramsinfo.setmargins (left, top, right, bottom);//Paramsinfo.addrule (relativelayout.align_parent_top);//PA                Ramsinfo.addrule (Relativelayout.align_parent_right, relativelayout.true);                Main.addview (info, paramsinfo); Add the main part of the game to the main interface relativelayout.layoutparams paramsbody = New Relativelayout.layoutparams (cellwidth*4+10, cellwidth*4+10);        Paramsbody.addrule (Relativelayout.center_in_parent, relativelayout.true);                Main.addview (body, paramsbody); Add Restart button to main interface relativelayout.layoutparams Paramsagain = new Relativelayout.layoutparams ((int) (Cellwidth * 1.2), (i        NT) (Cellwidth * 0.6));        Paramsagain.addrule (Relativelayout.align_parent_bottom);        Paramsagain.addrule (Relativelayout.center_horizontal, relativelayout.true);        Button Btnagain = New button (this);//Start Btnagain.settext again ("restart");                Btnagain.settextsize (SIZE3);//Set Font size Main.addview (Btnagain, Paramsagain);    again = btnagain;//maps the button to the global variable return main; }//In the space of the game, randomly generated values 2 public void Randomsite () {if (count<16)//When 16 squares are not filled with values {random rnd = new R        Andom ();        int n = rnd.nextint (16-count), cn=0;//randomly generates a value for (int i=0; i<4; i++) based on the number of empty positions.//Converts the position of the random number to the corresponding position in the 4*4 square FoR (int j=0; j<4; J + +) {if (num[i][j] = = 0) {if (CN = = N) {num[i][j] = 2;        The number of count++;//4*4 squares is greater than 0 statistics Aniscale (cell[i][j]);//Set the animation effect return;        } else cn++; }}}}//message box public void MessageBox (String str) {new Alertdialog.builder (this). Setmessage (    STR). Setpositivebutton ("OK", null). Show (); }//When the game interface is filled with values, determine if you can merge public boolean canbeadd () {///To determine whether there are adjacent values in the vertical two directions can be combined if (Canbeadd (direction.right)) Retu  RN true;  else return Canbeadd (Direction.down); }//When the game interface is filled with values, determine if it can be merged in the specified direction, and if not, the game ends public boolean canbeadd (Direction Direction) {if (count<16) return true;// When not filled, you can continue to manipulate int startn=0, addx=0, addy=0;//start value, end value, step increment, x, y direction increment if (direction = = Direction.right) {startn=3; addx=0; AddY = 1; }else if (direction = = Direction.left) {startn=0; addx=0; addy=-1;} else if (direction = = Direction.down) {startn=3; addx=1; addy=0;} else if (directIon = = Direction.up) {startn=0; addx=-1; addy=0;} for (int x=0; x<=3; x + +)//execute {int y=startn;int i=0 for each row or column, j=0;if (direction = = Direction.right | | direction = = Direction . left) {i=x; j=y;} else {i=y; j=x;} for (int k = 0; k<3; k++)//4 positions, starting from one direction for each of the two consecutive positions, the same is merged, the merge order is reversed in reverse of direction {int i1 = I-K*ADDX, J1 = j-k*addy, i2 = i1-a DdX, J2 = J1-addy;if (num[i1][j1]==num[i2][j2] && num[i1][j1]!=0) {return true;}}}    return false;}  @Override public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the action Bar        If it is present.        Getmenuinflater (). Inflate (R.menu.main, menu);    return true; } @Overridepublic Boolean OnTouch (View V, motionevent event) {//Gets the coordinates of the start and end point of the touch drag to determine the touch move direction switch (event.getaction ()) { Case motionevent.action_down://Touch the screen after the record coordinates x1 = EVENT.GETX ();//Press point coordinates y1 = Event.gety (); Break;case Motionevent.action_ move://Touch Move Break;case MotionEvent.ACTION_UP:x2 = Event.getx ();//move point coordinates y2 = event.gety (); Break;case motionevent.action _cancel:}//touch processing, requires touch press and release point coordinates are present, and different, in addition we require touch moving distance greater than or equal to a square width if ((x1!=-1 && x2!=-1) && (x1!=x2| | y1!= y2) && (Math.Abs (x1-x2) >= Cellwidth | | Math.Abs (y1-y2) >= cellwidth)) {if (X2-x1 > Math.Abs (y2-y1)) Direction = Direction.right;else if (x1-x2 > Math.Abs (y2-y1)) Direction = Direction.left;else if (y2-y1 > Math.Abs (x2-x1)) Direction = Direction.down;else If (Y1-y2 > Math.Abs (x2-x1)) Direction = direction.up;gameprocess (direction);//game Internal numeric processing refresh ();//Depending on the data in the array, Refresh display to interface x2 = x1 =-1; y2 = y1 = -1;//This sentence guarantees that each touch move is processed only once}return true;} The game's internal numeric processing is implemented in 3 steps: Overlay in one Direction, merge same values, and overlay public void gameprocess (Direction Direction) {Boolean flag = false;//in this direction again Flag whether a value can be dropped, or can be combined if (Gravaty (direction)) flag = true;//Control the value in the 4*4 square falls in one direction, superimposed if (add (direction)) {flag = true; Gravaty (direction);//If a value is merged, the value above the logic drops}if (flag) randomsite ();//If a value is dropped or merged, randomly generates 2if at an empty position (count==16 &&!canbeadd ()) MessageBox ("Sorry, this cannot be cleared"); when//16 squares are filled, determine if the values can be combined in a certain direction, not a hintInformation}//control the value of the fall direction of the game, the function to achieve the value of falling and stacked, the same value does not merge public boolean gravaty (Direction Direction) {int startn=0, endn=0, Step=0, ADDX =0, addy=0;//start value, end value, step increment, x, y direction increment boolean havedroped = false;//flag Whether there is a value drop if (direction = = Direction.right) {startn=3; endn = 0; Step=-1; addx=0; Addy=1; }else if (direction = = Direction.left) {startn=0; endn=3; step=1; addx=0; addy=-1;} else if (direction = = Direction.down) {startn=3; endn=0; step=-1; addx=1; addy=0;} else if (direction = = Direction.up) {startn=0; endn=3; step=1; addx=-1; addy=0;} for (int x=0; x<=3; x + +)//execute {for (int y=startn) on each row or column; (step<0 && y>=endn) | | (step>0 && Y&LT;=ENDN); y+=step) {int i=0, j=0, I2=-1, j2=-1;if (direction = Direction.right | | direction = direction.left) {i=x; j=y;} else {i=y; j=x;} i2=i;j2=j;//the value in the current square is not 0, and its direction is shifted to an empty position on one side of the area, with a value of 0while (num[i][j]! = 0 && Inarea (I2+ADDX, J2+addy) && num[ I2+addx][j2+addy] = = 0) {//calculates the position of the last available value of the coordinate direction i2 + = ADDX; J2 + = AddY;} if (Inarea (I2, J2) && (I!=i2 | | j!=j2)//The value at the coordinates is dropped to the last empty position {num[i2][j2] = num[i][j];num[i][j] = 0;havedroped = true;//has a value drop}}}return havedroped;} Add animation effect to view V, size change public void Aniscale (view v) {V.bringtofront ();//front-end display Animationset aniset = new Animationset (true);// Set the size from 0.5 times times to 1.1 times times scaleanimation Scaleani = new Scaleanimation (0.89f, 1.15f, 0.89f, 1.15f, Animation.relative_to_self, 0.5f, Animation.relative_to_self, 0.5f); Scaleani.setduration (400);//Set animation effect time aniset.addanimation (Scaleani);// Adds an animation effect to the animation set v.startanimation (Aniset);//view V starts the animation effect}//on gravaty () processing, controls the same value to merge public boolean add in the specified direction (Direction direction) {int startn=0, addx=0, addy=0;//start value, end value, step increment, X, y-direction increment boolean combined = false;//tag if there are numeric values combined if (direction = = Direction.right) {startn=3; addx=0; addy=1;} else if (direction = = Direction.left) {startn=0; addx=0; addy=-1;} else if (direction = = Direction.down) {startn=3; addx=1; addy=0;} else if (direction = = Direction.up) {startn=0; addx=-1; addy=0;} for (int x=0; x<=3; x + +)//execute {int y=startn;int i=0 for each row or column, j=0;if (direction = = DirectiOn. Right | | Direction = = Direction.left) {i=x; j=y;} else {i=y; j=x;} for (int k = 0; k<3; k++)//4 positions, starting from one direction for each of the two consecutive positions, the same is merged, the merge order is reversed in reverse of direction {int i1 = I-K*ADDX, J1 = j-k*addy, i2 = i1-a DdX, J2 = J1-addy;if (num[i1][j1]==num[i2][j2] && num[i1][j1]!=0) {scoreint + = num[i2][j2];//Cumulative score num[i1][j1] *= 2 NUM[I2][J2] = 0;combined = true;count--;//value is combined, the value greater than 0 is reduced by 1aniScale (cell[i1][j1]);//animate if (num[i1][j1] = = 2048) MessageBox ("Congratulations, you won!" //if (num[i1][j1] = = 2048) Toast.maketext (this, "Congratulations, you won!") ", Toast.length_short). Show ();}}} return combined;} Determine if N1 and N2 are between 0 and 3, ensure that the coordinates n1,n2 in the 4*4 Square range public boolean inarea (int n1, int n2) {return 0 <= N1 && n1<=3 &&amp ; 0 <= n2 && n2<=3;}        Refreshes the displayed values in the game grid, displays the values in the 4*4 array to the cell public void Refresh () {for (int i=0; i<4; i++) for (int j=0; j<4; J + +) { if (num[i][j]==0) Cell[i][j].settext ("");//value is 0 o'clock, empty shows else Cell[i][j].settext (String.valueof (Num[i][j]));//Greater Than 0 o'clock display the corresponding value in the grid cell[i][j].setbackgrOundcolor (Getbaccolor (Num[i][j]));//Set Background color if (num[i][j]==2 | | num[i][j]==4) cell[i][j].settextcolor (0xff776        E65);        else Cell[i][j].settextcolor (0XFFF9F6F2);//Set Font color if (MaxInt < num[i][j]) maxInt = num[i][j];//Record maximum value }maxview.settext (string.valueof (MAXINT));//Display maximum Scoreview.settext (string.valueof (Scoreint));//Display score}// Gets the background color corresponding to the values public int getbaccolor (int num) {int color[] = new int[]{0xff074747, 0xff999999, 0xffede0c8, 0xfff2b179, 0XFFF  59563, 0xfff67c5f, 0xfff65e3b, 0xffedcf72, 0xffedcc61, 0xffedc850, 0xffedc53f, 0xffedc22e}; The subscript position of the int i=0;//marker color array, corresponding to the values 0, 2, 4, 8, 16......while (num>1) {i++;num/=2;} Return color[i];//returns the corresponding color value} @Overridepublic void OnClick (View v)//Restart button's event response {new Alertdialog.builder (this)//. Settitle (""). Setmessage ("Are you sure you want to start this council again?") "). Setpositivebutton (" OK ", new Dialoginterface.onclicklistener () {public void OnClick (Dialoginterface dialogi    nterface, int i) {rePlay (); }}). Setnegativebutton ("Cancel", null). Show ();}//replay game, empty game data Information public void RePlay () {///empty data Maxint = 0;scoreint = 0;count = 0;for (int i=0; i<4; i++) for (int j=0; j<4;        J + +) {Num[i][j] = 0;        }//generates two random positions randomsite ();                Randomsite (); Refresh ();//Refreshes the display}}

Attachment Download: Http://git.oschina.net/scimence/sci_2048/attach_files



Android 2048 small game source

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.