Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android 游戲 實戰打飛機游戲 子彈生成與碰撞 以及爆炸效果(5)

android 游戲 實戰打飛機游戲 子彈生成與碰撞 以及爆炸效果(5)

編輯:關於Android編程

子彈生成 新建子彈類

public class Bullet {
    // 子彈圖片資源
    public Bitmap bmpBullet;
    // 子彈的坐標
    public int bulletX, bulletY;
    // 子彈的速度
    public int speed;
    // 子彈的種類以及常量
    public int bulletType;
    // 主角的
    public static final int BULLET_PLAYER = -1;
    // 鴨子的
    public static final int BULLET_DUCK = 1;
    // 蒼蠅的
    public static final int BULLET_FLY = 2;
    // Boss的
    public static final int BULLET_BOSS = 3;
    // 子彈是否超屏, 優化處理
    public boolean isDead;

    // Boss瘋狂狀態下子彈相關成員變量
    private int dir;// 當前Boss子彈方向
    // 8方向常量
    public static final int DIR_UP = -1;
    public static final int DIR_DOWN = 2;
    public static final int DIR_LEFT = 3;
    public static final int DIR_RIGHT = 4;
    public static final int DIR_UP_LEFT = 5;
    public static final int DIR_UP_RIGHT = 6;
    public static final int DIR_DOWN_LEFT = 7;
    public static final int DIR_DOWN_RIGHT = 8;

    // 子彈當前方向
    public Bullet(Bitmap bmpBullet, int bulletX, int bulletY, int bulletType) {
        this.bmpBullet = bmpBullet;
        this.bulletX = bulletX;
        this.bulletY = bulletY;
        this.bulletType = bulletType;
        // 不同的子彈類型速度不一
        switch (bulletType) {
        case BULLET_PLAYER:
            speed = 4;
            break;
        case BULLET_DUCK:
            speed = 3;
            break;
        case BULLET_FLY:
            speed = 4;
            break;
        case BULLET_BOSS:
            speed = 5;
            break;
        }
    }

    public void draw(Canvas canvas, Paint paint) {
        canvas.drawBitmap(bmpBullet, bulletX, bulletY, paint);
    }

    // 子彈的邏輯
    public void logic() {
        // 不同的子彈類型邏輯不一
        // 主角的子彈垂直向上運動
        switch (bulletType) {
        case BULLET_PLAYER:
            bulletY -= speed;
            if (bulletY < -50) {
                isDead = true;
            }
            break;
        // 鴨子和蒼蠅的子彈都是垂直下落運動
        case BULLET_DUCK:
        case BULLET_FLY:
            bulletY += speed;
            if (bulletY > MySurfaceView.screenH) {
                isDead = true;
            }
            break;
        case BULLET_BOSS:
            // Boss瘋狂狀態下的子彈邏輯待實現
            // 邊界處理
            if (bulletY > MySurfaceView.screenH || bulletY <= -40
                    || bulletX > MySurfaceView.screenW || bulletX <= -40) {
                isDead = true;
            }
            break;
        }
    }

}

在在MySurfacview裡面調用 生成子彈主角的和自己的

package com.gsf;

