Android 2048 game implementation

Source: Internet
Author: User
Tags gettext gety

Android 2048 mini-game complete implementation: GridLayout layout (Android 4.0 and above).



Package Com.example.y2048;import Android.annotation.suppresslint;import Android.app.activity;import Android.os.bundle;import Android.util.log;import Android.view.motionevent;import Android.view.View;import Android.widget.button;import Android.widget.gridlayout;import Android.widget.textview;import Android.widget.Toast ; Import Com.example.y2048.map.direction;import Com.example.y2048.map.maps;public class Mainactivity extends Activity {Private String tag = "Gridlayoutactivity"; GridLayout gridlayout;float StartX = 0, Starty = 0, endx, EndY; Maps maps = new maps ();p rivate TextView score;private TextView best; @SuppressLint ("Newapi") void init () {//Get View object Gridla yout = (GridLayout) Findviewbyid (R.id.root), for (int i = 0, i < 4; i++) {for (int j = 0; J < 4; J + +) {Button bn = NE W button (this), bn.setclickable (false), Bn.settext (""),///Set the size of the button bn.settextsize (120); bn.setwidth Bn.setheight (120);//Specifies the line where the component is located gridlayout.spec rowspec = Gridlayout.spec (i + 2);//Specifies the column in which the component is located gridlayout.spec columnSpec = Gridlayout.spec (j); String msg = "Rowspec:" + (i + 2) + "-Columnspec:" + (j); LOG.D (tag, msg); Gridlayout.layoutparams params = new Gridlayout.layoutparams (Rowspec, columnspec);//Specifies that the component fills the container//params.setgravity ( Gravity.fill); Gridlayout.addview (BN, params); Maps.addbutton (I, J, Bn);}} Score = (TextView) Findviewbyid (R.id.score); Score.settext ("0"); best = (TextView) Findviewbyid (r.id.best); Maps.setscore (score); Maps.setbest (best); Maps.init ();} @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview ( R.layout.activity_main); init ();} @Overridepublic boolean dispatchtouchevent (Motionevent event) {//System.out.println ("touch"); int action =  Event.getaction (); if (action = = motionevent.action_down) {StartX = Event.getx (); starty = Event.gety ();} else if (action = = MOTIONEVENT.ACTION_UP) {endx = Event.getx (); EndY = Event.gety (); int direction = Getslidedirection (StartX, Starty, EndX, E NdY);//System.out.println (startx+ "," +starty+ "|" +endx+ "," +endy+"+direction");//Toast.maketext (This, direction+ "", Toast.length_long). Show (); Boolean gameover = maps. Slide (direction); if (Gameover) {if (Maps.getscore () >maps.getbestscore ()) {Toast.maketext (this, "Congratulations over the best record!!! ", Toast.length_short). Show (); Maps.setbestscore (Maps.getscore ()); Best.settext (Maps.getscore () +" ");} Else{toast.maketext (This, "Gameover", Toast.length_short). Show ();}} Return Super.dispatchtouchevent (event);} Return angle private double getslideangle (float dx, float dy) {return math.atan2 (dy, dx) * 180/MATH.PI;} Return direction based on start and end 1: Up, 2: down, 3: Left, 4: Right, 0: not sliding private int getslidedirection (float StartX, float starty, float endx,float EndY) {Float dy = starty-endy;float dx = Endx-startx;int result = direction.none;//If the sliding distance is too short if (Math.Abs (dx) < 2 &&am P Math.Abs (DY) < 2) {return result;} Double angle = getslideangle (dx, dy), if (angle >= -45 && Angle <) {return direction.right;} else if (Angl e >= && Angle < 135) {return direction.up;} else if (angle>= -135 && Angle < -45) {return direction.down;} else if (angle >= 135 && Angle <= 180) | | (Angle >= -180 && Angle <-135)) {return direction.left;} return result;} public void Reset (view view) {Maps.init ();}}


Package Com.example.y2048.map;public interface Direction {//1: Up, 2: down, 3: Left, 4: Right, 0: static final int left=3;static not sliding Final int right=4;static final int up=1;static final int down=2;static final int none=0;}

Package Com.example.y2048.map;import Java.util.random;import Android.content.context;import Android.content.sharedpreferences;import Android.content.sharedpreferences.editor;import Android.view.View; Import Android.widget.button;import Android.widget.textview;public class Maps {private TextView score;private TextView Best;private button[][] maps = new Button[4][4];p ublic void AddButton (int i, int J, Button btn) {maps[i][j] = btn;} private void Swaptext (button btn1, button btn2) {charsequence text = Btn1.gettext (); Btn1.settext (Btn2.gettext ()); Btn2.settext (text);} void Up_remove_blank () {int I, J, k;for (j = 0; J < 4; J + +) {for (i = 1; i < 4; i++) {k = I;while (k-1 >= 0&amp ;& Maps[k-1][j].gettext (). toString (). Length () = = 0) {///The one above is empty swaptext (Maps[k][j], maps[k-1][j]); k--;}}} void Down_remove_blank () {int I, J, k;for (j = 0; J < 4; J + +) {for (i = 2; I >= 0; i--) {k = I;while (k + 1 <= 3& amp;& maps[k + 1][j].gettext (). toString (). Length () = = 0) {//The one above is an empty swapText (Maps[k][j], maps[k + 1][j]); k++;}}} void Left_remove_blank () {int I, J, k;for (i = 0; i < 4; i++) {for (j = 1; j < 4; J + +) {k = J;while (k-1 >= 0&A mp;& Maps[i][k-1].gettext (). toString (). Length () = = 0) {///The one above is empty swaptext (Maps[i][k], maps[i][k-1]); k--;}}} void Right_remove_blank () {int I, J, k;for (i = 0; i < 4; i++) {for (j = 2; J >= 0; j--) {k = J;while (k + 1 <= 3 && maps[i][k + 1].gettext (). toString (). Length () = = 0) {//The one above is empty swaptext (Maps[i][k], maps[i][k + 1]); k++;}}} void Left () {int I, j;for (i = 0; i < 4; i++) {for (j = 0; J < 3; J + +) {String S1 = Maps[i][j].gettext (). toString (); String s2 = maps[i][j + 1].gettext (). toString (); if (s1.equals (S2) &&!s1.equals ("")) {//Maps[i][j]+=maps[i][j+1 ];integer sum = integer.valueof (Maps[i][j].gettext (). toString ()), Sum + = integer.valueof (Maps[i][j + 1].gettext (). ToString ()); int total = Integer.valueof (Score.gettext (). ToString ()), Score.settext (string.valueof (sum + total); maps I [J].settExt (sum.tostring ()); Maps[i][j + 1].settext (""); Left_remove_blank ();}}} void Right () {int I, j;for (i = 0; i < 4; i++) {for (j = 3; J >= 1; j--) {String S1 = Maps[i][j].gettext (). ToString ( ); String s2 = Maps[i][j-1].gettext (). toString (); if (s1.equals (S2) &&!s1.equals ("")) {//Maps[i][j]+=maps[i][j-1 ];//Maps[i][j-1]=0;integer sum = integer.valueof (Maps[i][j].gettext (). toString ()); sum + = integer.valueof (Maps[i][j- 1].gettext (). ToString ()); int total = Integer.valueof (Score.gettext (). ToString ()); Score.settext (string.valueof (sum + total); Maps[i][j].settext (sum.tostring ()); Maps[i][j-1].settext (""); Right_remove_blank ();}}} void up () {int I, j;for (j = 0; J < 4; J + +) {//each column for (i = 0; i < 3; i++) {String S1 = Maps[i][j].gettext (). Tostrin g (); String s2 = maps[i + 1][j].gettext (). toString (); if (s1.equals (S2) &&!s1.equals ("")) {//maps[i][j]=maps[i][j]+ maps[i+1][j];//Maps[i+1][j]=0;integer sum = integer.valueof (Maps[i][j].gettext (). toString ()); sum + = Integer.vaLueof (Maps[i + 1][j].gettext (). ToString ()); int total = Integer.valueof (Score.gettext (). ToString ()); Score.settext ( String.valueof (sum + total); Maps[i][j].settext (sum.tostring ()); Maps[i + 1][j].settext ("");//Remove Space Up_remove_blank () ;}}}} void down () {int I, j;for (j = 0; J < 4; J + +) {//each column for (i = 3; I >= 1; i--) {String S1 = Maps[i][j].gettext (). toSt Ring (); String s2 = Maps[i-1][j].gettext (). toString (); if (s1.equals (S2) &&!s1.equals ("")) {//maps[i][j]=maps[i][j]+ maps[i-1][j];//Maps[i-1][j]=0;integer sum = integer.valueof (Maps[i][j].gettext (). toString ()); sum + = integer.valueof (Maps[i-1][j].gettext (). ToString ()); int total = Integer.valueof (Score.gettext (). ToString ()); Score.settext ( String.valueof (sum + total); Maps[i][j].settext (sum.tostring ()); Maps[i-1][j].settext ("");//Remove Space Down_remove_blank ();}}}} private void Addnumber () {Random random = new random (), int x = Random.nextint (4), int y = random.nextint (4); int number = RA Ndom.nextint (20);//probability of appearing 2 probability of 95% 4 5%if (number==0) nUmber=4;else Number=2;while (Maps[x][y].gettext (). toString (). Length ()! = 0) {x = Random.nextint (4); y = Random.nextint (4 );} Maps[x][y].settext (number + "");} public void Init () {for (int i = 0; i < 4; i++) {for (int j = 0; J < 4; J + +) {Maps[i][j].settext ("");}} Score.settext ("0"); Addnumber (); Addnumber ();} Private Boolean Isfull () {for (int i = 0; i < 4; i++) {for (int j = 0; J < 4; J + +) {if (Maps[i][j].gettext (). Tostrin g (). Length () = = 0) {return false;}}} return true;} public boolean Slide (int direction) {if (direction = = Direction.left) {Left_remove_blank (); left (); if (Isfull ()) return True;else {addnumber ();}} else if (direction = = Direction.right) {Right_remove_blank (); right (); if (Isfull ()) return True;else {Addnumber ();}} else if (direction = = Direction.up) {Up_remove_blank (); up (), if (Isfull ()) return True;else {Addnumber ();}} else if (direction = = Direction.down) {Down_remove_blank ();d own (); if (Isfull ()) return True;else {Addnumber ();}} return false;} public void SetScore (TextView sCore) {This.score = score;} public void Setbest (TextView best) {this.best = Best;best.settext (Getbestscore () + "");} public int Getscore () {return integer.valueof (Score.gettext (). toString ());} public int Getbestscore () {Sharedpreferences sp = Best.getcontext (). Getsharedpreferences ("BestScore.txt", context.mode_private); int Bestscore=sp.getint ("Bestscore", 0); return bestscore;} public void Setbestscore (int score) {Sharedpreferences sp = Best.getcontext (). Getsharedpreferences ("BestScore.txt", Context.mode_private); Editor edit = Sp.edit (); Edit.putint ("Bestscore", score); Edit.commit ();}}

<gridlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:id=" @+id/root "android:layout_width=" match_parent "android:layout_height=" MATC H_parent "android:columncount=" 4 "android:rowcount=" 6 "tools:ignore=" Newapi "> <textview android: Layout_width= "Wrap_content" android:layout_height= "50DP" android:layout_marginleft= "4DP" Android:layo ut_marginright= "4DP" android:gravity= "center" android:text= "score:"/> <textview android:id= "@+id/score" android:layout_width= "wrap_content" android:layout_height= "50DP" Android:layout_marginle ft= "4DP" android:layout_marginright= "4DP" android:gravity= "center" android:text= "score:"/> &lt ;        TextView android:layout_width= "wrap_content" android:layout_height= "50DP" android:gravity= "center" android:text= "best:"/> <textview       Android:id= "@+id/best" android:layout_width= "wrap_content" android:layout_height= "50DP" Androi        d:gravity= "center"/> <button android:layout_width= "wrap_content" android:layout_height= "40DP" Android:layout_columnspan= "4" android:onclick= "reset" android:text= "reset"/></gridlayout>










Android 2048 game implementation

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.