안 드 로 이 드 모방 2048 작은 게임 실현 코드

처음에 Splash 인터페이스 에 들 어 갔 을 때:
1.SplashActivity.Java(2 초 후 시작 화면 에 들 어 갑 니 다.Splash 인터페이스의 레이아웃 은 하나의 그림 만 있 습 니 다.블 로그 후에 보 여 드 리 겠 습 니 다)

public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new Thread(new Runnable() { 
@Override
public void run() {
try {
Thread.sleep(2000);
Intent intent=new Intent(SplashActivity.this, LoginActivity.class);
startActivity(intent);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finish();
}
}).start();
}
}
2.LoginActivity(로그 인 인터페이스)

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() {
//       
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("user", MODE_PRIVATE);
String number=sharedPreferences.getString("number", "");
int a,b;
if (number=="") {
a=0;//      
}else {
a=Integer.parseInt(number);
}
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, "    ", Toast.LENGTH_SHORT).show(); 
}
}
}
if (b==a) {
Toast.makeText(LoginActivity.this, "     ", Toast.LENGTH_SHORT).show();
}
}
});
//       
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,"         ", Toast.LENGTH_SHORT).show();
}else {
account="account"+b;
password="password"+b;
a++;
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString(account,etAcount.getText().toString());
editor.putString(password,etPassword.getText().toString());
editor.putString("number",a+"");
editor.commit();
Toast.makeText(LoginActivity.this,"    ", Toast.LENGTH_SHORT).show();
}
}else {
Toast.makeText(LoginActivity.this,"      ", Toast.LENGTH_SHORT).show();
}
}
});
} 
}
LoginActivity 의 레이아웃 은 다음 과 같 습 니 다.

<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="     " />
<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="     " />
<Button 
android:id="@+id/btn_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="  "
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="  "
android:layout_below="@id/et_pwd"
android:layout_toRightOf="@id/btn_login"
android:layout_marginTop="10dp"
android:layout_marginLeft="60dp"/>
3.MainActivity.java(홈 페이지)

public class MainActivity extends Activity {
private TextView tvScore;
private Animation animation;
private static MainActivity mainActivity = null;
private int score = 0;
private ImageView imageView;
private GameView gameView;
public static MainActivity getMainActivity() {
return mainActivity;
}
public MainActivity() {
mainActivity = this;
}
@Override
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://    ,     
animation=AnimationUtils.loadAnimation(this,R.anim.anim_monkey);
AlertDialog.Builder dialog2=new AlertDialog.Builder(this);
dialog2.setTitle("  +  ");
dialog2.setMessage("            !!      ");
dialog2.setPositiveButton("       ", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
imageView.startAnimation(animation);// ImageView    
}
});
dialog2.setNegativeButton("   ~", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog2.show();
break;
case R.id.btn_quit://         
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setTitle("  :");
dialog.setMessage("  ,        ?");
dialog.setPositiveButton("  ", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
System.exit(0);
}
});
dialog.setNegativeButton("  ", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
dialog.show();
break;
default:
break;
}
}
public void clearScore() {//    
score = 0;
showScore();
}
public void showScore() {//    
tvScore.setText(score + "");
}
public void addScore(int s) {//    
score += s;
showScore();
}
}
MainActivity 의 레이아웃 파일

<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:orientation="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"
android:layout_height="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:orientation="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="    "
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="    "
android:layout_marginRight="20dp"
android:textSize="20sp"
android:onClick="onClick"/>
</LinearLayout>
<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="        ,          ,          ,    ,             ,      ,       ,  "/>
</LinearLayout>
4.Card.java(카드 종류)

public class Card extends FrameLayout {
private int num=0;
private TextView label;
public Card(Context context) {
super(context);
label=new TextView(getContext()); 
label.setTextSize(32);
label.setGravity(Gravity.CENTER);
label.setBackgroundColor(0x33ffffff);//         
LayoutParams lp=new LayoutParams(-1,-1);//       layout  textView      
lp.setMargins(10, 10, 0, 0);//    
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+"");
}
}
//  equals  ,             
public boolean equals(Card o) {
return getNum()==o.getNum();
} 
}
5.GameView.java(주요 논리)

public class GameView extends GridLayout {
private Card[][] cardsMap = new Card[4][4];
//    cardsMap    Point    
private List<Point> emptyPoints = new ArrayList<Point>();
public GameView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initGameView();
}
public GameView(Context context) {
super(context);
initGameView();
}
public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
initGameView();
}
private void initGameView() {
setColumnCount(4);
setBackgroundColor(0xffddada0);
setOnTouchListener(new OnTouchListener() {
//          
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;//   0      
offsetY = event.getY() - startY;//   0     
if (Math.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;
}
});
}
//       
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
//                             
//                  ,            
super.onSizeChanged(w, h, oldw, oldh);
//         ,-10            ,       4          
int cardWidth = (Math.min(w, h) - 10) / 4;
addCards(cardWidth, cardWidth);
startGame();
}
//    ,  4*4   
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);
//                       
cardsMap[x][y] = c;
}
}
}
//    ,   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();
}
//      
private void endGame(){
boolean isfull=true;//             
for (int x = 0; x < 4; x++) {
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("    !       ?");
dialog.setCancelable(false);
dialog.setPositiveButton("    ",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
startGame();
}
});
dialog.setNegativeButton("  ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
dialog.show();
}
}
private void addRondomNum() {
//   point  ,                emptyPoints
emptyPoints.clear();
//          :              Point 
for (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));
}
}
}
//          Point List      Card   ,    card      ,     2 
//  point               card     cardsMap,         card    
Point p = emptyPoints.remove((int) (Math.random() * emptyPoints.size()));
cardsMap[p.x][p.y].setNum(Math.random() > 0.1 ? 2 : 4);
}
//  
private void swipeLeft() {
boolean add=false;
for (int y = 0; y < 4; y++) { 
for (int x = 0; x < 4; x++) {
for (int x1 = x + 1; x1 < 4; x1++) {
if (cardsMap[x1][y].getNum() > 0) {//         ,         0
if (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 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) {
if (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; x++) {
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; x++) {
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.마지막 으로 목록 프로필 에 정 보 를 설정 하 는 것 을 잊 지 마 세 요.

<?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="17"
android:targetSdkVersion="21" />
<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"
//       
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>
</manifest>
7.그 중에서 하늘 원숭이 의 애니메이션 효 과 는 다음 과 같다.
res 파일 아래 에 anim 폴 더 를 새로 만 듭 니 다.
anim 폴 더 아래 에 anim 새로 만 들 기monky.xml 레이아웃 파일
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="40"
android:fromYDelta="0"
android:toYDelta="-5000"
android:duration="4000"/>
<alpha 
android:fromAlpha="1"
android:toAlpha="0"
android:duration="5000"
/>
</set>
효과 도 는 다음 과 같다.




위 에서 말 한 것 은 편집장 이 여러분 에 게 소개 한 안 드 로 이 드 모방 2048 작은 게임 실현 코드 입 니 다.여러분 에 게 도움 이 되 기 를 바 랍 니 다.궁금 한 점 이 있 으 면 저 에 게 메 시 지 를 남 겨 주세요.편집장 은 제때에 답 해 드 리 겠 습 니 다.여기 서도 저희 사이트 에 대한 여러분 의 지지 에 감 사 드 립 니 다!

좋은 웹페이지 즐겨찾기