1. 程式人生 > >JAVA小白的第二個專案—飛機大戰分步驟理解流程

JAVA小白的第二個專案—飛機大戰分步驟理解流程

專案簡單簡介

飛機大戰是整合這一個月實訓以來的成果,其中包括了所學的封裝,繼承,多型,方法的過載等多個知識點構成的一款簡單的小遊戲。經過一個禮拜的時間將此專案完成,由多個模組組成。

這個程式碼我們一共需要建立7個類

一.如何實現遊戲背景圖滾動播放

這個遊戲首先的第一個問題就是呈現出飛機正在向前飛行的效果,也就是如何將圖片一張接著一張無縫的滾動播放
在MySurfacView的畫布上將背景圖片上傳
我們先建立Blackground類,並建立logic方法

package com.example.administrator.myapplication9;

import
android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; public class BackGround { private int y1; private int y2; private Bitmap bitmap; public BackGround(Bitmap bitmap){ this.bitmap = bitmap; y1=0; y2=y1-bitmap.getHeight(); } public
void draw(Canvas canvas,Paint paint){ logic(); canvas.drawBitmap(bitmap,0,y1,paint); canvas.drawBitmap(bitmap,0,y2,paint); } public void logic() { y1+=10; y2+=10; if (y1>=MySurfaceView.height){ y1=y2-bitmap.getHeight();//移動到第二張圖片的頂部
} if (y2>=MySurfaceView.height){ y2=y1-bitmap.getHeight(); } } }

如何繪製飛機

