From dbee942b0198d3e2fdbdbb41beb192643e470ac6 Mon Sep 17 00:00:00 2001 From: bingor_yhj Date: Mon, 3 Oct 2022 14:54:31 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9D=A6=E5=85=8B=E5=A4=A7=E6=88=98(=E4=B8=80?= =?UTF-8?q?=E6=9C=9F)-=E5=B9=B2=E6=8E=89=E6=95=8C=E6=96=B9=E5=9D=A6?= =?UTF-8?q?=E5=85=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/com/msb/Bullet.java | 22 ++++++++++++++++++++++ src/com/msb/Tank.java | 20 ++++++++++++++++++++ src/com/msb/TankFrame.java | 12 ++++++++++-- 3 files changed, 52 insertions(+), 2 deletions(-) diff --git a/src/com/msb/Bullet.java b/src/com/msb/Bullet.java index 5bc66f8..6d3da50 100644 --- a/src/com/msb/Bullet.java +++ b/src/com/msb/Bullet.java @@ -60,4 +60,26 @@ public class Bullet { if(x<0 || y<0 || x>TankFrame.GAME_WIDTH || y>TankFrame.GAME_HEIGHT) this.live = false; } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + //碰撞 + public void collide(Tank tank) { + Rectangle bullteRec = new Rectangle(this.x, this.y, WIDTH, HEIGHT); + Rectangle tankRec = new Rectangle(tank.getX(), tank.getY(), Tank.WIDTH, Tank.HEIGHT); + if(bullteRec.intersects(tankRec)) { + this.die(); + tank.die(); + } + } + + private void die() { + this.live = false; + } } diff --git a/src/com/msb/Tank.java b/src/com/msb/Tank.java index 2f32cdf..c505c2d 100644 --- a/src/com/msb/Tank.java +++ b/src/com/msb/Tank.java @@ -18,6 +18,7 @@ public class Tank { private TankFrame tankFrame; public static final int WIDTH = ResourcesMgr.tankD.getWidth(); public static final int HEIGHT = ResourcesMgr.tankD.getHeight(); + private boolean live = true; public Tank(int x, int y, DirEnum dir, TankFrame tankFrame) { this.x = x; @@ -27,6 +28,12 @@ public class Tank { } public void paint(Graphics g) { + + if( ! live) { + tankFrame.tanks.remove(this); + return; + } + /* Color color = g.getColor(); g.setColor(Color.YELLOW); g.fillRect(x, y, 50, 50); @@ -64,8 +71,21 @@ public class Tank { } public void fire() { + //子弹在坦克每个方向上的中心点应该是不一样的. TODO int bX = this.x + WIDTH/2 - Bullet.WIDTH/2; int bY = this.y+HEIGHT/2-Bullet.HEIGHT/2; tankFrame.bullets.add(new Bullet(bX, bY, this.dir, tankFrame)); } + + public int getX() { + return x; + } + + public int getY() { + return y; + } + + public void die() { + this.live = false; + } } diff --git a/src/com/msb/TankFrame.java b/src/com/msb/TankFrame.java index cc5cf4a..00c0dc1 100644 --- a/src/com/msb/TankFrame.java +++ b/src/com/msb/TankFrame.java @@ -50,17 +50,25 @@ public class TankFrame extends Frame { Color color = g.getColor(); g.setColor(Color.WHITE); g.drawString("子弹的数量:" + bullets.size(), 10, 60); + g.drawString("敌方坦克数量:" + tanks.size(), 10, 90); g.setColor(color); tank.paint(g); //画出敌方坦克 - for (Tank tank : tanks) { - tank.paint(g); + for (int i=0; i