diff --git a/src/com/msb/Bullet.java b/src/com/msb/Bullet.java index e3f4e2c..12083bf 100644 --- a/src/com/msb/Bullet.java +++ b/src/com/msb/Bullet.java @@ -15,14 +15,22 @@ public class Bullet extends Frame { public static final int WIDTH = 20; public static final int HEIGHT = 20; public static final int SPEED = 5; + private boolean live = true; + private TankFrame tankFrame; - public Bullet(int x, int y, DirEnum dir) { + public Bullet(int x, int y, DirEnum dir, TankFrame tankFrame) { this.x = x; this.y = y; this.dir = dir; + this.tankFrame = tankFrame; } public void paint(Graphics g) { + if( ! this.live) { + tankFrame.bullets.remove(this); + return; + } + Color color = g.getColor(); g.setColor(Color.RED); g.fillOval(x, y, WIDTH, HEIGHT); @@ -40,5 +48,7 @@ public class Bullet extends Frame { default: break; } + if(x<0 || y<0 || x>TankFrame.GAME_WIDTH || y>TankFrame.GAME_HEIGHT) this.live = false; + } } diff --git a/src/com/msb/Tank.java b/src/com/msb/Tank.java index 64835ed..2df4bea 100644 --- a/src/com/msb/Tank.java +++ b/src/com/msb/Tank.java @@ -55,6 +55,6 @@ public class Tank { } public void fire() { - tankFrame.bullet = new Bullet(this.x, this.y, this.dir); + tankFrame.bullets.add(new Bullet(this.x, this.y, this.dir, tankFrame)); } } diff --git a/src/com/msb/TankFrame.java b/src/com/msb/TankFrame.java index 9cfc408..9163f89 100644 --- a/src/com/msb/TankFrame.java +++ b/src/com/msb/TankFrame.java @@ -5,6 +5,8 @@ import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; +import java.util.ArrayList; +import java.util.List; import java.util.Objects; /** @@ -16,7 +18,8 @@ import java.util.Objects; public class TankFrame extends Frame { Tank tank = new Tank(200, 200, DirEnum.RIGHT, this); - Bullet bullet = new Bullet(200, 200, DirEnum.DOWN); +// Bullet bullet = new Bullet(200, 200, DirEnum.DOWN); + List bullets = new ArrayList<>(); public static final int GAME_WIDTH = 800; public static final int GAME_HEIGHT = 600; @@ -42,8 +45,14 @@ public class TankFrame extends Frame { @Override public void paint(Graphics g) { // super.paint(g); + Color color = g.getColor(); + g.setColor(Color.BLACK); + g.drawString("子弹的数量:" + bullets.size(), 10, 60); + g.setColor(color); tank.paint(g); - bullet.paint(g); + for (int i=0; i