Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

動手做一款 Android 拼圖小遊戲:自定義 View 與動畫的綜合練習

編輯:關於 Android 程式設計

一、需求描述

拼圖是個經典的益智玩法:把一張圖片切成若干塊、打亂之後,讓玩家在限定時間內還原。這個案例的規則很直覺——隨意點選兩塊即可交換位置,不需要拖曳,因此手機操作成本很低。關卡升級時,切圖的份數也跟著增加(3×3 → 4×4 → 5×5……),難度自然遞進。

核心功能拆成六項:

1. 依關卡動態切割圖片成指定份數;
2. 任選兩塊能正確交換;
3. 交換過程要有動畫過渡;
4. 過關判定與關卡回呼;
5. 時間邏輯(含逾時處理);
6. 遊戲的結束與暫停 / 續玩。

二、功能分析與實作要點

切圖工具。直觀上可以準備 3×3、4×4 各一組切好的圖,但這樣資源會迅速失控、難以維護。更好的做法是只放一張原圖,執行期用 Bitmap.createBitmap() 動態裁切,參數化「切成幾份」。

自定義容器。用一個自訂的 RelativeLayout 排列所有拼塊,負責計算每塊的寬高、間距與內邊距,並處理點擊。

交換與動畫。點擊選中兩塊後,先建立一個「動畫層」,複製兩個 ImageView 到動畫層上播放位移動畫;動畫開始時隱藏原本的 View,結束後真正交換資料並還原顯示。

過關與計時。用 Handler 每秒回呼更新剩餘時間;每次交換後比對每塊的 index 與其所在位置是否一致,全部一致即過關。

暫停與續玩。onPause() 時移除計時訊息,onResume() 時重新送出。

三、概要設計

整個專案只有三個主要角色:

· ImagePiece:資料物件,記錄「這是第幾塊」與對應的 Bitmap。
· ImageSplitterUtil:切圖工具類,提供 splitImage(bitmap, piece)。
· GamePintuLayout:自定義容器,負責排版、亂序、點擊交換、動畫與過關判定。

3.1 ImagePiece.java

package com.example.utils;

import android.graphics.Bitmap;

public class ImagePiece {
    private int index;        // 當前是第幾塊(正確位置)
    private Bitmap bitmap;    // 這塊的圖

    public ImagePiece() {}

    public ImagePiece(int index, Bitmap bitmap) {
        this.index = index;
        this.bitmap = bitmap;
    }

    public int getIndex() { return index; }
    public void setIndex(int index) { this.index = index; }
    public Bitmap getBitmap() { return bitmap; }
    public void setBitmap(Bitmap bitmap) { this.bitmap = bitmap; }
}

3.2 ImageSplitterUtil.java

package com.example.utils;

import java.util.ArrayList;
import java.util.List;
import android.graphics.Bitmap;

public class ImageSplitterUtil {

    /** 把 bitmap 切成 piece × piece 塊,回傳 List */
    public static List<ImagePiece> splitImage(Bitmap bitmap, int piece) {
        List<ImagePiece> imagePieces = new ArrayList<ImagePiece>();
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        // 以短邊作為切割基準,保證每塊是正方形
        int pieceWidth = Math.min(width, height) / piece;

        for (int i = 0; i < piece; i++) {        // 列
            for (int j = 0; j < piece; j++) {    // 行
                ImagePiece imagePiece = new ImagePiece();
                imagePiece.setIndex(j + i * piece);   // 記錄正確位置的序號
                int x = j * pieceWidth;
                int y = i * pieceWidth;
                imagePiece.setBitmap(
                        Bitmap.createBitmap(bitmap, x, y, pieceWidth, pieceWidth));
                imagePieces.add(imagePiece);
            }
        }
        return imagePieces;
    }
}

index 是後面過關判定的依據:只要每個格子裡的 ImagePiece.index 等於它的位置序號,就代表還原成功。

3.3 GamePintuLayout.java

以下列出關鍵片段。開頭是欄位與初始化:

public class GamePintuLayout extends RelativeLayout implements OnClickListener {

    private int mColumn = 3;          // 目前的切割級數
    private int mPadding;             // 容器內邊距
    private int mMargin = 3;          // 拼塊間距(dp)
    private ImageView[] mGamePintuItems;
    private int mItemWidth;
    private Bitmap mBitmap;           // 原圖
    private List<ImagePiece> mItemBitmaps;
    private boolean once;
    private int mWidth;               // 面板寬度(取寬高最小值,保持正方形)