我們需要建立一隻畫筆,鎖定畫布
並在MySurfaceView中建立run方法

  public void run() {
        gameSoundPool.playSound(3);

        Paint paint = new Paint();
        BackGround backGround = new BackGround(BitmapFactory.decodeResource(getResources(), R.mipmap.img_bg_level_3));
        plane = new Myplane(BitmapFactory.decodeResource(getResources(), R.mipmap.myplane),BitmapFactory.decodeResource(getResources(), R.mipmap.myhp));
        BossPlane bossPlane = new BossPlane(BitmapFactory.decodeResource(getResources(), R.mipmap.bossplane));

這樣就將敵機和我方機器繪製在了畫布上

如何繪製子彈

繪製子彈和繪製飛機的方法類似,建立一個子彈(bullet)類,在MySurfaceView中需要例項化子彈物件,然後將子彈的圖片上傳,我們還需要建立我方子彈,敵方子彈的陣列eg: private VectorbulletVector = new Vector <>();像這樣的一個數組用來存放子彈,呼叫bullet類,在bullet類中創造logic方法,用if語句進行判斷,分別進行判斷,並給玩家子彈和敵方子彈進行設定

這是先建立一個bullet類,子彈類,並在裡面建立方法,設定子彈的執行
這裡寫package com.example.administrator.myapplication9;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;

public class Bullet {
    private Bitmap bitmap;
    private int x, y;
    private int speed = 10;
    private boolean isDead;
    private int type;

    public Bullet(Bitmap bitmap, int x, int y,int type) {
        this.bitmap = bitmap;
        this.x = x;
        this.y = y;
        this.type = type;

    }

    public Bullet() {

    }

    public void draw(Canvas canvas, Paint paint) {
        canvas.drawBitmap(bitmap, x, y, paint);
        logic();
    }

    public void logic() {

        switch (type){
            //玩家子彈
            case 0:
                y -= speed+5;
                if (y < 0) {
                    isDead = true;
                }
                break;
            //Boss子彈
            case 1:
                y += speed+8;
                if (y < 0) {
                    isDead = true;
                }
                break;
                default:
                    break;
        }
    }

    public boolean isDead() {
        return isDead;
    }
    public Bitmap getBitmap(){
        return bitmap;
    }
    public int getX(){
        return x;
    }

    public int getY() {
        return y;
    }

    public void setDead(boolean dead) {
        isDead = dead;
    }
}

程式碼片
這是在MySurfacView中如何呼叫bullet類,並且進行例項化,用迴圈語句實現執行

這一段程式碼是在開始建立子彈的陣列

 private Vector<Bullet>bulletVector = new Vector <>();
    private Vector<Bullet>bossBulletVector = new Vector <>();
    private Vector<Bullet>boomVector = new Vector <>();
 public void run() {
        gameSoundPool.playSound(3);

        Paint paint = new Paint();
        BackGround backGround = new BackGround(BitmapFactory.decodeResource(getResources(), R.mipmap.img_bg_level_3));
        plane = new Myplane(BitmapFactory.decodeResource(getResources(), R.mipmap.myplane),BitmapFactory.decodeResource(getResources(), R.mipmap.myhp));
        BossPlane bossPlane = new BossPlane(BitmapFactory.decodeResource(getResources(), R.mipmap.bossplane));

        while (isDrawing) {
            count++;

            try {
                canvas = surfaceHolder.lockCanvas();//鎖定(選定)畫布
                canvas.drawColor(Color.WHITE);
             switch (GAME_STATE){

                 case 0:
                     backGround.draw(canvas, paint);
                     plane.draw(canvas, paint);
                     bossPlane.draw(canvas,paint);


                     if(count%20==0){
                         gameSoundPool.playSound(1);
                         Bullet bullet = new Bullet(BitmapFactory.decodeResource(getResources(), R.mipmap.mybullet),plane.getX(),plane.getY(),0);
                         Bullet bullet1 = new Bullet(BitmapFactory.decodeResource(getResources(), R.mipmap.mybullet),plane.getX()+plane.getWidth(),plane.getY(),0);
                         bulletVector.add(bullet);
                         bulletVector.add(bullet1);
                     }


                     for (int i = 0;i<bulletVector.size();i++) {

                         if (bulletVector.elementAt(i).isDead()) {
                             bulletVector.remove(i);

                         }
                     }
                     for (int i = 0;i<bulletVector.size();i++){

                         bulletVector.elementAt(i).draw(canvas,paint);
                         if (bossPlane.isCollision(bulletVector.elementAt(i))){
                             gameSoundPool.playSound(2);
                             Boom boom = new Boom(BitmapFactory.decodeResource(getResources(),R.mipmap.boom),bossPlane.getX()+bossPlane.getFrameW()/4,bossPlane.getY(),7);
                             boomVector.add(boom);
                         }
                     }

                     for (int i=0;i<boomVector.size();i++){
                         if (boomVector.elementAt(i).isDead()){
                             boomVector.remove(i);
                         }else{
                             boomVector.elementAt(i).draw(canvas,paint);
                         }
                     }

                     if(count%40==0){
                         Bullet bullet = new Bullet(BitmapFactory.decodeResource(getResources(), R.mipmap.bossbullet),bossPlane.getX()+bossPlane.getFrameW ()/2,bossPlane.getY()+bossPlane.getFrameH(),1);         
                         //Bullet bullet1 = new Bullet(BitmapFactory.decodeResource(getResources(), R.mipmap.bossbullet),bossPlane.getX()+bossPlane.getFrameW(),bossPlane.getY()+bossPlane.getFrameH(),1);
                         bossBulletVector.add(bullet);
                         // bossBulletVector.add(bullet1);
                     }

                     for (int i = 0;i < bossBulletVector.size(); i++) {

                         if (bossBulletVector.elementAt(i).isDead()) {
                             bossBulletVector.remove(i);

                         }
                     }
                     for (int i = 0;i < bossBulletVector.size(); i++){

                         bossBulletVector.elementAt(i).draw(canvas,paint);
                         plane.isCollision(bossBulletVector.elementAt(i));
                     }
                     plane.isCollision(bossPlane);
                        break;
                 case 1:
                     RectF rectF1 = new RectF(0,0,getWidth(),getHeight());
                     canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.gamewin),null,rectF1,paint);
                     break;
                 case 2:
                     RectF rectF = new RectF(0,0,getWidth(),getHeight());
                     canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),R.mipmap.gamelost),null,rectF,paint);
                     break;
             }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (canvas != null) {
                    surfaceHolder.unlockCanvasAndPost(canvas);//解鎖畫布,顯示到螢幕上
                }
            }

