知識回顧:上一個版本我們已經可以通過按空格鍵打出子彈,並且解決了子彈數量的內存泄漏問題。子彈通過坦克移動的不同方向去發射不同方向的子彈。
1.將坦克、子彈換成圖片
思路:1.新建一個image文件夾,然後加入你所需要的圖片;具體看GitHub源碼2.新建一個ResourceMgr,把坦克的圖片load到內存中;3.在Tank類裏面,重新畫出這張圖片(默認向下)
public class ResourceMgr {
public static BufferedImage tankL, tankU, tankR, tankD;
public static BufferedImage bulletL,bulletU,bulletR,bulletD;
static {
try {
//引入Tank圖片
tankL = ImageIO.read(ResourceMgr.class.getClassLoader().getResourceAsStream("images/tankL.gif"));
tankU = ImageIO.read(ResourceMgr.class.getClassLoader().getResourceAsStream("images/tankU.gif"));
tankR = ImageIO.read(ResourceMgr.class.getClassLoader().getResourceAsStream("images/tankR.gif"));
tankD = ImageIO.read(ResourceMgr.class.getClassLoader().getResourceAsStream("images/tankD.gif"));
//引入bullet的圖片
bulletL = ImageIO.read(ResourceMgr.class.getClassLoader().getResourceAsStream("images/bulletL.gif"));
bulletU = ImageIO.read(ResourceMgr.class.getClassLoader().getResourceAsStream("images/bulletU.gif"));
bulletR = ImageIO.read(ResourceMgr.class.getClassLoader().getResourceAsStream("images/bulletR.gif"));
bulletD = ImageIO.read(ResourceMgr.class.getClassLoader().getResourceAsStream("images/bulletD.gif"));
} catch (IOException e) {
e.printStackTrace();
}
}
2.將子彈從坦克中心位置打出
fire()方法開火時:計算中心位置
int bX = this.x + Tank.WIDTH/2 - Bullet.WIDTH/2;
int bY = this.y + Tank.HEIGHT/2 - Bullet.HEIGHT/2;
tf.bullets.add(new Bullet(bX, bY, this.dir, this.tf));
3.加入敵軍坦克
要求畫出5個坦克在界面上
思路:在TankFrame類裏面new一個list集合,在paint中畫出5個坦克就好了。
List<Tank> tanks = new ArrayList<>;
4.子彈與坦克的碰撞檢查
思路:打掉敵人坦克,需要碰撞檢測過程,兩個list每一顆子彈每一個坦克都要做碰撞檢測,如果撞上了,坦克死,子彈死
//子彈和坦克的碰撞檢測
public void collideWith(Tank tank) {
Rectangle rectBullet = new Rectangle(this.x,this.y,BULLET_WIDTH,BULLET_HEIGHT);
Rectangle rectTank =new Rectangle(tank.getX(),tank.getY(),tank.tankWidth,tank.tankHeight);
if(rectBullet.intersects(rectTank)) {
tank.die();
this.die();
}
}
private void die() {
this.living = false;
}
5.讓敵軍坦克動起來
區分敵我,默認不開啓隊友傷害,敵人坦克隨機發射子彈
思路:1.區分敵我和區分坦克的方向是一個思路,新建一個Group枚舉類,區分敵我坦克
public enum Group {
GOOD,BAD
}
主站Tank設置爲爲Gourp.good,所有的坦克爲Group.bad
6.加入爆炸
思路:在ResourceMgr中引入爆炸的圖片,因爲爆炸動畫爲連續的,所以引入一個爆炸的數組,然後新建一個類畫出爆炸和子彈、坦克類類似
public static BufferedImage [] expodes = new BufferedImage[16];
for(int i=0 ;i<16;i++){
expodes [i] = ImageIO.read(ResourceMgr.class.getClassLoader().getResourceAsStream("images/e"+(i+1)+".gif"));
}
public class Explode {
public static int WIDTH = ResourceMgr.explodes[0].getWidth();
public static int HEIGHT = ResourceMgr.explodes[0].getHeight();
private int x, y;
private boolean living = true;
TankFrame tf = null;
private int step = 0;
public Explode(int x, int y, TankFrame tf) {
this.x = x;
this.y = y;
this.tf = tf;
}
public void paint(Graphics g) {
g.drawImage(ResourceMgr.explodes[step++], x, y, null);
if(step >= ResourceMgr.explodes.length)
step = 0;
}
}