    private int level = 1;
    private static final int TIME_CHANGED = 0x110;
    private static final int NEXT_LEVEL   = 0x111;
    private int mTime;
    private boolean isTimeEnabled;
    private boolean isGameSuccess;
    private boolean isGameOver;
    private boolean isPause;

    public interface GamePintuListener {
        void nextLevel(int nextLevel);
        void timechanged(int currentTime);
        void gameover();
    }
    public GamePintuListener mListener;

    public void setOnGamePintuListener(GamePintuListener mListener) {
        this.mListener = mListener;
    }
    public void setTimeEnabled(boolean isTimeEnabled) {
        this.isTimeEnabled = isTimeEnabled;
    }

Handler 負責計時與過關兩個訊息:

private Handler mHandler = new Handler() {
    public void handleMessage(android.os.Message msg) {
        switch (msg.what) {
            case TIME_CHANGED:
                if (isGameSuccess || isGameOver || isPause) return;
                if (mListener != null) {
                    mListener.timechanged(mTime);
                    if (mTime == 0) {
                        isGameOver = true;
                        mListener.gameover();
                        return;
                    }
                }
                mTime--;
                mHandler.sendEmptyMessageDelayed(TIME_CHANGED, 1000);
                break;
            case NEXT_LEVEL:
                level = level + 1;
                if (mListener != null) {
                    mListener.nextLevel(level);
                } else {
                    nextLevel();
                }
                break;
        }
    }
};

初始化時做單位換算(dp → px)並取內邊距最小值:

private void init() {
    mMargin = (int) TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP, 3, getResources().getDisplayMetrics());
    mPadding = min(getPaddingLeft(), getPaddingRight(),
                   getPaddingTop(), getPaddingBottom());
}

private int min(int... params) {
    int min = params[0];
    for (int param : params) {
        if (param < min) min = param;
    }
    return min;
}

在 onMeasure 中完成一次性初始化,並強制把面板量成正方形:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    mWidth = Math.min(getMeasuredHeight(), getMeasuredWidth());
    if (!once) {
        initBitmap();      // 切圖 + 亂序
        initItem();        // 建立 ImageView 並排版
        checkTimeEnable(); // 依需要啟動計時
        once = true;
    }
    setMeasuredDimension(mWidth, mWidth);
}

private void checkTimeEnable() {
    if (isTimeEnabled) {
        contTimeBaseLevel();
        mHandler.sendEmptyMessage(TIME_CHANGED);
    }
}

// 每升一關,時間以 2 的次方倍數增加
private void contTimeBaseLevel() {
    mTime = (int) Math.pow(2, level) * 60;
}

切圖與亂序:

private void initBitmap() {
    if (mBitmap == null) {
        mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
    }
    mItemBitmaps = ImageSplitterUtil.splitImage(mBitmap, mColumn);
    // 用 sort 打亂順序
    Collections.sort(mItemBitmaps, new Comparator<ImagePiece>() {
        public int compare(ImagePiece a, ImagePiece b) {
            return Math.random() > 0.5 ? 1 : -1;
        }
    });
}

排版時用 tag 記住「格子位置_index」,這是交換與過關判定的關鍵:

private void initItem() {
    mItemWidth = (mWidth - mPadding * 2 - mMargin * (mColumn - 1)) / mColumn;
    mGamePintuItems = new ImageView[mColumn * mColumn];

    for (int i = 0; i < mGamePintuItems.length; i++) {
        ImageView item = new ImageView(getContext());
        item.setOnClickListener(this);
        item.setImageBitmap(mItemBitmaps.get(i).getBitmap());
        mGamePintuItems[i] = item;
        item.setId(i + 1);
        // tag 格式:"格子位置_圖片的 index"
        item.setTag(i + "_" + mItemBitmaps.get(i).getIndex());

        RelativeLayout.LayoutParams lp =
                new RelativeLayout.LayoutParams(mItemWidth, mItemWidth);
        if ((i + 1) % mColumn != 0) {                 // 不是最右列
            lp.rightMargin = mMargin;
        }
        if (i % mColumn != 0) {                       // 不是最左列
            lp.addRule(RelativeLayout.RIGHT_OF, mGamePintuItems[i - 1].getId());
        }
        if ((i + 1) > mColumn) {                      // 不是第一行
            lp.topMargin = mMargin;
            lp.addRule(RelativeLayout.BELOW, mGamePintuItems[i - mColumn].getId());
        }
        addView(item, lp);
    }
}

