Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 遊戲 >> Android 遊戲開發

Android 遊戲開發(17):自訂手勢實戰——手勢庫的建立、比對與遊戲應用

編輯:Android 遊戲開發

先聊一個常被忽略的選擇:該用哪一版 SDK?

寫 Android 遊戲時,多數直覺是「抓最新版 SDK 就對了」,但我反而常用 1.5、1.6 這類舊版本來開發。原因其實很務實。

首先,Android SDK 是向下相容的。能在低版本跑起來的程式,放到高版本機器上幾乎不會出問題;反過來則不然。其次,低版本能覆蓋更多老機型,等於把可觸及的使用者基盤拉大。

還有一個更關鍵的理由:新版 SDK 的底層通常更成熟、效能更好。同一款遊戲在舊機上會卡,換到新機就順順的——但這也形成一個陷阱。如果你一開始就用高版本開發,你根本看不出自己的程式在效能與記憶體上真實的表現如何;用低版本開發,反而會逼你把每一幀、每一次配置都寫得夠精實。等它在舊版本上都跑得順,換到新機器自然是享受。

結論:只要遊戲不需要更新的 API,以 SDK 1.5/1.6 為基準開發是很值得推薦的選擇。

觸控手勢之外,還有另一種玩法

上一篇談的是觸控手勢,但那終究只是系統把一組觸屏動作包裝好丟給你。真正有意思的是「輸入法手勢辨識」——也就是手機九宮格解鎖、畫個字母啟動 App 背後的那套技術。手勢是你自己定義的,系統只負責比對。

把這東西放進遊戲裡會很好玩:畫一個圓形換背景,畫一個 X 退出遊戲,畫個三角形開啟隱藏關卡。玩家會覺得這遊戲「有靈魂」。

本篇要掌握兩件事:

  1. 如何建立手勢、刪除手勢,並從 SD 卡讀回手勢檔。
  2. 手勢建立之後,如何把它比對出來。

三個關鍵角色

  • GestureOverlayView:一個手寫繪圖區,玩家手指畫的軌跡都落在這層上面。
  • GestureLibrary:手勢倉庫,負責手勢的儲存、刪除、讀取與比對。
  • Prediction:比對結果。它帶有 name(對應的手勢名稱)與 score(相似度)。

另外要理解「筆畫」這個概念——它和寫字的筆畫是同一回事。筆畫類型有兩種:

  • 單一筆畫(GESTURE_STROKE_TYPE_SINGLE):手指從接觸螢幕到離開,一氣呵成算一筆。
  • 多筆畫(GESTURE_STROKE_TYPE_MULTIPLE):在一段緊接的時間內可以寫好幾筆,最後合併成一個手勢。

版面配置

畫面由上到下是 TextView、EditText,接著是一個 RelativeLayout,裡頭疊了自訂的 SurfaceView 與鋪滿全屏的 GestureOverlayView。

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView
        android:id="@+id/himi_tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textSize="15sp"
        android:textColor="#FFFFFF00" />

    <EditText
        android:id="@+id/himi_edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1">

        <com.himi.MySurfaceView
            android:id="@+id/view3d"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" />

        <android.gesture.GestureOverlayView
            android:id="@+id/himi_gesture"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_weight="1.0" />
    </RelativeLayout>
</LinearLayout>

GestureOverlayView 這裡只定義了寬高,其餘重要屬性我放在程式碼裡設定,XML 當然也做得到。

主程式骨架

/**
 * 輸入法手勢辨識
 * 注意:android.gesture 這個套件從 API 4(SDK 1.6)才開始支援。
 * 提醒:手勢預設存到 SD 卡,別忘了在 AndroidManifest.xml 加上讀寫權限!
 */
public class MainActivity extends Activity {
    private GestureOverlayView gov;   // 手寫繪圖區
    private Gesture gesture;          // 手寫 instance
    private GestureLibrary gestureLib;// 手勢倉庫
    private TextView tv;
    private EditText et;
    private String path;              // 手勢檔路徑
    private File file;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                             WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);

        tv  = (TextView) findViewById(R.id.himi_tv);
        et  = (EditText) findViewById(R.id.himi_edit);
        gov = (GestureOverlayView) findViewById(R.id.himi_gesture);

        // 筆畫類型:改成 GESTURE_STROKE_TYPE_SINGLE 就只吃單一筆畫
        gov.setGestureStrokeType(GestureOverlayView.GESTURE_STROKE_TYPE_MULTIPLE);

        path = new File(Environment.getExternalStorageDirectory(), "gestures").getAbsolutePath();
        file = new File(path);
        gestureLib = GestureLibraries.fromFile(path);

        gov.addOnGestureListener(new OnGestureListener() {
            // 開始畫手勢時觸發
            @Override
            public void onGestureStarted(GestureOverlayView overlay, MotionEvent event) {
                tv.setText("請在緊接的時間內用兩筆畫完成一個手勢!");
            }

            // 手勢形成時觸發
            @Override
            public void onGestureEnded(GestureOverlayView overlay, MotionEvent event) {
                gesture = overlay.getGesture();
                if (gesture.getStrokesCount() == 2) {
                    if (event.getAction() == MotionEvent.ACTION_UP) {
                        if (et.getText().toString().equals("")) {
                            tv.setText("你沒有輸入手勢名稱,儲存失敗。");
                        } else {
                            tv.setText("正在儲存手勢…");
                            addMyGesture(et.getText().toString(), gesture);
                        }
                    }
                } else {
                    tv.setText("請在緊接的時間內用兩筆畫完成一個手勢!");
                }
            }

            @Override public void onGestureCancelled(GestureOverlayView o, MotionEvent e) {}
            @Override public void onGesture(GestureOverlayView o, MotionEvent e) {}
        });

        if (!gestureLib.load()) {
            tv.setText("第一次載入,先來練習畫幾個手勢吧!操作:先在 EditText 輸入名稱,再畫手勢。");
        } else {
            Set<String> set = gestureLib.getGestureEntries();
            loadAllGesture(set, set.toArray());
        }
    }
}

