1. 程式人生 > >【Java_專案篇】--JAVA實現坦克大戰遊戲--坦克發射子彈(三)

【Java_專案篇】--JAVA實現坦克大戰遊戲--坦克發射子彈(三)

前期相關文章

一、任務需求

新增hero坦克子彈並且發射。

二、思路

1.建立子彈類

1.由於每顆子彈都是一個獨立的執行緒,會不斷變換子彈座標,所以子彈類要實現Runnable介面。
2.子彈需要座標x,y以及方向,所以建構函式有三個引數。
3.實現Runnable介面後,要覆蓋run方法:
    1.如果不讓執行緒sleep,子彈飛出去很快,快到在螢幕如上瞬間消失。
    2.所以增加一個sleep()
    3.另外,子彈需要判斷四個方向,增加switch語句
    4.子彈跑出螢幕需要死亡,增加變數islive判斷是否存活。否則無限制飛行,不斷佔用記憶體空間。

2.hero坦克類中加入shotEnemy()方法,表示發射子彈

1.新建子彈變數s
    Shot s = null;
2.判斷開火的方向,增加switch語句。
3.開火後,啟動執行緒。
Thread t =new Thread(s);
    t.start();

3.完成子彈實現過程,接著要在螢幕中讓子彈顯示,即畫出子彈

1.paintComponent方法里加入,畫出子彈
    判斷子彈是否存活
    hero.s!=null很重要,遊戲剛開始沒有發射子彈,hero.s=null,此時進入if去畫子彈會出現異常。
    if(hero.s!=null&&hero.s.isLive==true){
        g.setColor(Color.red);
        g.draw3DRect(hero.s.x, hero.s.y, 1, 1, false);
    }
2.在KeyPressed監聽器處新增,按下J鍵發射一顆子彈
    if(e.getKeyCode()==KeyEvent.VK_J){
        hero.shotEnemy();
    }

4.MyPanel實現Runnable介面