點擊處理:第一次點擊加上紅色濾鏡做「選中」提示,第二次點擊觸發交換;重複點同一塊則取消選中。

private ImageView mFirst;
private ImageView mSecond;

public void onClick(View v) {
    if (isAniming) return;                 // 動畫播放期間忽略點擊
    if (mFirst == v) {                     // 再次點擊同一塊:取消選中
        mFirst.setColorFilter(null);
        mFirst = null;
        return;
    }
    if (mFirst == null) {
        mFirst = (ImageView) v;
        mFirst.setColorFilter(Color.parseColor("#55FF0000"));
    } else {
        mSecond = (ImageView) v;
        exchangeView();
    }
}

交換動畫是這個案例最有趣的部分——用一個覆蓋在上方的動畫層承載兩個複製品,讓它們互相飛向對方:

private RelativeLayout mAnimLayout;
private boolean isAniming;

private void exchangeView() {
    mFirst.setColorFilter(null);
    setUpAnimLayout();                      // 準備動畫層

    ImageView first = new ImageView(getContext());
    final Bitmap firstBitmap = mItemBitmaps
            .get(getImageIdByTag((String) mFirst.getTag())).getBitmap();
    first.setImageBitmap(firstBitmap);
    LayoutParams lp = new LayoutParams(mItemWidth, mItemWidth);
    lp.leftMargin = mFirst.getLeft() - mPadding;
    lp.topMargin  = mFirst.getTop()  - mPadding;
    first.setLayoutParams(lp);
    mAnimLayout.addView(first);

    ImageView second = new ImageView(getContext());
    final Bitmap secondBitmap = mItemBitmaps
            .get(getImageIdByTag((String) mSecond.getTag())).getBitmap();
    second.setImageBitmap(secondBitmap);
    LayoutParams lp2 = new LayoutParams(mItemWidth, mItemWidth);
    lp2.leftMargin = mSecond.getLeft() - mPadding;
    lp2.topMargin  = mSecond.getTop()  - mPadding;
    second.setLayoutParams(lp2);
    mAnimLayout.addView(second);

    // 兩塊互相平移到對方位置
    TranslateAnimation anim = new TranslateAnimation(0,
            mSecond.getLeft() - mFirst.getLeft(), 0, mSecond.getTop() - mFirst.getTop());
    anim.setDuration(300);
    anim.setFillAfter(true);
    first.startAnimation(anim);

    TranslateAnimation animSecond = new TranslateAnimation(0,
            -mSecond.getLeft() + mFirst.getLeft(), 0, -mSecond.getTop() + mFirst.getTop());
    animSecond.setDuration(300);
    animSecond.setFillAfter(true);
    second.startAnimation(animSecond);

    anim.setAnimationListener(new AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
            mFirst.setVisibility(View.INVISIBLE);   // 動畫期間藏起真身
            mSecond.setVisibility(View.INVISIBLE);
            isAniming = true;
        }
        @Override
        public void onAnimationRepeat(Animation animation) { }

        @Override
        public void onAnimationEnd(Animation animation) {
            // 動畫結束後才真正交換圖與 tag
            String firstTag  = (String) mFirst.getTag();
            String secondTag = (String) mSecond.getTag();
            mFirst.setImageBitmap(secondBitmap);
            mSecond.setImageBitmap(firstBitmap);
            mFirst.setTag(secondTag);
            mSecond.setTag(firstTag);
            mFirst.setVisibility(View.VISIBLE);
            mSecond.setVisibility(View.VISIBLE);
            mFirst = mSecond = null;
            checkSuccess();                         // 順便檢查是否過關
            isAniming = false;
        }
    });
}

private void setUpAnimLayout() {
    if (mAnimLayout == null) {
        mAnimLayout = new RelativeLayout(getContext());
        addView(mAnimLayout);
    } else {
        mAnimLayout.removeAllViews();
    }
}

過關判定:逐一比對每個格子的 tag 中的 index 是否等於它的位置序號。