我把建立手勢、比對手勢、遍歷手勢、手勢轉圖片這幾件事各自拉成獨立函式,思路會清楚很多。

一個容易踩到的坑:手勢什麼時候算「完成」?

理論上,設定成多筆畫之後,系統應該要等你停手一段時間才判定手勢完成。實測卻不是這樣:不管你設定的類型是單一還是多筆畫,只要手指離開螢幕,Android 就會立刻觸發 onGestureEnded——即使你只寫了兩筆中的第一筆。

解法是 gesture.getStrokesCount()。它會回報這段時間內你畫了幾筆,而單一筆畫模式下這個值永遠不會大於 1。用這個值當條件,就能過濾掉「手指還沒離開就被誤判」的情況。

建立手勢

public void addMyGesture(String name, Gesture gesture) {
    try {
        if (name.equals("himi")) {
            findGesture(gesture);   // 名稱是 himi 就走比對流程
        } else {
            if (Environment.getExternalStorageState() != null) {
                if (!file.exists()) {
                    // 手勢檔不存在:直接寫入倉庫後存檔
                    gestureLib.addGesture(name, gesture);
                    if (gestureLib.save()) {
                        gov.clear(true);
                        gestureToImage(gesture);
                        et.setText("");
                    } else {
                        tv.setText("儲存手勢失敗!");
                    }
                } else {
                    // 手勢檔已存在:先讀回來,同名就移除舊的,再寫入新的
                    if (!gestureLib.load()) {
                        tv.setText("手勢檔讀取失敗!");
                    } else {
                        Set<String> set = gestureLib.getGestureEntries();
                        Object ob[] = set.toArray();
                        boolean isHavedGesture = false;
                        for (int i = 0; i < ob.length; i++) {
                            if (((String) ob[i]).equals(name)) isHavedGesture = true;
                        }
                        if (isHavedGesture) {
                            gestureLib.removeEntry(name); // 連 key 一起刪掉
                            gestureLib.addGesture(name, gesture);
                        } else {
                            gestureLib.addGesture(name, gesture);
                        }
                        if (gestureLib.save()) {
                            gov.clear(true);
                            gestureToImage(gesture);
                            et.setText("");
                        }
                    }
                }
            } else {
                tv.setText("目前裝置沒有 SD 卡。");
            }
        }
    } catch (Exception e) {
        tv.setText("操作異常!");
    }
}

整體套路和 File 存檔一樣:先看 SD 卡有沒有,再看檔案有沒有。檔案不存在就乾脆地寫進倉庫並 save();檔案存在就必須先 load() 讀回內容,處理同名衝突後再存。

關於刪除的兩種寫法,值得說清楚:

  • gestureLib.removeGesture(name, gesture) 只移掉手勢本身,名稱這個 key 還留在 HashMap 裡。下次同名手勢寫入時,會直接覆蓋該條目的 value。
  • gestureLib.removeEntry(name) 則是把整個條目(key 與 value)一起刪掉。

因為底層就是 HashMap(key = 手勢名稱,value = 手勢),其實同名情況下你連刪除都可以省略,直接 addGesture 就會自動覆蓋。

把手勢轉成圖片

public void gestureToImage(Gesture ges) {
    if (MySurfaceView.vec_bmp != null) {
        MySurfaceView.vec_bmp.addElement(
            ges.toBitmap(100, 100, 12, Color.GREEN));
    }
}

遍歷所有手勢

public void loadAllGesture(Set<String> set, Object ob[]) {
    if (gestureLib.load()) {
        set = gestureLib.getGestureEntries();
        ob  = set.toArray();
        for (int i = 0; i < ob.length; i++) {
            gestureToImage(gestureLib.getGestures((String) ob[i]).get(0));
            MySurfaceView.vec_string.addElement((String) ob[i]);
        }
    }
}

手勢比對

public void findGesture(Gesture gesture) {
    try {
        if (Environment.getExternalStorageState() != null) {
            if (!file.exists()) {
                tv.setText("比對失敗:手勢檔不存在。");
            } else if (!gestureLib.load()) {
                tv.setText("比對失敗:手勢檔讀取失敗。");
            } else {
                // recognize() 回傳所有可能的匹配結果
                List<Prediction> predictions = gestureLib.recognize(gesture);
                if (!predictions.isEmpty()) {
                    Prediction prediction = predictions.get(0);
                    // score 代表相似度,實務上通常忽略 score < 1 的結果
                    if (prediction.score >= 1) {
                        tv.setText("最相似的手勢:name = " + prediction.name);
                    }
                }
            }
        } else {
            tv.setText("比對失敗:目前裝置沒有 SD 卡。");
        }
    } catch (Exception e) {
        e.printStackTrace();
        tv.setText("發生異常,比對失敗。");
    }
}

核心就是 recognize():它回傳一個 Prediction 集合,裡面可能有多個相似的候選,第一個通常就是最佳解,再用 score 決定要不要採信。

結語

不論是觸控手勢還是輸入法手勢,放進遊戲裡都能讓操作層次整個升級。自訂手勢的門檻其實不高,但玩家感受到的「這遊戲很懂我」卻非常強烈,值得花時間做。

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