1.由於子彈打出去後,需要不斷讓它顯示,螢幕每隔一段時間需要repaint()
    所以過載run()方法,讓MyPanel每隔一段時間repaint()一次
    public void run() {
    while(true){
        try {
            Thread.sleep(100);//休息100ms,重畫一次MyPanel
        } catch (Exception e) {
            e.printStackTrace();
        }
        repaint();
    }

5.由於MyPanel實現了Runnable介面,所以讓該執行緒跑起來

1.在MyTankGame方法中啟動執行緒即可
    p1 = new MyPanel();
        Thread t = new Thread(p1);
        t.start();

三、程式碼如下

MyTankGame.java

這裡寫圖片描述

/**
 * 功能:坦克遊戲的2.0
 * 1.畫出坦克
 * 2.坦克的移動
 * 3.坦克發射子彈
 */

package Tank_03;

import java.awt.Color;
import java.awt.Graphics;


import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Vector;

import javax.swing.JFrame;
import javax.swing.JPanel;

@SuppressWarnings("serial")
public class MyTankGame2 extends JFrame{

    MyPanel p1 = null;

    public MyTankGame2(){
        p1 = new MyPanel();
        Thread t = new Thread(p1);
        t.start();
        add(p1);
        setSize(400, 300);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        addKeyListener(p1);//註冊監聽

    }

    public static void main(String[] args) {
         new MyTankGame2();
    }
}

//畫圖
@SuppressWarnings("serial")
class MyPanel extends JPanel implements KeyListener,Runnable{

    Hero hero = null;
    Vector<EnemyTank> ets = new Vector<EnemyTank>();
    int enSize = 3;

    public MyPanel(){
        hero = new Hero(100,100);//設定坦克出現的位置(10,10)
        // 初始化敵人的坦克
        for(int i=0;i<enSize;i++){
            //建立對人的坦克物件
            EnemyTank et =new EnemyTank((i+1)*30,0);
            et.setColor(1);
            et.setDirect(1);
            ets.add(et);
        }
    }

    protected void paintComponent(Graphics g){

        super.paintComponent(g);

        g.fillRect(0, 0, 400, 300);//背景填充

        //畫出我方坦克
        drawTank(hero.getX(),hero.getY(),g,hero.Direct,0);//一定要傳入畫筆g

        //畫出子彈
        if(hero.s!=null&&hero.s.isLive==true){
//          System.out.format("%d %d  ", hero.s.x,hero.s.y);            
            g.setColor(Color.red);
            g.draw3DRect(hero.s.x, hero.s.y, 1, 1, false);
        }
        //畫出敵方坦克
        for(int i=0;i<ets.size();i++){
            drawTank(ets.get(i).getX(), ets.get(i).getY(), g, ets.get(i).getDirect(), ets.get(i).getColor());
        }


    }

    /*
     * drawTank (坦克座標x,y,畫筆g,方向,坦克型別)
     * 方法介紹:
     *      可以設定-->坦克的顏色(型別:敵方坦克,我方坦克),方向,出現的座標
     * 
     * 如果type是default 則預設顏色為畫出黑色坦克
     * 
     * 封裝性:將坦克封裝到方法中。
     * 
     */

    public void drawTank(int x,int y,Graphics g,int direct,int type){
        switch (type) {
        case 0:
            g.setColor(Color.cyan);
            break;
        case 1:
            g.setColor(Color.yellow);
        default:
            break;
        }
        switch (direct) {
        case 0:
            //向上
            g.fill3DRect(x   , y    , 5 , 30, false);
            g.fill3DRect(x+15, y    , 5 , 30, false);
            g.fill3DRect(x+5 , y+5  , 10, 20, false);
            g.fillOval(x+4, y+10, 10 , 10);
            g.drawLine(x+9, y+15, x+9, y );
            break;
        case 1:
            //向下w
            g.fill3DRect(x   , y    , 5 , 30, false);
            g.fill3DRect(x+15, y    , 5 , 30, false);
            g.fill3DRect(x+5 , y+5  , 10, 20, false);
            g.fillOval(x+4, y+10, 10 , 10);
            g.drawLine(x+9, y+15, x+9, y+30 );
            break;
        case 2:
            //向左
            g.fill3DRect(x   , y    , 30, 5 , false);
            g.fill3DRect(x   , y+15 , 30, 5 , false);
            g.fill3DRect(x+5 , y+5  , 20, 10, false);
            g.fillOval(x+9 , y+4, 10  , 10 );
            g.drawLine(x+5, y+9, x-4, y+9);
            break;
        case 3:
            //向右
            g.fill3DRect(x   , y    , 30, 5 , false);
            g.fill3DRect(x   , y+15 , 30, 5 , false);
            g.fill3DRect(x+5 , y+5  , 20, 10, false);
            g.fillOval(x+9 , y+4, 10  , 10 );
            g.drawLine(x+15, y+9, x+30, y+9);
            break;
        default:
            break;
        }
        //repaint();  因為監聽器裡面有repaint()  所以不用在加repaint()了
    }

    @Override
    public void keyTyped(KeyEvent e) {
    }

    @Override
    public void keyPressed(KeyEvent e) {//實現介面 根據按鍵上下左右移動 可以控制速度和移動
        if(e.getKeyCode()==KeyEvent.VK_W){
            hero.setDirect(0);
            hero.moveUp();
        }else if(e.getKeyCode()==KeyEvent.VK_S){
            hero.setDirect(1);
            hero.moveDown();
        }else if(e.getKeyCode()==KeyEvent.VK_A){
            hero.setDirect(2);
            hero.moveLeft();
        }else if(e.getKeyCode()==KeyEvent.VK_D){
            hero.setDirect(3);
            hero.moveRight();
        }
        if(e.getKeyCode()==KeyEvent.VK_J){
            //開火
            hero.shotEnemy();
        }
        //判斷玩家是否按下J攻擊鍵
        repaint();
    }

    @Override
    public void keyReleased(KeyEvent e) {
    }
    //@Override
    public void run() {
        //每隔100毫秒 重新畫圖
        while(true){
            try {
                Thread.sleep(100);
            } catch (Exception e) {
                e.printStackTrace();
            }
            repaint();
        }
    }
}

members.java

package Tank_03;



//坦克父類  可以設定坦克出現位置(x,y)
class Tank {
    int x = 0;
    int y = 0;
    int speed = 10;
    int Direct = 0;
    int color;
    public int getColor() {
        return color;
    }
    public void setColor(int color) {
        this.color = color;
    }
    public int getDirect() {
        return Direct;
    }
    public void setDirect(int direct) {
        Direct = direct;
    }
    public int getSpeed() {
        return speed;
    }
    public void setSpeed(int speed) {
        this.speed = speed;
    }
    public Tank (int x,int y){
        this.x = x;
        this.y = y;
    }
    public int getX() {
        return x;
    }
    public void setX(int x) {
        this.x = x;
    }
    public int getY() {
        return y;
    }
    public void setY(int y) {
        this.y = y;
    }


    //視訊中是把移動放在hero類中

}
//敵方坦克
class EnemyTank extends Tank{

    public EnemyTank(int x, int y) {
        super(x, y);
    }
}
//我的英雄坦克
class Hero extends Tank{

    //子彈
    Shot s = null;

    public Hero(int x,int y){
        super(x, y);
    }
    //開火
    public void shotEnemy(){

        switch (Direct) {
        case 0:
            s = new Shot(x+8,y-4,0);
            break;
        case 1:
            s = new Shot(x+9,y+32,1);
            break;
        case 2: 
            s = new Shot(x-8,y+8,2);
            break;
        case 3:
            s = new Shot(x+32,y+9,3);
            break;
        default:
            break;
        }
        Thread t =new Thread(s);
        t.start();
    }
    public void moveUp(){
        y-=speed;
    }
    public void moveDown(){
        y+=speed;
    }
    public void moveLeft(){
        x-=speed;
    }
    public void moveRight(){
        x+=speed;
    }
}
//子彈類
class Shot implements Runnable{
    int x;
    int y;
    int Direct; 
    int speed = 5;
    boolean isLive = true;
    public Shot(int x,int y,int Direct){
        this.x=x;
        this.y=y;
        this.Direct = Direct;
    }
    @Override

    public void run() {
        while(true){
            try {
                Thread.sleep(50);
            } catch (Exception e) {
                // TODO: handle exception
            }
            switch(Direct){
            case 0: 
                y-=speed;
                break;
            case 1:
                y+=speed;
                break;
            case 2:
                x-=speed;
                break;
            case 3:
                x+=speed;
                break;
            default:
                break;
            }

//          System.out.println(""+x+" "+y);
            //子彈何時死亡
            if(x<0||x>400||y<0||y>300){
                isLive = false;
                break;
            }
        }
    }
}

四、效果圖

這裡寫圖片描述