private void checkSuccess() {
    boolean isSuccess = true;
    for (int i = 0; i < mGamePintuItems.length; i++) {
        ImageView imageView = mGamePintuItems[i];
        if (getImageIndexByTag((String) imageView.getTag()) != i) {
            isSuccess = false;
        }
    }
    if (isSuccess) {
        isGameSuccess = true;
        mHandler.removeMessages(TIME_CHANGED);
        Toast.makeText(getContext(), "Success, level up!", Toast.LENGTH_LONG).show();
        mHandler.sendEmptyMessage(NEXT_LEVEL);
    }
}

public int getImageIdByTag(String tag) {
    return Integer.parseInt(tag.split("_")[0]);     // 格子位置
}
public int getImageIndexByTag(String tag) {
    return Integer.parseInt(tag.split("_")[1]);     // 圖片的 index
}

關卡切換與暫停 / 續玩:

public void nextLevel() {
    this.removeAllViews();     // 移除舊的拼塊
    mAnimLayout = null;        // 動畫層也要丟掉
    mColumn++;                 // 增加切割級數
    isGameSuccess = false;
    checkTimeEnable();
    initBitmap();              // 重新切圖、重新亂序
    initItem();                // 重新排版
}

public void restart() {
    isGameOver = false;
    mColumn--;
    nextLevel();
}

public void pause() {
    isPause = true;
    mHandler.removeMessages(TIME_CHANGED);
}

public void resume() {
    if (isPause) {
        isPause = false;
        mHandler.sendEmptyMessage(TIME_CHANGED);
    }
}

3.4 MainActivity.java:把回呼接到 UI

public class MainActivity extends Activity {

    private GamePintuLayout mGamePintuLayout;
    private TextView mLevel;
    private TextView mTime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTime  = (TextView) findViewById(R.id.id_time);
        mLevel = (TextView) findViewById(R.id.id_level);
        mGamePintuLayout = (GamePintuLayout) findViewById(R.id.id_gamepintu);
        mGamePintuLayout.setTimeEnabled(true);

        mGamePintuLayout.setOnGamePintuListener(new GamePintuListener() {
            @Override
            public void timechanged(int currentTime) {
                mTime.setText("" + currentTime);
            }

            @Override
            public void nextLevel(final int nextLevel) {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("GAME INFO").setMessage("LEVEL UP!!!")
                        .setPositiveButton("NEXT LEVEL", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mGamePintuLayout.nextLevel();
                                mLevel.setText("" + nextLevel);
                            }
                        }).show();
            }

            @Override
            public void gameover() {
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("GAME INFO").setMessage("GAME OVER!!!")
                        .setPositiveButton("RESTART", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                mGamePintuLayout.restart();
                            }
                        })
                        .setNegativeButton("QUIT", new OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                finish();
                            }
                        }).show();
            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        mGamePintuLayout.pause();      // 離開時暫停計時
    }

    @Override
    protected void onResume() {
        super.onResume();
        mGamePintuLayout.resume();     // 回來時繼續
    }
}

3.5 版面配置

<RelativeLayout 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"
    tools:context="${relativePackage}.${activityClass}" >

    <com.example.game_pintu.view.GamePintuLayout
        android:id="@+id/id_gamepintu"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:padding="3dp" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/id_gamepintu" >

        <TextView
            android:id="@+id/id_level"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:background="@drawable/textbg"
            android:gravity="center"
            android:padding="4dp"
            android:text="1"
            android:textColor="#EA7821"
            android:textSize="10sp" />

        <TextView
            android:id="@+id/id_time"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_alignParentRight="true"
            android:background="@drawable/textbg"
            android:gravity="center"
            android:padding="4dp"
            android:text="50"
            android:textColor="#EA7821"
            android:textSize="10sp" />
    </RelativeLayout>
</RelativeLayout>

倒數與關卡用的圓形背景 drawable/textbg.xml:

<shape xmlns:android="https://schemas.android.com/apk/res/android"
    android:shape="oval" >
    <stroke android:width="2px" android:color="#1579DB" />
    <solid android:color="#B4CDE6" />
</shape>

四、實測結果

開始遊戲:

拼回原圖:

過關並進入下一關(切割級數增加):

五、可以再加強的地方

這個版本聚焦在核心玩法,仍有幾處現實專案會補強:亂序時應排除「剛好本身就是完成狀態」的初始盤面;Handler 若在 Activity 銷毀後仍發送訊息會造成記憶體洩漏,正式版宜在 onDestroy() 中移除 callbacks;此外可加入步數統計、最佳紀錄與提示功能,讓遊玩體驗更完整。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved