Android 2048 game implementation
Last Update:2017-06-10
Source: Internet
Author: User
<span id="Label3"></p><p><p>Android 2048 mini-game complete implementation: gridlayout layout (android 4.0 and above).</p></p><p><p></p></p><p><p>Once did a 2048 algorithm problem, learned a few days android, think can achieve an android Version. And I wrote A.</p></p><p><p></p></p><p><p>Included in Something:</p></p><p><p>GridLayout layout</p></p><p><p>Adding view components dynamically in activity</p></p><p><p>Infer the direction the user is sliding on the screen</p></p><p><p>2048 algorithm (in C + + written before the test, write is also easy to understand it, http://blog.csdn.net/liang5630/article/details/39895087).</p></p><p><p>Not much to say, first:</p></p><p><p><br></p></p><p><p><br></p></p><p><p></p></p><pre name="code" class="java">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 Button's font size 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 1: up according to the start and end Points. 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;//assume that the sliding distance is too short if (math.abs (dx) < 2 && 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 ();}}</pre><br><br><p><p></p></p><p><p></p></p><pre name="code" class="java"><pre name="code" class="java">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;}</pre></pre><br><pre name="code" class="java">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& ;& 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 ();}}</pre><br><pre name="code" class="html"><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:"/> < ; 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></pre><br><p><p><br></p></p><p><p>Reprint Please specify source: http://blog.csdn.net/liang5630/article/details/41251549</p></p><p><p>Source code and APK download:</p></p><p><p><br></p></p><p><p><br></p></p><p><p><br></p></p><p><p><br></p></p><p><p><br></p></p><p><p><br></p></p><p><p><br></p></p> <p><p>Android 2048 game implementation</p></p></span>