以上這一段是完整的一段run方法,裡面有子彈的繪製,還有如何執行程式,下面這一小段程式碼就是如何在MySurfaceView裡如何繪製子彈

 Bullet bullet = new Bullet(BitmapFactory.decodeResource(getResources(), R.mipmap.bossbullet),bossPlane.getX()+bossPlane.getFrameW()/2,bossPlane.getY()+bossPlane.getFrameH(),1);
                         //Bullet bullet1 = new Bullet(BitmapFactory.decodeResource(getResources(), R.mipmap.bossbullet),bossPlane.getX()+bossPlane.getFrameW(),bossPlane.getY()+bossPlane.getFrameH(),1);
                         bossBulletVector.add(bullet);
                         // bossBulletVector.add(bullet1);

例項化,然後將子彈繪製出來

如何判斷碰撞

在飛機大戰中碰撞分為兩種,飛機與飛機的碰撞,能夠子彈與飛機的碰撞,而這一段也是非常重要的,我們需要知道飛機的位置,get到飛機的位置,當我方飛機碰撞到敵方飛機的頂部,或子彈打到時,敵方飛機有爆炸效果(爆炸效果如何實現,下文會寫),左右時,我方飛機進行閃爍,同樣,當敵方子彈闖入我方飛機的範圍內,我方飛機閃爍,並且減少血量
在Myplane中建立兩個方法 noCollision(Boss),isCollision(myplane)
並用if語句進行條件判斷如果碰到血量就–