import java.util.Random;
import java.util.Vector;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class MySurfaceView extends SurfaceView implements Callback, Runnable {
    private SurfaceHolder sfh;
    private Paint paint;
    private Thread th;
    private boolean flag;
    private Canvas canvas;

    // 1 定義游戲狀態常量
    public static final int GAME_MENU = 0;// 游戲菜單
    public static final int GAMEING = 1;// 游戲中
    public static final int GAME_WIN = 2;// 游戲勝利
    public static final int GAME_LOST = 3;// 游戲失敗
    public static final int GAME_PAUSE = -1;// 游戲菜單
    // 當前游戲狀態(默認初始在游戲菜單界面)
    public static int gameState = GAME_MENU;
    // 聲明一個Resources實例便於加載圖片
    private Resources res = this.getResources();
    // 聲明游戲需要用到的圖片資源(圖片聲明)
    private Bitmap bmpBackGround;// 游戲背景
    private Bitmap bmpBoom;// 爆炸效果
    private Bitmap bmpBoosBoom;// Boos爆炸效果
    private Bitmap bmpButton;// 游戲開始按鈕
    private Bitmap bmpButtonPress;// 游戲開始按鈕被點擊
    private Bitmap bmpEnemyDuck;// 怪物鴨子
    private Bitmap bmpEnemyFly;// 怪物蒼蠅
    private Bitmap bmpEnemyBoos;// 怪物豬頭Boos
    private Bitmap bmpGameWin;// 游戲勝利背景
    private Bitmap bmpGameLost;// 游戲失敗背景
    private Bitmap bmpPlayer;// 游戲主角飛機
    private Bitmap bmpPlayerHp;// 主角飛機血量
    private Bitmap bmpMenu;// 菜單背景
    public static Bitmap bmpBullet;// 子彈
    public static Bitmap bmpEnemyBullet;// 敵機子彈
    public static Bitmap bmpBossBullet;// Boss子彈
    public static int screenW;
    public static int screenH;

    // 聲明一個敵機容器
    private Vector vcEnemy;
    // 每次生成敵機的時間(毫秒)
    private int createEnemyTime = 50;
    private int count;// 計數器
    // 敵人數組:1和2表示敵機的種類,-1表示Boss
    // 二維數組的每一維都是一組怪物
    private int enemyArray[][] = { { 1, 2 }, { 1, 1 }, { 1, 3, 1, 2 },
            { 1, 2 }, { 2, 3 }, { 3, 1, 3 }, { 2, 2 }, { 1, 2 }, { 2, 2 },
            { 1, 3, 1, 1 }, { 2, 1 }, { 1, 3 }, { 2, 1 }, { -1 } };
    // 當前取出一維數組的下標
    private int enemyArrayIndex;
    // 是否出現Boss標識位
    private boolean isBoss;
    // 隨機庫,為創建的敵機賦予隨即坐標
    private Random random;

    //
    private GameMenu gameMenu;
    private GameBg gameBg;

    private Player player;

    // 敵機子彈容器
    private Vector vcBullet;
    // 添加子彈的計數器
    private int countEnemyBullet;
    // 主角子彈容器
    private Vector vcBulletPlayer;
    // 添加子彈的計數器
    private int countPlayerBullet;

    /**
     * SurfaceView初始化函數
     */
    public MySurfaceView(Context context) {
        super(context);
        sfh = this.getHolder();
        sfh.addCallback(this);
        paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setAntiAlias(true);
        setFocusable(true);
    }

    /**
     * SurfaceView視圖創建,響應此函數
     */
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        screenW = this.getWidth();
        screenH = this.getHeight();
        initGame();
        flag = true;
        // 實例線程
        th = new Thread(this);
        // 啟動線程
        th.start();
    }

    /**
     * 加載游戲資源
     */
    private void initGame() {
        // 加載游戲資源
        bmpBackGround = BitmapFactory
                .decodeResource(res, R.drawable.background);
        bmpBoom = BitmapFactory.decodeResource(res, R.drawable.boom);
        bmpBoosBoom = BitmapFactory.decodeResource(res, R.drawable.boos_boom);
        bmpButton = BitmapFactory.decodeResource(res, R.drawable.button);
        bmpButtonPress = BitmapFactory.decodeResource(res,
                R.drawable.button_press);
        bmpEnemyDuck = BitmapFactory.decodeResource(res, R.drawable.enemy_duck);
        bmpEnemyFly = BitmapFactory.decodeResource(res, R.drawable.enemy_fly);
        bmpEnemyBoos = BitmapFactory.decodeResource(res, R.drawable.enemy_pig);
        bmpGameWin = BitmapFactory.decodeResource(res, R.drawable.gamewin);
        bmpGameLost = BitmapFactory.decodeResource(res, R.drawable.gamelost);
        bmpPlayer = BitmapFactory.decodeResource(res, R.drawable.player);
        bmpPlayerHp = BitmapFactory.decodeResource(res, R.drawable.hp);
        bmpMenu = BitmapFactory.decodeResource(res, R.drawable.menu);
        bmpBullet = BitmapFactory.decodeResource(res, R.drawable.bullet);
        bmpEnemyBullet = BitmapFactory.decodeResource(res,
                R.drawable.bullet_enemy);
        bmpBossBullet = BitmapFactory
                .decodeResource(res, R.drawable.boosbullet);

        // 菜單類實例化
        gameMenu = new GameMenu(bmpMenu, bmpButton, bmpButtonPress);
        // 實例游戲背景
        gameBg = new GameBg(bmpBackGround);
        // 實例主角
        player = new Player(bmpPlayer, bmpPlayerHp);
        //敵機子彈容器實例
        vcBullet = new Vector();
        //主角子彈容器實例
        vcBulletPlayer = new Vector();
        // 實例敵機容器
        vcEnemy = new Vector();
        // 實例隨機庫
        random = new Random();
    }

    /**
     * 游戲繪圖
     */
    public void myDraw() {
        try {
            canvas = sfh.lockCanvas();
            if (canvas != null) {
                canvas.drawColor(Color.WHITE);
                // 繪圖函數根據游戲狀態不同進行不同繪制

                switch (gameState) {
                case GAME_MENU:

                    gameMenu.draw(canvas, paint);
                    break;
                case GAMEING:
                    gameBg.draw(canvas, paint);
                    player.draw(canvas, paint);
                    if (isBoss == false) {
                        // 敵機繪制
                        for (int i = 0; i < vcEnemy.size(); i++) {
                            vcEnemy.elementAt(i).draw(canvas, paint);
                        }
                        //敵機子彈繪制
                        for (int i = 0; i < vcBullet.size(); i++) {
                            vcBullet.elementAt(i).draw(canvas, paint);
                        }

                    } else {
                        // boss 繪制

                    }
                    // 處理主角子彈繪制
                    for (int i = 0; i < vcBulletPlayer.size(); i++) {
                        vcBulletPlayer.elementAt(i).draw(canvas, paint);
                    }

                    break;

                case GAME_WIN:

                    break;
                case GAME_LOST:

                    break;
                case GAME_PAUSE:

                    break;
                default:
                    break;
                }

            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            if (canvas != null)
                sfh.unlockCanvasAndPost(canvas);
        }
    }

    /**
     * 觸屏事件監聽
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (gameState) {
        case GAME_MENU:

            gameMenu.onTouchEvent(event);
            break;
        case GAMEING:

            break;

        case GAME_WIN:

            break;
        case GAME_LOST:

            break;
        case GAME_PAUSE:

            break;
        }
        return true;
    }

    /**
     * 按鍵事件監聽
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (gameState) {
        case GAME_MENU:

            break;
        case GAMEING:
            player.onKeyDown(keyCode, event);
            break;

        case GAME_WIN:

            break;
        case GAME_LOST:

            break;
        case GAME_PAUSE:
            break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (gameState) {
        case GAME_MENU:

            break;
        case GAMEING:
            player.onKeyUp(keyCode, event);
            break;

        case GAME_WIN:

            break;
        case GAME_LOST:

            break;
        case GAME_PAUSE:
            break;
        }
        return super.onKeyUp(keyCode, event);
    }

    /**
     * 游戲邏輯
     */
    private void logic() {
        switch (gameState) {
        case GAME_MENU:

            break;
        case GAMEING:
            gameBg.logic();
            player.logic();
            // 敵機邏輯
            if (isBoss == false) {
                // 敵機邏輯
                for (int i = 0; i < vcEnemy.size(); i++) {
                    Enemy en = vcEnemy.elementAt(i);
                    // 因為容器不斷添加敵機 ,那麼對敵機isDead判定,
                    // 如果已死亡那麼就從容器中刪除,對容器起到了優化作用;
                    if (en.isDead) {
                        vcEnemy.removeElementAt(i);
                    } else {
                        en.logic();
                    }
                }
                // 生成敵機
                count++;
                if (count % createEnemyTime == 0) {
                    for (int i = 0; i < enemyArray[enemyArrayIndex].length; i++) {
                        // 蒼蠅
                        if (enemyArray[enemyArrayIndex][i] == 1) {
                            int x = random.nextInt(screenW - 100) + 50;
                            vcEnemy.addElement(new Enemy(bmpEnemyFly, 1, x, -50));
                            // 鴨子左
                        } else if (enemyArray[enemyArrayIndex][i] == 2) {
                            int y = random.nextInt(20);
                            vcEnemy.addElement(new Enemy(bmpEnemyDuck, 2, -50,
                                    y));
                            // 鴨子右
                        } else if (enemyArray[enemyArrayIndex][i] == 3) {
                            int y = random.nextInt(20);
                            vcEnemy.addElement(new Enemy(bmpEnemyDuck, 3,
                                    screenW + 50, y));
                        }
                    }
                    // 這裡判斷下一組是否為最後一組(Boss)
                    if (enemyArrayIndex == enemyArray.length - 1) {
                        isBoss = true;
                    } else {
                        enemyArrayIndex++;
                    }
                }

                // 每2秒添加一個敵機子彈
                countEnemyBullet++;
                if (countEnemyBullet % 40 == 0) {
                    for (int i = 0; i < vcEnemy.size(); i++) {
                        Enemy en = vcEnemy.elementAt(i);
                        // 不同類型敵機不同的子彈運行軌跡
                        int bulletType = 0;
                        switch (en.type) {
                        // 蒼蠅
                        case Enemy.TYPE_FLY:
                            bulletType = Bullet.BULLET_FLY;
                            break;
                        // 鴨子
                        case Enemy.TYPE_DUCKL:
                        case Enemy.TYPE_DUCKR:
                            bulletType = Bullet.BULLET_DUCK;
                            break;
                        }
                        vcBullet.add(new Bullet(bmpEnemyBullet, en.x + 10,
                                en.y + 20, bulletType));
                    }
                }
                // 處理敵機子彈邏輯
                for (int i = 0; i < vcBullet.size(); i++) {
                    Bullet b = vcBullet.elementAt(i);
                    if (b.isDead) {
                        vcBullet.removeElement(b);
                    } else {
                        b.logic();
                    }
                }

                //每1秒添加一個主角子彈
                countPlayerBullet++;
                if (countPlayerBullet % 20 == 0) {
                    vcBulletPlayer.add(new Bullet(bmpBullet, player.x + 15, player.y - 20, Bullet.BULLET_PLAYER));
                }

                // 處理敵機與主角的碰撞
                for (int i = 0; i < vcEnemy.size(); i++) {
                    if (player.isCollsionWith(vcEnemy.elementAt(i))) {
                        // 發生碰撞,主角血量-1
                        player.setPlayerHp(player.getPlayerHp() - 1);
                        // 當主角血量小於0,判定游戲失敗
                        if (player.getPlayerHp() <= -1) {
                            gameState = GAME_LOST;
                        }
                    }
                }

                //處理主角子彈邏輯
                for (int i = 0; i < vcBulletPlayer.size(); i++) {
                    Bullet b = vcBulletPlayer.elementAt(i);
                    if (b.isDead) {
                        vcBulletPlayer.removeElement(b);
                    } else {
                        b.logic();
                    }
                }
            }
            break;

        case GAME_WIN:

            break;
        case GAME_LOST:

            break;
        case GAME_PAUSE:
            break;
        }

    }

    @Override
    public void run() {
        while (flag) {
            long start = System.currentTimeMillis();
            myDraw();
            logic();
            long end = System.currentTimeMillis();
            try {
                if (end - start < 50) {
                    Thread.sleep(50 - (end - start));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * SurfaceView視圖狀態發生改變,響應此函數
     */
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
    }

    /**
     * SurfaceView視圖消亡時,響應此函數
     */
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        flag = false;
    }
}

==現在子彈碰撞主角 並沒有發生事情 需要子彈和主角的碰撞檢測===

//修改Player類 添加碰撞檢測


    // // 判斷碰撞(主角與敵機子彈)
    public boolean isCollsionWith(Bullet bullet) {
        // 是否處於無敵時間
        if (isCollision == false) {
            int x2 = bullet.bulletX;
            int y2 = bullet.bulletY;
            int w2 = bullet.bmpBullet.getWidth();
            int h2 = bullet.bmpBullet.getHeight();
            if (x >= x2 && x >= x2 + w2) {
                return false;
            } else if (x <= x2 && x + bmpPlayer.getWidth() <= x2) {
                return false;
            } else if (y >= y2 && y >= y2 + h2) {
                return false;
            } else if (y <= y2 && y + bmpPlayer.getHeight() <= y2) {
                return false;
            }
            // 碰撞即進入無敵狀態
            isCollision = true;
            return true;
            // 處於無敵狀態,無視碰撞
        } else {
            return false;
        }
    }

在主界面 MySrufaceView 的邏輯函數中添加 主角和敵機子彈的碰撞

    //處理敵機子彈與主角碰撞
                for (int i = 0; i < vcBullet.size(); i++) {
                    if (player.isCollsionWith(vcBullet.elementAt(i))) {
                        //發生碰撞,主角血量-1
                        player.setPlayerHp(player.getPlayerHp() - 1);
                        //當主角血量小於0,判定游戲失敗
                        if (player.getPlayerHp() <= -1) {
                            gameState = GAME_LOST;
                        }
                    }
                }

當然 主角的子彈碰撞了敵機 也需要進行碰撞檢測 修改 敵機類 Enemy

    //判斷碰撞(敵機與主角子彈碰撞)
    public boolean isCollsionWith(Bullet bullet) {
        int x2 = bullet.bulletX;
        int y2 = bullet.bulletY;
        int w2 = bullet.bmpBullet.getWidth();
        int h2 = bullet.bmpBullet.getHeight();
        if (x >= x2 && x >= x2 + w2) {
            return false;
        } else if (x <= x2 && x + frameW <= x2) {
            return false;
        } else if (y >= y2 && y >= y2 + h2) {
            return false;
        } else if (y <= y2 && y + frameH <= y2) {
            return false;
        }
        //發生碰撞,讓其死亡
        isDead = true;
        return true;
    }

在主視圖中添加邏輯 主角子彈和敵機碰撞的邏輯

                //處理主角子彈與敵機碰撞
                for (int i = 0; i < vcBulletPlayer.size(); i++) {
                    //取出主角子彈容器的每個元素
                    Bullet blPlayer = vcBulletPlayer.elementAt(i);
                    for (int j = 0; j < vcEnemy.size(); j++) {
                        //添加爆炸效果  待完成
                    }
                }

效果圖

上面完成 的效果圖

===============下面完成爆炸的效果============

新建一個爆炸類 Boom

/**
 * 瞬間爆炸 類
 * @author liuml
 * @time 2016-6-1 上午11:32:56
 */
public class Boom {
    //爆炸效果資源圖
    private Bitmap bmpBoom;
    //爆炸效果的位置坐標
    private int boomX, boomY;
    //爆炸動畫播放當前的幀下標
    private int cureentFrameIndex;
    //爆炸效果的總幀數
    private int totleFrame;
    //每幀的寬高
    private int frameW, frameH;
    //是否播放完畢,優化處理
    public boolean playEnd;

    //爆炸效果的構造函數
    public Boom(Bitmap bmpBoom, int x, int y, int totleFrame) {
        this.bmpBoom = bmpBoom;
        this.boomX = x;
        this.boomY = y;
        this.totleFrame = totleFrame;
        frameW = bmpBoom.getWidth() / totleFrame;
        frameH = bmpBoom.getHeight();
    }

    //爆炸效果繪制
    public void draw(Canvas canvas, Paint paint) {
        canvas.save();
        canvas.clipRect(boomX, boomY, boomX + frameW, boomY + frameH);
        canvas.drawBitmap(bmpBoom, boomX - cureentFrameIndex * frameW, boomY, paint);
        canvas.restore();
    }

    //爆炸效果的邏輯
    public void logic() {
        if (cureentFrameIndex < totleFrame) {
            cureentFrameIndex++;
        } else {
            playEnd = true;
        }
    }
}

下面就還是老套路了 在主界面 聲明爆炸容器 然後繪制 然後是邏輯實現

    package com.gsf;

import java.util.Random;
import java.util.Vector;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;

public class MySurfaceView extends SurfaceView implements Callback, Runnable {
    private SurfaceHolder sfh;
    private Paint paint;
    private Thread th;
    private boolean flag;
    private Canvas canvas;

    // 1 定義游戲狀態常量
    public static final int GAME_MENU = 0;// 游戲菜單
    public static final int GAMEING = 1;// 游戲中
    public static final int GAME_WIN = 2;// 游戲勝利
    public static final int GAME_LOST = 3;// 游戲失敗
    public static final int GAME_PAUSE = -1;// 游戲菜單
    // 當前游戲狀態(默認初始在游戲菜單界面)
    public static int gameState = GAME_MENU;
    // 聲明一個Resources實例便於加載圖片
    private Resources res = this.getResources();
    // 聲明游戲需要用到的圖片資源(圖片聲明)
    private Bitmap bmpBackGround;// 游戲背景
    private Bitmap bmpBoom;// 爆炸效果
    private Bitmap bmpBoosBoom;// Boos爆炸效果
    private Bitmap bmpButton;// 游戲開始按鈕
    private Bitmap bmpButtonPress;// 游戲開始按鈕被點擊
    private Bitmap bmpEnemyDuck;// 怪物鴨子
    private Bitmap bmpEnemyFly;// 怪物蒼蠅
    private Bitmap bmpEnemyBoos;// 怪物豬頭Boos
    private Bitmap bmpGameWin;// 游戲勝利背景
    private Bitmap bmpGameLost;// 游戲失敗背景
    private Bitmap bmpPlayer;// 游戲主角飛機
    private Bitmap bmpPlayerHp;// 主角飛機血量
    private Bitmap bmpMenu;// 菜單背景
    public static Bitmap bmpBullet;// 子彈
    public static Bitmap bmpEnemyBullet;// 敵機子彈
    public static Bitmap bmpBossBullet;// Boss子彈
    public static int screenW;
    public static int screenH;

    // 聲明一個敵機容器
    private Vector vcEnemy;
    // 每次生成敵機的時間(毫秒)
    private int createEnemyTime = 50;
    private int count;// 計數器
    // 敵人數組:1和2表示敵機的種類,-1表示Boss
    // 二維數組的每一維都是一組怪物
    private int enemyArray[][] = { { 1, 2 }, { 1, 1 }, { 1, 3, 1, 2 },
            { 1, 2 }, { 2, 3 }, { 3, 1, 3 }, { 2, 2 }, { 1, 2 }, { 2, 2 },
            { 1, 3, 1, 1 }, { 2, 1 }, { 1, 3 }, { 2, 1 }, { -1 } };
    // 當前取出一維數組的下標
    private int enemyArrayIndex;
    // 是否出現Boss標識位
    private boolean isBoss;
    // 隨機庫,為創建的敵機賦予隨即坐標
    private Random random;

    //
    private GameMenu gameMenu;
    private GameBg gameBg;

    private Player player;

    // 敵機子彈容器
    private Vector vcBullet;
    // 添加子彈的計數器
    private int countEnemyBullet;
    // 主角子彈容器
    private Vector vcBulletPlayer;
    // 添加子彈的計數器
    private int countPlayerBullet;

    //爆炸效果容器
    private Vector vcBoom;

    /**
     * SurfaceView初始化函數
     */
    public MySurfaceView(Context context) {
        super(context);
        sfh = this.getHolder();
        sfh.addCallback(this);
        paint = new Paint();
        paint.setColor(Color.WHITE);
        paint.setAntiAlias(true);
        setFocusable(true);
    }

    /**
     * SurfaceView視圖創建,響應此函數
     */
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        screenW = this.getWidth();
        screenH = this.getHeight();
        initGame();
        flag = true;
        // 實例線程
        th = new Thread(this);
        // 啟動線程
        th.start();
    }

    /**
     * 加載游戲資源
     */
    private void initGame() {
        // 加載游戲資源
        bmpBackGround = BitmapFactory
                .decodeResource(res, R.drawable.background);
        bmpBoom = BitmapFactory.decodeResource(res, R.drawable.boom);
        bmpBoosBoom = BitmapFactory.decodeResource(res, R.drawable.boos_boom);
        bmpButton = BitmapFactory.decodeResource(res, R.drawable.button);
        bmpButtonPress = BitmapFactory.decodeResource(res,
                R.drawable.button_press);
        bmpEnemyDuck = BitmapFactory.decodeResource(res, R.drawable.enemy_duck);
        bmpEnemyFly = BitmapFactory.decodeResource(res, R.drawable.enemy_fly);
        bmpEnemyBoos = BitmapFactory.decodeResource(res, R.drawable.enemy_pig);
        bmpGameWin = BitmapFactory.decodeResource(res, R.drawable.gamewin);
        bmpGameLost = BitmapFactory.decodeResource(res, R.drawable.gamelost);
        bmpPlayer = BitmapFactory.decodeResource(res, R.drawable.player);
        bmpPlayerHp = BitmapFactory.decodeResource(res, R.drawable.hp);
        bmpMenu = BitmapFactory.decodeResource(res, R.drawable.menu);
        bmpBullet = BitmapFactory.decodeResource(res, R.drawable.bullet);
        bmpEnemyBullet = BitmapFactory.decodeResource(res,
                R.drawable.bullet_enemy);
        bmpBossBullet = BitmapFactory
                .decodeResource(res, R.drawable.boosbullet);

        // 菜單類實例化
        gameMenu = new GameMenu(bmpMenu, bmpButton, bmpButtonPress);
        // 實例游戲背景
        gameBg = new GameBg(bmpBackGround);
        // 實例主角
        player = new Player(bmpPlayer, bmpPlayerHp);
        //敵機子彈容器實例
        vcBullet = new Vector();
        //主角子彈容器實例
        vcBulletPlayer = new Vector();
        // 實例敵機容器
        vcEnemy = new Vector();
        // 實例隨機庫
        random = new Random();
        //爆炸效果容器實例
        vcBoom = new Vector();
    }

    /**
     * 游戲繪圖
     */
    public void myDraw() {
        try {
            canvas = sfh.lockCanvas();
            if (canvas != null) {
                canvas.drawColor(Color.WHITE);
                // 繪圖函數根據游戲狀態不同進行不同繪制

                switch (gameState) {
                case GAME_MENU:

                    gameMenu.draw(canvas, paint);
                    break;
                case GAMEING:
                    gameBg.draw(canvas, paint);
                    player.draw(canvas, paint);
                    if (isBoss == false) {
                        // 敵機繪制
                        for (int i = 0; i < vcEnemy.size(); i++) {
                            vcEnemy.elementAt(i).draw(canvas, paint);
                        }
                        //敵機子彈繪制
                        for (int i = 0; i < vcBullet.size(); i++) {
                            vcBullet.elementAt(i).draw(canvas, paint);
                        }
                        //爆炸效果繪制
                        for (int i = 0; i < vcBoom.size(); i++) {
                            vcBoom.elementAt(i).draw(canvas, paint);
                        }
                    } else {
                        // boss 繪制

                    }
                    // 處理主角子彈繪制
                    for (int i = 0; i < vcBulletPlayer.size(); i++) {
                        vcBulletPlayer.elementAt(i).draw(canvas, paint);
                    }

                    break;

                case GAME_WIN:

                    break;
                case GAME_LOST:

                    break;
                case GAME_PAUSE:

                    break;
                default:
                    break;
                }

            }
        } catch (Exception e) {
            // TODO: handle exception
        } finally {
            if (canvas != null)
                sfh.unlockCanvasAndPost(canvas);
        }
    }

    /**
     * 觸屏事件監聽
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (gameState) {
        case GAME_MENU:

            gameMenu.onTouchEvent(event);
            break;
        case GAMEING:

            break;

        case GAME_WIN:

            break;
        case GAME_LOST:

            break;
        case GAME_PAUSE:

            break;
        }
        return true;
    }

    /**
     * 按鍵事件監聽
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (gameState) {
        case GAME_MENU:

            break;
        case GAMEING:
            player.onKeyDown(keyCode, event);
            break;

        case GAME_WIN:

            break;
        case GAME_LOST:

            break;
        case GAME_PAUSE:
            break;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        switch (gameState) {
        case GAME_MENU:

            break;
        case GAMEING:
            player.onKeyUp(keyCode, event);
            break;

        case GAME_WIN:

            break;
        case GAME_LOST:

            break;
        case GAME_PAUSE:
            break;
        }
        return super.onKeyUp(keyCode, event);
    }

    /**
     * 游戲邏輯
     */
    private void logic() {
        switch (gameState) {
        case GAME_MENU:

            break;
        case GAMEING:
            gameBg.logic();
            player.logic();
            // 敵機邏輯
            if (isBoss == false) {
                // 敵機邏輯
                for (int i = 0; i < vcEnemy.size(); i++) {
                    Enemy en = vcEnemy.elementAt(i);
                    // 因為容器不斷添加敵機 ,那麼對敵機isDead判定,
                    // 如果已死亡那麼就從容器中刪除,對容器起到了優化作用;
                    if (en.isDead) {
                        vcEnemy.removeElementAt(i);
                    } else {
                        en.logic();
                    }
                }
                // 生成敵機
                count++;
                if (count % createEnemyTime == 0) {
                    for (int i = 0; i < enemyArray[enemyArrayIndex].length; i++) {
                        // 蒼蠅
                        if (enemyArray[enemyArrayIndex][i] == 1) {
                            int x = random.nextInt(screenW - 100) + 50;
                            vcEnemy.addElement(new Enemy(bmpEnemyFly, 1, x, -50));
                            // 鴨子左
                        } else if (enemyArray[enemyArrayIndex][i] == 2) {
                            int y = random.nextInt(20);
                            vcEnemy.addElement(new Enemy(bmpEnemyDuck, 2, -50,
                                    y));
                            // 鴨子右
                        } else if (enemyArray[enemyArrayIndex][i] == 3) {
                            int y = random.nextInt(20);
                            vcEnemy.addElement(new Enemy(bmpEnemyDuck, 3,
                                    screenW + 50, y));
                        }
                    }
                    // 這裡判斷下一組是否為最後一組(Boss)
                    if (enemyArrayIndex == enemyArray.length - 1) {
                        isBoss = true;
                    } else {
                        enemyArrayIndex++;
                    }
                }

                // 每2秒添加一個敵機子彈
                countEnemyBullet++;
                if (countEnemyBullet % 40 == 0) {
                    for (int i = 0; i < vcEnemy.size(); i++) {
                        Enemy en = vcEnemy.elementAt(i);
                        // 不同類型敵機不同的子彈運行軌跡
                        int bulletType = 0;
                        switch (en.type) {
                        // 蒼蠅
                        case Enemy.TYPE_FLY:
                            bulletType = Bullet.BULLET_FLY;
                            break;
                        // 鴨子
                        case Enemy.TYPE_DUCKL:
                        case Enemy.TYPE_DUCKR:
                            bulletType = Bullet.BULLET_DUCK;
                            break;
                        }
                        vcBullet.add(new Bullet(bmpEnemyBullet, en.x + 10,
                                en.y + 20, bulletType));
                    }
                }
                // 處理敵機子彈邏輯
                for (int i = 0; i < vcBullet.size(); i++) {
                    Bullet b = vcBullet.elementAt(i);
                    if (b.isDead) {
                        vcBullet.removeElement(b);
                    } else {
                        b.logic();
                    }
                }

                //每1秒添加一個主角子彈
                countPlayerBullet++;
                if (countPlayerBullet % 20 == 0) {
                    vcBulletPlayer.add(new Bullet(bmpBullet, player.x + 15, player.y - 20, Bullet.BULLET_PLAYER));
                }

                // 處理敵機與主角的碰撞
                for (int i = 0; i < vcEnemy.size(); i++) {
                    if (player.isCollsionWith(vcEnemy.elementAt(i))) {
                        // 發生碰撞,主角血量-1
                        player.setPlayerHp(player.getPlayerHp() - 1);
                        // 當主角血量小於0,判定游戲失敗
                        if (player.getPlayerHp() <= -1) {
                            gameState = GAME_LOST;
                        }
                    }
                }

                //處理主角子彈邏輯
                for (int i = 0; i < vcBulletPlayer.size(); i++) {
                    Bullet b = vcBulletPlayer.elementAt(i);
                    if (b.isDead) {
                        vcBulletPlayer.removeElement(b);
                    } else {
                        b.logic();
                    }
                }

                //處理敵機子彈與主角碰撞
                for (int i = 0; i < vcBullet.size(); i++) {
                    if (player.isCollsionWith(vcBullet.elementAt(i))) {
                        //發生碰撞,主角血量-1
                        player.setPlayerHp(player.getPlayerHp() - 1);
                        //當主角血量小於0,判定游戲失敗
                        if (player.getPlayerHp() <= -1) {
                            gameState = GAME_LOST;
                        }
                    }
                }

                //處理主角子彈與敵機碰撞
                for (int i = 0; i < vcBulletPlayer.size(); i++) {
                    //取出主角子彈容器的每個元素
                    Bullet blPlayer = vcBulletPlayer.elementAt(i);
                    for (int j = 0; j < vcEnemy.size(); j++) {
                        //添加爆炸效果
                        //取出敵機容器的每個元與主角子彈遍歷判斷
                        if (vcEnemy.elementAt(j).isCollsionWith(blPlayer)) {
                            vcBoom.add(new Boom(bmpBoom, vcEnemy.elementAt(j).x, vcEnemy.elementAt(j).y, 7));
                        }
                    }
                }
            }
            break;

        case GAME_WIN:

            break;
        case GAME_LOST:

            break;
        case GAME_PAUSE:
            break;
        }

    }

    @Override
    public void run() {
        while (flag) {
            long start = System.currentTimeMillis();
            myDraw();
            logic();
            long end = System.currentTimeMillis();
            try {
                if (end - start < 50) {
                    Thread.sleep(50 - (end - start));
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * SurfaceView視圖狀態發生改變,響應此函數
     */
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
    }

    /**
     * SurfaceView視圖消亡時,響應此函數
     */
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        flag = false;
    }
}

效果圖

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved