Android High imitation 2048 small game implementation code _android

Source: Internet
Author: User
Tags abs gettext gety clearscore

Just started into the splash interface:

1.splashactivity.java (two seconds after entering the start interface, splash interface layout Only a picture, after the blog, will show you)

public class Splashactivity extends activity {
@Override
protected void onCreate (Bundle savedinstancestate) { C4/>super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_splash);
New Thread (New Runnable () { 
@Override public
void Run () {
try {
thread.sleep);
Intent intent=new Intent (Splashactivity.this, loginactivity.class);
StartActivity (intent);
} catch (Interruptedexception e) {
//TODO auto-generated catch block
e.printstacktrace ();
}
Finish ();
}
}). Start ();
}

2.LoginActivity (Landing interface)

Private Button btn1,btn2;
Private EditText Etacount,etpassword; @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_login);
Initview ();
private void Initview () {btn1= (button) Findviewbyid (R.id.btn_login); btn2= (Button) Findviewbyid (R.id.btn_register);
Etacount= (EditText) Findviewbyid (R.id.et_account);
Etpassword= (EditText) Findviewbyid (R.ID.ET_PWD); Btn1.setonclicklistener (New Onclicklistener () {//Login button listener @Override public void OnClick (View v) {sharedpreferences share
Dpreferences=getsharedpreferences ("User", mode_private);
String number=sharedpreferences.getstring ("number", "");
int a,b;
if (number== "") {a=0;//record number of users}else {a=integer.parseint);}
String account;
String password;
for (b=0;b<a;b++) {account= "account" +B; password= "Password" +B;
String jname=sharedpreferences.getstring (Account, "");
String jpwd=sharedpreferences.getstring (password, ""); if (Jname.equals () Etacount.gettext () TostriNg ()) | | Jpwd.equals (Etpassword.gettext (). ToString ())) {if jname.equals (Etacount.gettext (). ToString ()) &&
Jpwd.equals (Etpassword.gettext (). toString ())) {finish ();
Intent intent=new Intent (Loginactivity.this, Mainactivity.class);
StartActivity (Intent);
Break }else if (Jname.equals (Etacount.gettext (). toString ())) {Toast.maketext (loginactivity.this, "Password error", Toast.length_ 
Short). Show ();
}} if (B==a) {Toast.maketext (loginactivity.this, "User not registered", Toast.length_short). Show ()
});
Registration button Listener Btn2.setonclicklistener (new Onclicklistener () {@Override public void OnClick (View v) {String account;
String password;
Sharedpreferences sharedpreferences=getsharedpreferences ("user", mode_private);
String number=sharedpreferences.getstring ("number", "");
int A;
int b; if (number== "") {a=0}
else {a=integer.parseint (number);} for (b = 0; b <a; b++) {account= ' account ' +b; password= ' password ' +b;
String jname=sharedpreferences.getstring (Account, ""); if (Jname.equals () Etacount.gettext (). ToSTring ()) {break;}}
if (b==a) {if (Etacount.gettext (). ToString (). Equals ("") &&etpassword.gettext (). ToString (). Equals ("")) {
Toast.maketext (loginactivity.this, "Username password cannot be blank", Toast.length_short). Show ();
}else {account= "account" +b password= "password" +B;
Sharedpreferences.editor Editor=sharedpreferences.edit ();
Editor.putstring (Account,etacount.gettext (). toString ());
Editor.putstring (Password,etpassword.gettext (). toString ());
Editor.putstring ("number", + "");
Editor.commit ();
Toast.maketext (Loginactivity.this, "registered successfully", Toast.length_short). Show ();
}}else {Toast.maketext (loginactivity.this, "This account already exists", Toast.length_short). Show ();
}); } 
}

The

loginactivity layout is as follows:

<imageview android:id= "@+id/img_head" android:layout_width= "match_parent" android:layout_height= "260DP" Android : background= "@drawable/head_game" "/> <edittext android:id=" @+id/et_account "android:layout_width=" Match_ Parent "android:layout_height=" 50DP "android:layout_below=" @id/img_head "android:layout_marginleft=" 50DP "Android: layout_marginright= "50DP" android:layout_margintop= "40DP" android:background= "@drawable/set_charge_top" Android: drawableleft= "@drawable/login_img2" android:hint= "Please enter account"/> <edittext android:id= "@+id/et_pwd" android:layout _width= "Match_parent" android:layout_height= "50DP" android:layout_below= "@id/et_account" Android:layout_ marginleft= "50DP" android:layout_margintop= "10DP" android:layout_marginright= "50DP" android:background= "@drawable /set_charge_top "android:drawableleft=" @drawable/login_img3 "android:hint=" Please enter the password "/> <button" android:id= /btn_login "android:layout_width=" wrap_content "android:layout_height=" wrap_content "android:text=" DengRecord "android:layout_below=" @id/et_pwd "android:layout_margintop=" 10DP "android:layout_marginleft=" 70DP "/> <
Button android:id= "@+id/btn_register" android:layout_width= "wrap_content" android:layout_height= "Wrap_content" android:text= "register" android:layout_below= "@id/et_pwd" android:layout_torightof= "@id/btn_login" Android:layout_ margintop= "10DP" android:layout_marginleft= "60DP"/>

3.mainactivity.java (master face)

public class Mainactivity extends activity {private TextView tvscore; private Animation Animation; private static Mainac
Tivity mainactivity = null;
private int score = 0;
Private ImageView ImageView;
Private Gameview Gameview; public static mainactivity getmainactivity () {return mainactivity.} public mainactivity () {mainactivity = this;} @Over Ride protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (
R.layout.activity_main);
Tvscore = (TextView) Findviewbyid (R.id.tvscore);
imageview= (ImageView) Findviewbyid (R.id.img_monkey); public void OnClick (view view) {switch (View.getid ()) {Case r.id.btn_help://Help button, pop-up dialog box Animation=animationutils.loada
Nimation (This,r.anim.anim_monkey);
Alertdialog.builder dialog2=new Alertdialog.builder (this);
Dialog2.settitle ("Taunt + contempt"); Dialog2.setmessage ("You need help with such a simple game!!")
How can you not be in heaven "); Dialog2.setpositivebutton ("Give Me a channeling monkey", New Onclicklistener () {@Override public void OnClick (dialoginterface dialog, int which) {
Imageview.startanimation (animation);//Set animation for ImageView}}); Dialog2.setnegativebutton ("Continue playing ~", new Onclicklistener () {@Override public void OnClick (dialoginterface dialog, int
which) {}});
Dialog2.show ();
Break
Case r.id.btn_quit://Exit button click event alertdialog.builder dialog = new Alertdialog.builder (this);
Dialog.settitle ("Hint:"); Dialog.setmessage ("Master, are you really going to leave me?")
"); 
Dialog.setpositivebutton (OK), new Onclicklistener () {@Override public void OnClick (Dialoginterface dialog, int which) {
System.exit (0);
}
}); 
Dialog.setnegativebutton ("Cancel", new Onclicklistener () {@Override public void OnClick (Dialoginterface dialog, int which) {
}
});
Dialog.show ();
Break
Default:break; } public void ClearScore () {//clear score score = 0; Showscore ();} public void Showscore () {//Show score Tvscore.settext (score + "")
; public void Addscore (int s) {//Add score score + = = s; showscore ();}}

Mainactivity Layout file

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http:// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:o" rientation= "vertical" tools:context= "com.jerry.game2048.MainActivity" > <linearlayout android:layout_width= "
Match_parent "android:layout_height=" wrap_content "android:orientation=" horizontal "android:background=" "#574336" > <textview android:layout_marginleft= "10dp" android:layout_width= "wrap_content" android:layout_height= "wrap _content "android:text=" @string/score "android:textsize=" 24sp "android:textcolor=" #FFFFFF "android:textstyle=" bold "/> <textview android:id=" @+id/tvscore "android:textsize=" 25sp "android:textcolor=" #FFFFFF "Android:layout_ Width= "Wrap_content" android:layout_height= "wrap_content"/> </LinearLayout> < Com.jerry.game2048.GameView android:id= "@+id/gameview" android:layout_width= "Fill_parent" 0DP "Android:layout_weight= "1" ></com.jerry.game2048.GameView> <imageview android:id= "@+id/img_monkey" android:layout_width=
"60DP" android:layout_height= "60DP" android:visibility= "visible" android:layout_gravity= "Center_horizontal" android:src= "@drawable/icon10" android:scaletype= "Fitxy"/> <linearlayout android:id= "@+id/ly_btns" Android: layout_margintop= "20DP" android:layout_width= "match_parent" android:layout_height= "Wrap_content" Android:o rientation= "Horizontal" android:background= "#ddada0" > <button android:id= "@+id/btn_help" Android:layout_
Width= "0DP" android:layout_weight= "1" android:layout_height= "wrap_content" android:layout_marginleft= "20DP"
android:text= "Game Help" android:textsize= "20sp" android:onclick= "OnClick"/> <button android:id= "@+id/btn_quit"
Android:layout_width= "0DP" android:layout_weight= "1" android:layout_height= "Wrap_content" android:text= "Exit Game" android:layout_marginright= "20DP" android:textsize= "20sp" android:onclick= "OnClick"/> </LinearLayout> &Lt TextView android:layout_width= "match_parent" android:layout_height= "40DP" android:singleline= "true" Android: Ellipsize= "marquee" android:focusable= "true" android:focusableintouchmode= "true" android:marqueerepeatlimit= Marquee_forever "android:scrollhorizontally=" true "android:textsize=" 30sp "android:background=" #000000 "Android: Textcolor= "#ffffff" android:text= "here to write the actual project, you need to add advertising information, this is a race lamp effect, encountered problems, can be left in this blog post and questions, you can answer, reproduced please indicate the source, thank you"/> < /linearlayout>

4.card.java (Card Class)

public class Card extends Framelayout {
private int num=0;
Private TextView label;
Public Card (context) {
super (context);
Label=new TextView (GetContext ()); 
Label.settextsize (a);
Label.setgravity (gravity.center);
Label.setbackgroundcolor (0X33FFFFFF);/set the color of each card
layoutparams lp=new layoutparams ( -1,-1); This class is used to initialize the wide-high attribute
Lp.setmargins (10, 10, 0, 0) in the layout control TextView;/set interval
addview (LABEL,LP); 
Setnum (0);
}
public int Getnum () {return
num;
}
public void setnum (int num) { 
this.num=num;
if (num<=0) {
label.settext ("");
} else {
Label.settext (num+ "");
}
}
Override the Equals method to determine if the number of card bindings is equal public
Boolean equals (Cards O) {return
getnum () ==o.getnum ()} 
}

5.gameview.java (main logic)

public class Gameview extends GridLayout {private card[][] Cardsmap = new CARD[4][4];//To hold the collection of point classes cardsmap subscript privat
E list<point> emptypoints = new arraylist<point> (); Public Gameview (context, AttributeSet attrs, int defstyle) {Super (context, attrs, Defstyle); Initgameview (); PU
Blic Gameview (context) {super (context); Initgameview ();} public Gameview (context context, AttributeSet Attrs) {
Super (context, attrs);
Initgameview (); } private void Initgameview () {setcolumncount (4); SetBackgroundColor (0xffddada0); Setontouchlistener (new Ontouchlistener () {///Add touch Event start private float startx, Starty, OffsetX, OffsetY; @Override public boolean Ontouch (View V, Motionevent event) {switch (event.getaction ()) {Case MotionEvent.ACTION_DOWN:startX = Event.getx (); starty = Event.gety
();
Break Case MotionEvent.ACTION_UP:offsetX = Event.getx ()-startx;//greater than 0 represents right sliding OffsetY = Event.gety ()-starty;//less than 0 represents up-slip if (M Ath.abs (OffsetX) > Math.Abs (OffsetY)) {if (OFfsetx > 5) {swiperight ();} else if (OffsetX <-5) {swipeleft ();}}
else {if (OffsetY > 5) {Swipedown ();} else if (OffsetY <-5) {swipeup ();}} break;
return true;
}
}); //per card width and height @Override protected void onsizechanged (int w, int h, int oldw, int oldh) {//The method is the height of the change when we can get the current width of the height is how much//the
The method is also called when the game is created, which is the method used to Super.onsizechanged (W, H, OLDW, OLDH);
To get a narrow length of the phone, 10 is the distance between each card, with the width of the phone divided by 4 is the length of each card int cardwidth = (math.min (w, h)-10)/4;
Addcards (Cardwidth, cardwidth);
Startgame ();  }//Add cards to form 4*4 matrix private void addcards (int cardwidth, int cardheight) {card C; for (int y = 0; y < 4; y++) {for (int x = 0; x < 4; X + +) {c = new card (GetContext ()); C.setnum (2); AddView (c, Cardwidth, cardheight);//By the way, the newly created cards are stored in the newly created two-dimensional array in the initialization process cardsmap[x][
Y] = c; }}///Start Game, initialize 16 card public void Startgame () {mainactivity.getmainactivity (). ClearScore (); for (int y = 0; y < 4; y
+ +) {for (int x = 0; x < 4 + x + +) {cardsmap[x][y].setnum (0);}} addrondomnum (); AddRondomnum (); }//Judge game end private void Endgame () {Boolean isfull=true;//to determine whether the card is covered with a flag variable for (int x = 0; x < 4; + +) {for (int y = 0; y < 4; y++) {if (Cardsmap[x][y].getnum () ==0 | | (X>0&&cardsmap[x][y].equals (cardsmap[x-1][y]) | | (X<3&&cardsmap[x][y].equals (cardsmap[x+1][y]) | | (Y>0&&cardsmap[x][y].equals (cardsmap[x][y-1]) | | (Y<3&&cardsmap[x][y].equals (cardsmap[x][y+1]))
{isfull=false; break;} } if (isfull) {alertdialog.builder dialog=new Alertdialog.builder (GetContext ()); Dialog.settitle ("Game over!
"); Dialog.setmessage ("You are too vegetable!") Do you want to play it one more time?
");
Dialog.setcancelable (FALSE); Dialog.setpositivebutton ("Restart", new Dialoginterface.onclicklistener () {public void OnClick (Dialoginterface dialog,
int which) {startgame ();}}); Dialog.setnegativebutton ("Cancel", new Dialoginterface.onclicklistener () {@Override public void OnClick (dialoginterface
dialog, int which) {//TODO auto-generated Method stub}});
Dialog.show (); }} private void Addrondomnum () {//clear this point and empty the previous emptypoints emptypoints.clear () Each time you add a random number to it;//iterate through all of the locations: that is, add a control points for each card (int y = 0; y < 4; y++) {for (int x = 0; x < 4; x + +) {if (Cardsmap[x][y].getnum () <= 0) {emptypoints.add (new point (x, Y));}}//Pass Randomly retrieves the card position from the list of stored points, sets the text attribute to the card, and can only save 2 or//through the Point object to act as the subscript role to control the two-dimensional array cardsmap that holds the card.
Then randomly assigns the point P = emptypoints.remove ((int) (Math.random () * emptypoints.size ()) to the card object to be positioned;
Cardsmap[p.x][p.y].setnum (Math.random () > 0.1? 2:4); }//Left private void Swipeleft () {Boolean add=false; for (int y = 0; y < 4; y++) {for (int x = 0; x < 4; x +) {fo R (int x1 = x + 1; x1 < 4; x1++) {if (Cardsmap[x1][y].getnum () > 0) {//Except for the first column, if there is a number greater than 0 if (cardsmap[x][y].getn Um () <= 0) {//If there is no cardsmap[x][y].setnum on the Left (Cardsmap[x1][y].getnum ());//Move the number on the right to the left cardsmap[x1][y].setnum (0);//
The right number 0 x--;
Add=true;
Break else if (Cardsmap[x][y].equals (Cardsmap[x1][y])) {Cardsmap[x][y].setnum (Cardsmap[x][y].getnum () * 2); cardsMap[x1][ Y].setnum (0);
Mainactivity.getmainactivity (). Addscore (Cardsmap[x][y].getnum ());
Add=true;
} break;  }} if (add) {addrondomnum (); Endgame ()//To determine whether to end}//Right private void Swiperight () {Boolean add=false; for (int y = 0; Y < 4; y++) {for (int x = 3; x >= 0; x--) {for (int x1 = x-1; x1 >= 0; x1--) {if (Cardsmap[x1][y].getnum () > 0) {i F (cardsmap[x][y].getnum () <= 0) {cardsmap[x][y].setnum (Cardsmap[x1][y].getnum ()); Cardsmap[x1][y].setnum (0); x + +
;
Add=true;
Break else if (Cardsmap[x][y].equals (Cardsmap[x1][y])) {Cardsmap[x][y].setnum (Cardsmap[x][y].getnum () * 2); cardsMap[x1][
Y].setnum (0);
Mainactivity.getmainactivity (). Addscore (Cardsmap[x][y].getnum ());
Add=true;
} break;
}} if (add) {addrondomnum (); Endgame ();}} private void Swipeup () {Boolean add=false; for (int x = 0; x < 4 + +) {for (int y = 0; y < 4; y++) {for (int y1 = y + 1; Y1 < 4; y1++) {if (Cardsmap[x][y1].getnum () > 0) {if (Cardsmap[x][y].getnum () <= 0) {cardsmap[x][Y].setnum (Cardsmap[x][y1].getnum ());
Cardsmap[x][y1].setnum (0);
y--;
Add=true;
Break else if (Cardsmap[x][y].equals (Cardsmap[x][y1])) {Cardsmap[x][y].setnum (Cardsmap[x][y].getnum () * 2); cardsMap[x][
Y1].setnum (0);
Mainactivity.getmainactivity (). Addscore (Cardsmap[x][y].getnum ());
Add=true;
} break;
}} if (add) {addrondomnum (); Endgame ();}} private void Swipedown () {Boolean add=false; for (int x = 0; x < 4 + +) {for (int y = 3; y >= 0; y--) {for (int y1 = y-1; Y1 >= 0; y1--) {if (Cardsmap[x][y1].getnum () > 0) {if (Cardsmap[x][y].getnum () <= 0) {cardsmap[x][y].setnum (cardsmap[x][y1
].getnum ());
Cardsmap[x][y1].setnum (0);
y++;
Add=true;
Break else if (Cardsmap[x][y].equals (Cardsmap[x][y1])) {Cardsmap[x][y].setnum (Cardsmap[x][y].getnum () * 2); cardsMap[x][
Y1].setnum (0);
Mainactivity.getmainactivity (). Addscore (Cardsmap[x][y].getnum ());
Add=true;
} break;
}} if (add) {addrondomnum (); Endgame ();}} }

6. Finally, do not forget to configure information in the manifest configuration file

<?xml version= "1.0" encoding= "Utf-8"?> <manifest xmlns:android= "http://schemas.android.com/apk/res/" Android "package=" com.jerry.game2048 "android:versioncode=" 1 "android:versionname=" 1.0 "> <uses-sdk android: minsdkversion= "android:targetsdkversion="/> <application android:allowbackup= "true" android:icon= "@ drawable/game2048 "android:label=" @string/app_name "android:theme=" @style/apptheme "> <activity android:name= "Com.jerry.game2048.MainActivity" android:label= "@string/app_name"//Set screen to vertical screen android:screenorientation= "Portrait" > </activity> <activity android:name= ". Splashactivity "android:label=" @string/title_activity_splash "> <intent-filter> <action android:name=" Android.intent.action.MAIN "/> <category android:name=" Android.intent.category.LAUNCHER "/> </ intent-filter> </activity> <activity android:name= ". Loginactivity "android:label=" @string/title_activity_login "> </activity> </application&Gt </manifest>

7. One of the monkey's animation effects achieved as follows:

Create a new Anim folder under the Res file
Create a new Anim_monky.xml layout file under the Anim folder

Anim_monky.xml

<?xml version= "1.0" encoding= "Utf-8"?> <set xmlns:android=
"http://schemas.android.com/apk/res/" Android ">
<translate
android:fromxdelta=" 0 "
android:toxdelta=" Android:fromydelta= "
0"
android:toydelta= " -5000"
android:duration= "4000"/>
<alpha android:fromalpha= 
"1"
Android:toalpha= "0"
android:duration= "5000"
/>
</set>

The effect chart is as follows:


The above is a small set to introduce Android 2048 small game to achieve code, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

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.