diff --git a/src/main/java/com/example/tankbattle/Bullet.java b/src/main/java/com/example/tankbattle/Bullet.java index 01ad0a6..87ff41d 100644 --- a/src/main/java/com/example/tankbattle/Bullet.java +++ b/src/main/java/com/example/tankbattle/Bullet.java @@ -9,13 +9,19 @@ public class Bullet { private int x, y; private Dir dir; - public Bullet(int x, int y, Dir dir) { + public boolean live = true; + + private TankFrame tf; + + public Bullet(int x, int y, Dir dir, TankFrame tf) { this.x = x; this.y = y; this.dir = dir; + this.tf = tf; } public void paint(Graphics g) { + if (!live) tf.bullets.remove(this); Color c = g.getColor(); g.setColor(Color.RED); g.fillOval(x, y, WIDTH, HEIGHT); @@ -41,5 +47,7 @@ public class Bullet { default: break; } + + if (x < 0 || y < 0 || x > TankFrame.GAME_WIDTH || y > TankFrame.GAME_HEIGHT) live = false; } } diff --git a/src/main/java/com/example/tankbattle/Tank.java b/src/main/java/com/example/tankbattle/Tank.java index 0e6ee8b..b98aa51 100644 --- a/src/main/java/com/example/tankbattle/Tank.java +++ b/src/main/java/com/example/tankbattle/Tank.java @@ -67,6 +67,6 @@ public class Tank { } public void fire(){ - tf.bullets.add(new Bullet(this.x, this.y, this.dir)); + tf.bullets.add(new Bullet(this.x, this.y, this.dir, this.tf)); } } diff --git a/src/main/java/com/example/tankbattle/TankFrame.java b/src/main/java/com/example/tankbattle/TankFrame.java index 519336d..378dc95 100644 --- a/src/main/java/com/example/tankbattle/TankFrame.java +++ b/src/main/java/com/example/tankbattle/TankFrame.java @@ -9,13 +9,13 @@ import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.ArrayList; +import java.util.Iterator; import java.util.List; public class TankFrame extends Frame { Tank myTank = new Tank(200, 200, Dir.DOWN, this); - Bullet b = new Bullet(300, 300, Dir.DOWN); - private static final int GAME_WIDTH = 800,GAME_HEIGHT=600; + public static final int GAME_WIDTH = 800,GAME_HEIGHT=600; List bullets = new ArrayList<>(); @@ -50,11 +50,19 @@ public class TankFrame extends Frame { @Override public void paint(Graphics g) { + Color c = g.getColor(); + g.setColor(Color.WHITE); + g.drawString("子弹的数量" + bullets.size(), 10, 60); + g.setColor(c); + myTank.paint(g); - b.paint(g); - for (Bullet bullet1 : bullets) { - bullet1.paint(g); + for (int i = 0; i < bullets.size(); i++) { + bullets.get(i).paint(g); } +// for (Iterator it = bullets.iterator(); it.hasNext()) { +// Bullet b = it.next(); +// if (!b.live) it.remove(); +// } }