public void draw(Canvas canvas,Paint paint){
        if (hp<=0){
            MySurfaceView.GAME_STATE= 2;
        }
        if (noCollision){
            noCollisionCount++;
            if (noCollisionCount%10==0){
                canvas.drawBitmap(bitmap,x,y,paint);//飛機閃爍
            }
            if (noCollisionCount>100){//無敵時間
                noCollision = false;
                noCollisionCount = 0;
            }
        }else {
            //非無敵狀態
            canvas.drawBitmap(bitmap,x,y,paint);
        }

        for (int i = 0; i<hp; i++){
            canvas.drawBitmap(bitmapHp,i*bitmapHp.getWidth(),MySurfaceView.height-bitmapHp.getHeight(),paint);
        }

    }
    public void touchEvent(MotionEvent event){
        if (event.getAction()==MotionEvent.ACTION_MOVE){
            float ex = (int) event.getX();
            float ey = (int) event.getY();
            if (ex>x&&ex<x+width&&ey>y&&ey<y+height){
                x = (int) ex-width/2;
                y = (int) ey-height/2;
                if(y<0){
                    y=0;
                }
                if(y+height>MySurfaceView.height){
                    y=MySurfaceView.height-height;
                }
            }
        }
     `

``` public boolean isCollision(Bullet bullet){
        if (noCollision){
            return false;
        }else{
            if (bullet.getX()>x&&bullet.getX()<x+width&&bullet.getY()>y&&bullet.getY()<y+height){
                noCollision = true;
                if (hp>0){
                    hp--;
                }

                return true;
            }
        }
        return false;
    }


上面的這兩段程式碼實現的判斷碰撞,然後不同的飛機的不同反應






<div class="se-preview-section-delimiter"></div>

####如何繪製爆炸效果
當飛機子彈打到敵方飛機時會有爆炸效果,我們需要新建一個Bomm類





<div class="se-preview-section-delimiter"></div>

package com.example.administrator.myapplication9;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;

public class Boom extends Bullet {
private Bitmap bitmap;
private int x,y;
private int totalFrame;
private int currentFrame;
private int frameW,frameH;
private boolean isEnd;

public Boom(Bitmap bitmap, int x, int y, int totalFrame) {
    super();
    this.bitmap = bitmap;
    this.x = x;
    this.y = y;
    this.totalFrame = totalFrame;
    frameW = bitmap.getWidth()/totalFrame;
    frameH =  bitmap.getHeight();
}
public void  draw(Canvas canvas, Paint paint){
    canvas.save();
    canvas.clipRect(x,y,x+frameW,y+frameH);
    canvas.drawBitmap(bitmap,x-currentFrame*frameW,y,paint);
    canvas.restore();
    logic();

}
public void logic(){

    if (currentFrame<totalFrame){
        currentFrame++;
    }else{
        isEnd = true;
    }
}

public boolean isEnd() {
    return isEnd;
}

}

同樣我們需要get到位置,爆炸的效果是一幀一幀顯示的,並且在MySurfaceView中呼叫,運用for迴圈





<div class="se-preview-section-delimiter"></div>

for (int i = 0;i

package com.example.administrator.myapplication9;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

public class GameSoundPool {
    private SoundPool soundPool;
    private int s1;
    private int s2;
   private int s3;
-

    public GameSoundPool(Context context){
        this.soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC,0);
        s1 = soundPool.load(context,R.raw.shoot,1);
        s2 = soundPool.load(context,R.raw.explosion2,1);
       // s3 = soundPool.load(context,R.raw.bg_logobg,2);
    }
    public void playSound(int s) {
        switch (s){
            case 1:
               soundPool.play(s1,1,1,1,1,1.0f);
                break;
            case 2:
                soundPool.play(s2,1,1,1,1,1.0f);
                break;
            case 3:
               soundPool.play(s3,1,1,1,1,1.0f);
               break;
        }
    }
    }

用switch,case語句進行判斷,然後將在MySurfaceView中,將這些音樂寫入合適的位置,比如在boss發射子彈時執行哪一個音樂,音樂程式碼中的引數分別是左右聲道,音樂的播放速率。

相關推薦

JAVA第二專案飛機大戰步驟理解流程

專案簡單簡介 飛機大戰是整合這一個月實訓以來的成果,其中包括了所學的封裝,繼承,多型,方法的過載等多個知識點構成的一款簡單的小遊戲。經過一個禮拜的時間將此專案完成,由多個模組組成。 這個程式碼我們一共需要建立7個類 一.如何實現遊戲背景圖滾動播放

JAVA系列之第二分支:面向物件程式設計

想必剛入門的小白總是搞不清楚面向物件和麵向過程這兩個概念,雖然我在前面有所提及,但是都是泛泛而談,也有各種語言融入進去,不理解的會越來越暈,那麼,這節我就專門來講講什麼是JAVA的面向物件。 面向過程和麵向物件回顧 不記得概念的可以具體看看之前的文章,這裡僅做簡單的回顧: 面向過程 關注於流

Java專案——飛機大戰(一、實現執行緒繪製背景和我方飛機,鍵盤控制飛機運動)

1 總體需求分析 1.1 類 1、主類 2、我方飛機類 3、執行緒類 2.2 效果圖 2 實現 2.1 飛機類 MyPlane 飛機類包括以下引數: 位置x、y 速度vx、vy 圖片圖示myicom:設定為飛機的圖片   飛機類

JAVA在多方幫助下的第二系統—自助售賣系統

我們還是建立兩個類 寫一些屬性和 方法並建立set get方法 package com.lenovo.www.entity; public class Sales { private String goodsid; private St

java自己動手開發一個網站之建立專案及域名訪問(第5回)

新手小白,大神們看到什麼問題,請多多指出 目錄 一、建立專案  1.建立web專案,新增一個index.html頁面, 2.建立一個本地服務tomcat,並配置(檢驗tomcat是否成功,http://localhost:8080/) 3.後將專案新增進去,本地測試

JAVA系列之第五分支:LinkedList容器深入分析一

上一節我們瀏覽了ArrayList容器,來總結一下? 儲存資料的為一個名叫做elementData的陣列預設容量為10 擴容大小為原容量的一半即originSize+originSize>>2的大小 擴容方式為建立新的陣列並且通過陣列的複製來完成擴容 刪除

JAVA學習的第一程式碼—圖書管理系統

小白在實訓的學習實訓的第二週開始寫圖書管理系統程式碼,接下來是記錄學習的過程。 建立了一個Library 類和Booktest類 建立Library類對圖書管理系統 建立方法,然後在寫構造方法 package com.lenovo.w

Java入門學習筆記demo1輸出helloworld

out hello string 語句 返回 學習筆記 print [] system public class Hello{//公共 類 類名   public static void main(String[] args){ // 公共 靜態

Java的幹貨鋪子(四)

java 面向對象 面向對象編程學習筆記一.靈活對應——多態性 多態是指對於一種服務功能,可以具有不同的實現方式,即多種形態。多態形象的描述了現實世界的復雜形態,使程序具有良好的擴展性。在繼承的基礎上,方法的重載是實現多態的方式之一。 重點:Object類的toString()與equ

Java的幹貨鋪子(五)

roc tab 輸出信息 聲明 操作日期 返回 space sdf 特定 一.常用類1.Math類 Math 類提供了一序列基本數學運算和幾何函數的方法。 Math類是final類,並且它的所有成員變量和成員方法都是靜態的。jiduanz 常用的一些靜態方法:d

免費公開課-6月27日晚20點,Java到大牛之路

發的 路線圖 內容 優惠 RM 關東升 專題 ++ tex 講師主頁:http://edu.51cto.com/lecturer/701759.html【關東升老師】一個在IT領域摸爬滾打20多年的老程序員、培訓師、作者。移動開發專家,軟件架構師,高級培訓講師,IT作家。參

python+flask開發第二

web服務器 root 常用 ·· 組成 mouse port sheet targe 使用VSCode編譯python web頁面 1.先從最基礎的說起吧,關於VSCode的使用: 運行python程序與運行java,c,c++程序一樣,需要新建一個文件,第一個文件建議不

自學JavaSkip大神

2018年Java學習各階段配套視訊百度網盤開啟——菜霸plus推薦 感覺有用加關注,我會繼續更新 第1階段:Java語言入門 Java從入門到精通教程 https://pan.baidu.com/s/1pLc7AvL 第2階段:Java語言進階 Java高新技術教程 http://pa

java必看入門學習路線~~ (建議收藏哦!)

  java是一門通用的程式語言,其實可以幹很多事情,怎麼學java就看怎麼用了 熟悉一種文字編輯器,比如:vim,Emacs,Notepad++,TextMat等。知道哪些是開源的,哪些是閉源的,哪些要收費。養成不用盜版軟體的習慣。 最近看資料的時候,瀏覽到一個程式設計師小哥

java1

一、eclipse便捷操作 1,程式在遇到段錯誤時,便會直接中止程式,這會帶來一些損失,可以使用try關鍵詞對可能發生段錯誤進行捕捉異常。   選中程式碼段->右鍵->surround with->Try/Catch Block。   try{     程式碼段   }   ca

java自己動手開發一個網站之域名的申請(第4回)

新手小白,大神們看到什麼問題,請多多指出   目錄   域名的申請 域名的申請   之前想做部落格,聽說朋友用的阿里雲的域名很便宜,於是就過去申請了一個 登入賬號就是淘寶的賬號 地址: https://wanwang.al

java自己動手開發一個網站之技術選型(第3回)

新手小白,大神們看到什麼問題,請多多指出 目錄     MyWeb技術選型 一、域名 二 、網站空間 三 、開發環境: 四、框架選擇 1.前段 2.後端 五、資料庫 六、伺服器 MyWeb技術選型 一、域名 來

java自己動手開發一個網站之搭建一個網站需要啥(第2回)

新手小白,大神們看到什麼問題,請多多指出 目錄 新手小白,大神們看到什麼問題,請多多指出 搭建網站的流程 註冊域名 購買空間 製作網站 搭建網站的流程 搭建網站有哪些流程 1\註冊域名  2\購買空間  3\製作網站  &

java自己動手開發一個網站之立項(第1回)

新手小白,大神們看到什麼問題,請多多指出   MyWeb專案立項     修訂記錄表 修訂人 修訂版本 修訂描述 修訂時間 備註

我沒有“從入門到放棄”——3月的自學心得

2018年8月1日,我開始了java第一天 到現在3個月了~我沒有放棄! 那時候學習,完完全全就是跟著老師的節奏走~也就花了1個月的時間吧javase學完了。 這個時候我出現了一些瓶頸。以及在java上的懷疑。 瓶頸,就是我對專案的缺乏~還有別的系統知識,java不僅僅是java,它是一個系