文章目录
Android 2048小游戏开发
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hello"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.zhanghao.game.MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/containner"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.zhanghao.game.MainActivity"
tools:ignore="MergeRootFrame" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/score_"
android:textSize="30sp" />
<TextView
android:id="@+id/tvScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp" />
</LinearLayout>
<com.zhanghao.game.GameView
android:id="@+id/gameView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" >
</com.zhanghao.game.GameView>
</LinearLayout>
MainActivity.java
package com.zhanghao.game;
import com.example.hello.R;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
public MainActivity() {
mainActivity = this;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvScore = (TextView) this.findViewById(R.id.tvScore);
}
public void clearScore() {
score = 0;
showScore();
}
public void showScore() {
tvScore.setText(score + "");
}
public void addScore(int addScore) {
score += addScore;
showScore();
}
private TextView tvScore;
private int score = 0;
private static MainActivity mainActivity = null;
public static MainActivity getMainActivity() {
return mainActivity;
}
}
GameView.java
package com.zhanghao.game;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.GridLayout;
@SuppressLint("ClickableViewAccessibility")
public class GameView extends GridLayout {
public GameView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
// TODO Auto-generated constructor stub
initGameView();
}
public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
initGameView();
}
public GameView(Context context) {
super(context);
// TODO Auto-generated constructor stub
initGameView();
}
private void initGameView() {
setColumnCount(4);
setBackgroundColor(0xffbbada0);
setOnTouchListener(new OnTouchListener() {
private float startX, startY, offsetX, offsetY;
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = event.getX();
startY = event.getY();
break;
case MotionEvent.ACTION_UP:
offsetX = event.getX() - startX;
offsetY = event.getY() - startY;
if (Math.abs(offsetX) > Math.abs(offsetY)) {
if (offsetX < -5) {
// System.out.println("left");
swipeLeft();
} else if (offsetX > 5) {
// System.out.println("right");
swipeRight();
}
} else {
if (offsetY < -5) {
// System.out.println("up");
swipeUp();
} else if (offsetY > 5) {
// System.out.println("down");
swipeDown();
}
}
break;
default:
break;
}
return true;
}
});
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
// TODO Auto-generated method stub
super.onSizeChanged(w, h, oldw, oldh);
int cardWidth = (Math.min(w, h) - 10) / 4;
addCard(cardWidth, cardWidth);
startGame();
}
private void startGame() {
MainActivity.getMainActivity().clearScore();
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
cardMaps[x][y].setNum(0);
}
}
addRandomNum();
addRandomNum();
}
private void addCard(int cardWidth, int cardHeight) {
Card card;
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
card = new Card(getContext());
card.setNum(0);
addView(card, cardWidth, cardHeight);
cardMaps[x][y] = card;
}
}
}
private void addRandomNum() {
emptyPoints.clear();
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
if (cardMaps[x][y].getNum() <= 0) {
emptyPoints.add(new Point(x, y));
}
}
}
Point point = emptyPoints.remove((int) (Math.random() * emptyPoints.size()));
cardMaps[point.x][point.y].setNum(Math.random() > 0.1 ? 2 : 4);
}
private void swipeDown() {
boolean merge = false;
for (int x = 0; x < 4; x++) {
for (int y = 3; y >= 0; y--) {
for (int y1 = y - 1; y1 >= 0; y1--) {
if (cardMaps[x][y1].getNum() > 0) {
if (cardMaps[x][y].getNum() <= 0) {
cardMaps[x][y].setNum(cardMaps[x][y1].getNum());
cardMaps[x][y1].setNum(0);
y++;
merge = true;
} else if (cardMaps[x][y].equals(cardMaps[x][y1])) {
cardMaps[x][y].setNum(cardMaps[x][y1].getNum() * 2);
cardMaps[x][y1].setNum(0);
MainActivity.getMainActivity().addScore(cardMaps[x][y].getNum());
merge = true;
}
break;
}
}
}
}
if (merge) {
addRandomNum();
checkComplete();
}
}
private void swipeUp() {
boolean merge = false;
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 4; y++) {
for (int y1 = y + 1; y1 < 4; y1++) {
if (cardMaps[x][y1].getNum() > 0) {
if (cardMaps[x][y].getNum() <= 0) {
cardMaps[x][y].setNum(cardMaps[x][y1].getNum());
cardMaps[x][y1].setNum(0);
y--;
merge = true;
} else if (cardMaps[x][y].equals(cardMaps[x][y1])) {
cardMaps[x][y].setNum(cardMaps[x][y1].getNum() * 2);
cardMaps[x][y1].setNum(0);
MainActivity.getMainActivity().addScore(cardMaps[x][y].getNum());
merge = true;
}
break;
}
}
}
}
if (merge) {
addRandomNum();
checkComplete();
}
}
private void swipeRight() {
boolean merge = false;
for (int y = 0; y < 4; y++) {
for (int x = 3; x >= 0; x--) {
for (int x1 = x - 1; x1 >= 0; x1--) {
if (cardMaps[x1][y].getNum() > 0) {
if (cardMaps[x][y].getNum() <= 0) {
cardMaps[x][y].setNum(cardMaps[x1][y].getNum());
cardMaps[x1][y].setNum(0);
x++;
merge = true;
} else if (cardMaps[x][y].equals(cardMaps[x1][y])) {
cardMaps[x][y].setNum(cardMaps[x1][y].getNum() * 2);
cardMaps[x1][y].setNum(0);
MainActivity.getMainActivity().addScore(cardMaps[x][y].getNum());
merge = true;
}
break;
}
}
}
}
if (merge) {
addRandomNum();
checkComplete();
}
}
private void swipeLeft() {
boolean merge = false;
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
for (int x1 = x + 1; x1 < 4; x1++) {
if (cardMaps[x1][y].getNum() > 0) {
if (cardMaps[x][y].getNum() <= 0) {
cardMaps[x][y].setNum(cardMaps[x1][y].getNum());
cardMaps[x1][y].setNum(0);
x--;
merge = true;
} else if (cardMaps[x][y].equals(cardMaps[x1][y])) {
cardMaps[x][y].setNum(cardMaps[x1][y].getNum() * 2);
cardMaps[x1][y].setNum(0);
MainActivity.getMainActivity().addScore(cardMaps[x][y].getNum());
merge = true;
}
break;
}
}
}
}
if (merge) {
addRandomNum();
checkComplete();
}
}
private void checkComplete() {
boolean complete=true;
ALL:
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
if (cardMaps[x][y].getNum() == 0 || (x > 0 && cardMaps[x][y].equals(cardMaps[x - 1][y]))
|| (x < 3 && cardMaps[x][y].equals(cardMaps[x + 1][y]))
|| (y > 0 && cardMaps[x][y].equals(cardMaps[x][y - 1]))
|| (y < 3 && cardMaps[x][y].equals(cardMaps[x][y + 1]))
) {
complete=false;
break ALL;
}
}
}
if (complete) {
new AlertDialog.Builder(getContext()).setTitle("你好").setMessage("游戏结束!").setPositiveButton("重来", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
startGame();
}
}).show();
}
}
private Card[][] cardMaps = new Card[4][4];
private List<Point> emptyPoints = new ArrayList<Point>();
}
Card.java
package com.zhanghao.game;
import android.content.Context;
import android.view.Gravity;
import android.widget.FrameLayout;
import android.widget.TextView;
public class Card extends FrameLayout {
public Card(Context context) {
super(context);
// TODO Auto-generated constructor stub
label = new TextView(getContext());
label.setTextSize(50);
label.setGravity(Gravity.CENTER);
label.setBackgroundColor(0x33ffffff);
LayoutParams lp = new LayoutParams(-1, -1);
lp.setMargins(10, 10, 0, 0);
addView(label, lp);
setNum(0);
}
private int num = 0;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
if (num <= 0) {
label.setText("");
} else {
label.setText(num + "");
}
}
public boolean equals(Card card) {
return getNum() == card.getNum();
}
private TextView label;
}