删除子弹,避免内存泄漏

master
kn5886348135 3 years ago
parent 58d564f4e2
commit 4f99e1cbc1

@ -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;
}
}

@ -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));
}
}

@ -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<Bullet> 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<Bullet> it = bullets.iterator(); it.hasNext()) {
// Bullet b = it.next();
// if (!b.live) it.remove();
// }
}

Loading…
Cancel
Save