編輯:關於 Android 開發
《2048》是一款流傳很廣的數字遊戲,最早在 2014 年 3 月 20 日發行。原作者 Gabriele Cirulli 先在 GitHub 上釋出網頁版,之後被移植到各個平台。玩法承襲自《1024》與《小 3 傳奇》,規則簡單卻容易上癮。原始版本:https://gabrielecirulli.github.io/2048/
接下來我們一步步用 Android 原生 API 把它做出來。
新建名為 game2048 的專案,先寫最簡單的 activity_main.xml:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world" />
</LinearLayout>
把上方換成計分列,下方留給遊戲區,並用 layout_weight 讓遊戲區吃掉剩餘空間:
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<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" />
<TextView
android:id="@+id/tvScore"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<GridLayout
android:id="@+id/gameView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" >
</GridLayout>
</LinearLayout>
遊戲區的行為需要自訂,因此新增一個繼承 GridLayout 的 GameView:

package com.wuyudong.game2048;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.GridLayout;
public class GameView extends GridLayout {
public GameView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
initGameView();
}
public GameView(Context context, AttributeSet attrs) {
super(context, attrs);
initGameView();
}
public GameView(Context context) {
super(context);
initGameView();
}
private void initGameView() {
}
}
接著把版面中的 GridLayout 換成這個自訂類別(記得寫完整套件名稱):
<!-- 把自訂的 GameView 綁進版面 -->
<com.wuyudong.game2048.GameView
android:id="@+id/gameView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" >
</com.wuyudong.game2048.GameView>
2048 的操作就是上下左右四個方向的滑動。做法是在 ACTION_DOWN 記下起點,在 ACTION_UP 算出位移量,再比較 X 與 Y 軸的絕對值決定方向:
private void initGameView() {
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;
offsetY = event.getY() - startY;
if (Math.abs(offsetX) > Math.abs(offsetY)) {
if (offsetX < -5) {
System.out.println("left");
} else if (offsetX > 5) {
System.out.println("right");
}
} else {
if (offsetY < -5) {
System.out.println("up");
} else if (offsetY > 5) {
System.out.println("down");
}
}
break;
default:
break;
}
return true;
}
});
}
每一格就是一張卡片,用 FrameLayout 包一個 TextView 即可:
package com.wuyudong.game2048;
import android.content.Context;
import android.widget.FrameLayout;
import android.widget.TextView;
public class Card extends FrameLayout {
public Card(Context context) {
super(context);
lable = new TextView(getContext());
lable.setTextSize(32);
LayoutParams lp = new LayoutParams(-1, -1);
addView(lable, lp);
setNum(0);
}
private int num = 0;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
lable.setText(num + "");
}
public boolean equals(Card o) {
return getNum() == o.getNum();
}
private TextView lable;
}
在 onSizeChanged() 中取得實際尺寸後建立卡片,因為此時才能拿到正確的寬高:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
int cardWidth = (Math.min(w, h) - 10) / 4;
addCards(cardWidth, cardWidth);
}
private void addCards(int cardWith, 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, cardWith, cardHeight);
}
}
}
此時執行會發現一個問題:所有卡片都擠在同一列。

原因是 GridLayout 預設不會自動換行。在 initGameView() 中指定列數即可:
setColumnCount(4);

接著讓數字置中,並補上背景色與間距:
lable.setGravity(Gravity.CENTER); setBackgroundColor(0xffbbada0); // 整體背景 lable.setBackgroundColor(0x33ffffff); // 卡片背景 lp.setMargins(10, 10, 0, 0); // 卡片間距

