Android使用SurfaceView开发《捉小猪》小游戏 (一)
先上效果圖:
哈哈, 說下實現思路:
我們可以把每一個樹樁, 小豬, 車廂都看成是一個Drawable, 這個Drawable里面保存了x, y坐標, 我們的SurfaceView在draw的時候, 就把這些Drawable draw出來.
那可能有的小伙伴就會問了:
1. 那小豬是怎么讓它跑起來, 并且腿部還不斷地在動呢?
2. 還有小豬是怎么找到出路的呢?
剛剛我們講過小豬是Drawable, 其實我們自定義的這個Drawable就是一個幀動畫, 它里面有一個Bitmap數組, 一個currentIndex(這個用來記錄當前幀), 我們在子線程里面不斷更新這個currentIndex, 當Drawable被調用draw的時候, 就根據currentIndex來從Bitmap數組里面取對應的bitmap出來. 剛剛還講過Drawable里面保存了當前x, y坐標, 我們的路徑動畫在播放的時候, 就不斷的更新里面的坐標, 另外, SurfaceView那邊也不斷的調用這些Drawable的draw方法, 把他們畫出來, 這樣小豬就可以邊移動, 邊播放奔跑的動畫了, 哈哈.
小豬找出路的話, 我們先看看這個:
哈哈哈, 這樣思路是不是清晰了好多.
其實我們的SurfaceView里面有一個Rect二維數組, 用來存放這些矩形, 小豬離開手指之后, 就開始從小豬當前所在的矩形,
用廣度優先遍歷, 找到一條最短的路徑(比如: [5,5 5,4 5,3 5,2 5,1 5,0]這樣的), 然后再根據這條路徑在Rect數組中找到對應的矩形, 最后根據這些對應的矩形的坐標來確定出Path.
哈哈, 有了Path小豬就可以跑了.
下面我們先來看看那個自定義的Drawable怎么寫 (下面的那個ThreadPool類就是我們自己封裝的一個單例的線程池):
/*** 自定義的Drawable,類似于AnimationDrawable*/ public class MyDrawable extends Drawable implements Cloneable {private final int mDelay;//幀延時private final byte[] mLock;//控制線程暫停的鎖private Semaphore mSemaphore;//來用控制線程更新問題private Bitmap[] mBitmaps;//幀private Paint mPaint;private int mCurrentIndex;//當前幀索引private float x, y;//當前坐標private Future mTask;//幀動畫播放的任務private volatile boolean isPaused;//已暫停public MyDrawable(int delay, Bitmap... bitmaps) {mSemaphore = new Semaphore(1);mBitmaps = bitmaps;mDelay = delay;mPaint = new Paint();mPaint.setAntiAlias(true);mLock = new byte[0];}public void start() {stop();mTask = ThreadPool.getInstance().execute(() -> {while (true) {synchronized (mLock) {while (isPaused) {try {mLock.wait();} catch (InterruptedException e) {return;}}}try {Thread.sleep(mDelay);} catch (InterruptedException e) {return;}try {mSemaphore.acquire();} catch (InterruptedException e) {return;}mCurrentIndex++;if (mCurrentIndex == mBitmaps.length) {mCurrentIndex = 0;}mSemaphore.release();}});}void pause() {isPaused = true;}void resume() {isPaused = false;synchronized (mLock) {mLock.notifyAll();}}private void stop() {if (mTask != null) {mTask.cancel(true);mTask = null;mCurrentIndex = 0;}}@Overridepublic void draw(@NonNull Canvas canvas) {try {mSemaphore.acquire();} catch (InterruptedException e) {return;}canvas.drawBitmap(mBitmaps[mCurrentIndex], x, y, mPaint);mSemaphore.release();}public void release() {stop();if (mBitmaps != null) {for (Bitmap bitmap : mBitmaps) {if (bitmap != null && !bitmap.isRecycled()) {bitmap.recycle();}}}mBitmaps = null;mPaint = null;mTask = null;}public float getX() {return x;}public void setX(float x) {this.x = x;}public float getY() {return y;}public void setY(float y) {this.y = y;}public Bitmap getBitmap() {Bitmap result = null;if (mBitmaps != null && mBitmaps.length > 0) {result = mBitmaps[0];}return result;}@Overridepublic int getIntrinsicWidth() {if (mBitmaps.length == 0) {return 0;}return mBitmaps[0].getWidth();}@Overridepublic int getIntrinsicHeight() {if (mBitmaps.length == 0) {return 0;}return mBitmaps[0].getHeight();}@Overridepublic void setAlpha(int alpha) {mPaint.setAlpha(alpha);}@Overridepublic void setColorFilter(ColorFilter cf) {mPaint.setColorFilter(cf);}@Overridepublic int getOpacity() {return PixelFormat.TRANSLUCENT;}@SuppressWarnings("MethodDoesntCallSuperMethod")public MyDrawable clone() {return new MyDrawable(0, mBitmaps[0]);} }start方法大概就是開啟一個子線程, 每次指定延時過后就更新currentIndex, currentIndex超出范圍就置0, 這樣就可以一直循環播放下去了, 哈哈.
mSemaphore是當執行draw的時候, 用來鎖定currentIndex不讓更新的.
好了, 現在有了Drawable, 我們再來看看Path是怎么播放的:
我們可以先獲取到Path上面的點, 有了這些點接下來就非常簡單了.
獲取Path上面的點坐標的方法大家應該也很熟悉了吧, 代碼就不貼出來了,5.0及以上系統用Path的approximate方法, 5.0系統以下的用PathMeasure類. 具體代碼在SDK里面也可以找到.
播放Path的話, 我們可以自定義一個PathAnimation:
其實我們自定義的這個PathAnimation播放Path的邏輯也非常簡單:當start方法執行的時候,記錄一下開始時間,然后一個while循環,條件就是: 當前時間 - 開始時間 < 動畫時長, 然后根據當前動畫已經播放的時長和總動畫時長計算出當前動畫的播放進度, 然后我們就可以用這個progress來獲取Path上對應的點,看看完整的代碼:
我們通過setUpdateListener方法來監聽動畫進度, OnAnimationUpdateListener接口的onUpdate方法參數還有一個PointF, 這個PointF就是根據動畫當前進度從mPathKeyframes中獲取到Path所對應的坐標點.
我們來寫一個demo來看看這個PathAnimation的效果:
哈哈, 可以了, 是我們想要的效果.
現在動畫什么的都準備好了,就差怎么把出路變成Path了,我們先來看看怎么找出路:
上面說到,屏幕上都鋪滿了矩形,我們可以再創建一個int類型的二維數組,用來保存這些矩形的狀態(空閑:0,小豬占用:1,樹樁占用:2)
我們把這個數組打印出來是這樣的:
我們再看看這個數組:(空閑:0,小豬占用:1,樹樁占用:2)
0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 00 0 0 0 2 2 0 0 00 0 0 2 1 2 0 0 00 0 0 2 0 2 0 0 02 0 2 0 2 0 0 0 02 0 0 0 0 0 0 0 00 2 2 2 2 0 0 0 00 2 0 0 0 0 0 0 0這時候就要用到一個 “廣度優先遍歷” ,思路就是 (邏輯有點復雜,一次看不懂看多幾次就明白了):
先傳入這個狀態數組和當前小豬的坐標;創建一個List<List<Point>>,存放出路,名字就叫做footprints吧;創建一個隊列,這個隊列存放待查找的點;當前小豬的坐標先放進footprints;當前小豬的坐標入隊;標記小豬坐標已經走過;進入循環 (循環條件就是隊列不為空){創建一個臨時的footprints;(因為最多可能有6個新的路徑)隊頭出隊;尋找周圍6個方向(上,下,左,右,左上,右上,左下,右下)可以到達的位置 (不包括越界的、標記過的、不是空閑的);遍歷這個可到達位置的數組{遍歷footprints{檢查隊頭的坐標是否跟footprints的元素(List<Point>)的最后一個元素(Point)的位置(x,y)是一樣的(即可以鏈接)(比如: 現在footprints是[[(5,5), (5,4)], [(6,5), (6,4)]],隊頭的坐標是(5,4), 那可達位置的數組就可能是[(5,3), (5,5), (4,4), (4,5), (6,4), (6,5)]){則創建一個新的List<Point>;add footprints的元素(比如: [(5,5), (5,4)]);再add可達位置的坐標(比如: (5,3);臨時的footprints add 這個新的List (那臨時的footprints現在就是 [[(5,5), (5,4), (5,3)]]了);} }檢查本次可達位置的坐標是否已經是在邊界 (已經找到出路){footprints add 臨時的footprints的元素;遍歷footprints{判斷footprints的元素的最后一位是否邊界位置{return 這個footprints的元素; (必然是最短的路徑);}}}隊列入隊本次可達位置的坐標;}(本次沒有找到出路) footprints addAll 臨時的footprints的元素,準備下一輪循環;}執行到了這里, 即表示沒有出路, 如果footprints里面是空的話,我們直接返回null,如果不為空,就返回footprints最后一個元素,即能走的最長的一條路徑;好了,我們看看代碼是怎么寫的 (WayData等同于Point, 里面也保存有x, y坐標點):
public static List<WayData> findWay(int[][] items, WayData currentPos) {//獲取數組的尺寸int verticalCount = items.length;int horizontalCount = items[0].length;//創建隊列Queue<WayData> way = new ArrayDeque<>();//出路List<List<WayData>> footprints = new ArrayList<>();//復制一個新的數組 (因為要標記狀態)int[][] pattern = new int[verticalCount][horizontalCount];for (int vertical = 0; vertical < verticalCount; vertical++) {System.arraycopy(items[vertical], 0, pattern[vertical], 0, horizontalCount);}//當前坐標入隊way.offer(currentPos);//添加進集合List<WayData> temp = new ArrayList<>();temp.add(currentPos);footprints.add(temp);//標記狀態 (已走過)pattern[currentPos.y][currentPos.x] = STATE_WALKED;while (!way.isEmpty()) {//隊頭出隊WayData header = way.poll();//以header為中心,獲取周圍可以到達的點(即未被占用,未標記過的)(這個方法在獲取到可到達的點時,會標記這個點為: 已走過)List<WayData> directions = getCanArrivePos(pattern, header);//創建臨時的footprintsList<List<WayData>> footprintsTemp = new ArrayList<>();//遍歷可到達的點for (int i = 0; i < directions.size(); i++) {WayData direction = directions.get(i);for (List<WayData> tmp : footprints) {//檢查是否可以鏈接if (canLinks(header, tmp)) {List<WayData> list = new ArrayList<>();list.addAll(tmp);list.add(direction);footprintsTemp.add(list);}}//檢查是否已達到邊界if (isEdge(verticalCount, horizontalCount, direction)) {if (!footprintsTemp.isEmpty()) {footprints.addAll(footprintsTemp);}//返回最短的出路for (List<WayData> tmp : footprints) {if (!tmp.isEmpty() && isEdge2(verticalCount, horizontalCount, tmp)) {return tmp;}}}//本次未找到出路,入隊這個可到達的點way.offer(direction);}//準備下一輪循環if (!footprintsTemp.isEmpty()) {footprints.addAll(footprintsTemp);}}//沒有出路,返回能走的最長的一條路徑;return footprints.isEmpty() ? null : footprints.get(footprints.size() - 1);}getCanArrivePos方法:
/**尋找周圍6個方向可以到達的位置(不包括越界的,標記過的,不是空閑的)*/public static List<WayData> getCanArrivePos(int[][] items, WayData currentPos) {int verticalCount = items.length;int horizontalCount = items[0].length;List<WayData> result = new ArrayList<>();int offset = currentPos.y % 2 == 0 ? 0 : 1, offset2 = currentPos.y % 2 == 0 ? 1 : 0;for (int i = 0; i < 6; i++) {WayData tmp = getNextPosition(currentPos, offset, offset2, i);if ((tmp.x > -1 && tmp.x < horizontalCount) && (tmp.y > -1 && tmp.y < verticalCount)) {if (items[tmp.y][tmp.x] != Item.STATE_SELECTED && items[tmp.y][tmp.x] != Item.STATE_OCCUPIED && items[tmp.y][tmp.x] != STATE_WALKED) {result.add(tmp);items[tmp.y][tmp.x] = STATE_WALKED;}}}//打亂它,為了讓方向順序不一樣, 即每次都不同Collections.shuffle(result);return result;}getNextPosition方法:
/**根據當前方向獲取對應的位置*/private static WayData getNextPosition(WayData currentPos, int offset, int offset2, int direction) {WayData result = new WayData(currentPos.x, currentPos.y);switch (direction) {case 0://左result.x -= 1;break;case 1://左上result.x -= offset;result.y -= 1;break;case 2://左下result.x -= offset;result.y += 1;break;case 3://右result.x += 1;break;case 4://右上result.x += offset2;result.y -= 1;break;case 5://右下result.x += offset2;result.y += 1;break;}return result;}我們執行findWay方法,就會得到這個結果:
0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 00 0 0 0 2 2 0 0 00 0 0 2 1 2 0 0 00 0 0 2 * 2 0 0 02 0 2 * 2 0 0 0 02 * * * 0 0 0 0 0* 2 2 2 2 0 0 0 00 2 0 0 0 0 0 0 0哈哈,是不是很好玩, 我們將這條出路的坐標,分別獲取到對應的Rect,再根據這個Rect的坐標來連接成Path, 然后我們的小豬就可以跑啦.
本文到此結束,有錯誤的地方請指出,謝謝大家!
Android使用SurfaceView開發《捉小豬》小游戲 (二)
完整代碼地址: https://github.com/wuyr/CatchPiggy
游戲主頁: https://wuyr.github.io/
總結
以上是生活随笔為你收集整理的Android使用SurfaceView开发《捉小猪》小游戏 (一)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 纯js实现俄罗斯方块详解与源码
- 下一篇: 朵拉影像开发 冬天真的来了