開局時清空棋盤,再隨機放兩顆數字。做法是每次先掃出所有空格子,從中隨機挑一個填入,並讓 2 的出現機率略高於 4:
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
int cardWidth = (Math.min(w, h) - 10) / 4;
addCards(cardWidth, cardWidth);
startGame();
}
private void startGame() {
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
cardsMap[x][y].setNum(0);
}
}
addRandomNum();
addRandomNum();
}
private void addRandomNum() {
emptyPoints.clear(); // 每次都要清空
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 p = emptyPoints.remove((int) (Math.random() * emptyPoints.size()));
cardsMap[p.x][p.y].setNum(Math.random() > 0.1 ? 2 : 4);
}
每個方向的核心觀念相同:沿著移動方向掃描,遇到空格就往前挪,遇到相同數字就合併並歸零來源格。
private void swipeLeft() {
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) {
if (cardsMap[x][y].getNum() <= 0) {
cardsMap[x][y].setNum(cardsMap[x1][y].getNum());
cardsMap[x1][y].setNum(0);
x--;
break;
} else if (cardsMap[x][y].equals(cardsMap[x1][y])) {
cardsMap[x][y].setNum(cardsMap[x][y].getNum() * 2);
cardsMap[x1][y].setNum(0);
break;
}
}
}
}
}
}
private void swipeRight() {
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++;
break;
} else if (cardsMap[x][y].equals(cardsMap[x1][y])) {
cardsMap[x][y].setNum(cardsMap[x][y].getNum() * 2);
cardsMap[x1][y].setNum(0);
break;
}
}
}
}
}
}
private void swipeUp() {
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--;
break;
} else if (cardsMap[x][y].equals(cardsMap[x][y1])) {
cardsMap[x][y].setNum(cardsMap[x][y].getNum() * 2);
cardsMap[x][y1].setNum(0);
break;
}
}
}
}
}
}
private void swipeDown() {
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++;
break;
} else if (cardsMap[x][y].equals(cardsMap[x][y1])) {
cardsMap[x][y].setNum(cardsMap[x][y].getNum() * 2);
cardsMap[x][y1].setNum(0);
break;
}
}
}
}
}
}
private Card[][] cardsMap = new Card[4][4];
private List<Point> emptyPoints = new ArrayList<Point>();
這裡有個細節值得注意:往左或往上移動時若發生了位移,會把索引 x-- 或 y-- 退回一格,讓同一列能連續壓縮;往右或往下則是 x++、y++。少了這一步,一次滑動只能合併一組,手感就會不對。
MainActivity 負責把分數顯示到上方:
package com.wuyudong.game2048;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
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) findViewById(R.id.tvScore);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void clearScore() {
score = 0;
showScore();
}
public void showScore() {
tvScore.setText(score + "");
}
public void addScore(int s) {
score += s;
showScore();
}
private int score = 0;
private TextView tvScore;
private static MainActivity mainActivity = null;
public static MainActivity getMainActivity() {
return mainActivity;
}
}
GameView 在合併成功時呼叫 MainActivity.getMainActivity().addScore(...),並在每次有效移動後補上一顆隨機數字,遊戲就完整了。
只要棋盤上還有空格,或上下左右任一相鄰格數字相同,就代表還能繼續;反之則結束:
private void checkComplete() {
boolean complete = true;
ALL:
for (int y = 0; y < 4; y++) {
for (int x = 0; x < 4; x++) {
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]))) {
complete = false;
break ALL;
}
}
}
if (complete) {
new AlertDialog.Builder(getContext())
.setTitle("Oh")
.setMessage("Game Over!")
.setPositiveButton("restart", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
startGame();
}
}).show();
}
}

這個專案篇幅不大,卻涵蓋了自訂 View、GridLayout 動態排版、手勢辨識、二維陣列狀態管理與生命週期時機(為什麼要在 onSizeChanged 才建卡片)等常見課題,很適合當作 Android 入門的整合練習。若要繼續加值,可以替不同數字設計不同底色、加上最佳分數持久化,或補上滑動動畫。
Eclipse 掛上 Genymotion 插件:從安裝到啟動裝置的完整流程
Eclipse 掛上 Genymotion 插件的完整流程 先把我自己打包的 Genymotion 與 VirtualBox 放這裡,需要的可以取用:https://pa
Android Dialog 對話框各種用法詳解
Android Dialog 對話框各種用法詳解 本文整理 Android 中 Dialog 的常見用法,包含普通對話框、輸入框、列表、單選、多選與自訂佈局等六種形式。
Android View 事件體系入門:滑動、派送與衝突處理
Android View 事件體系重點整理 本章聚焦 View 的位置、滑動、事件派送與衝突處理,是理解 Android 觸摸互動的基礎。 View 的位置與 Motio
使用 Android Studio GsonFormat 外掛快速解析複雜 JSON
GsonFormat 外掛可以把 JSON 字串快速轉成 Java Bean,大幅減少手寫欄位與內部類別的時間,特別適合處理巢狀結構複雜的回應。安裝與使用先到 Setti