坦克大战(一期)-完成子弹的可持续发射,并且子弹飞出边界的时候将字段从容器中移除,避免出现内存溢出

Network
bingor_yhj 2 years ago
parent 87698795ef
commit 7fa73e7ddd

@ -15,14 +15,22 @@ public class Bullet extends Frame {
public static final int WIDTH = 20; public static final int WIDTH = 20;
public static final int HEIGHT = 20; public static final int HEIGHT = 20;
public static final int SPEED = 5; 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.x = x;
this.y = y; this.y = y;
this.dir = dir; this.dir = dir;
this.tankFrame = tankFrame;
} }
public void paint(Graphics g) { public void paint(Graphics g) {
if( ! this.live) {
tankFrame.bullets.remove(this);
return;
}
Color color = g.getColor(); Color color = g.getColor();
g.setColor(Color.RED); g.setColor(Color.RED);
g.fillOval(x, y, WIDTH, HEIGHT); g.fillOval(x, y, WIDTH, HEIGHT);
@ -40,5 +48,7 @@ public class Bullet extends Frame {
default: break; default: break;
} }
if(x<0 || y<0 || x>TankFrame.GAME_WIDTH || y>TankFrame.GAME_HEIGHT) this.live = false;
} }
} }

@ -55,6 +55,6 @@ public class Tank {
} }
public void fire() { 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));
} }
} }

@ -5,6 +5,8 @@ import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent; import java.awt.event.KeyEvent;
import java.awt.event.WindowAdapter; import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent; import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects; import java.util.Objects;
/** /**
@ -16,7 +18,8 @@ import java.util.Objects;
public class TankFrame extends Frame { public class TankFrame extends Frame {
Tank tank = new Tank(200, 200, DirEnum.RIGHT, this); 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<Bullet> bullets = new ArrayList<>();
public static final int GAME_WIDTH = 800; public static final int GAME_WIDTH = 800;
public static final int GAME_HEIGHT = 600; public static final int GAME_HEIGHT = 600;
@ -42,8 +45,14 @@ public class TankFrame extends Frame {
@Override @Override
public void paint(Graphics g) { public void paint(Graphics g) {
// super.paint(g); // super.paint(g);
Color color = g.getColor();
g.setColor(Color.BLACK);
g.drawString("子弹的数量:" + bullets.size(), 10, 60);
g.setColor(color);
tank.paint(g); tank.paint(g);
bullet.paint(g); for (int i=0; i<bullets.size(); i++) {
bullets.get(i).paint(g);
}
} }
//双缓冲,解决闪烁现象 //双缓冲,解决闪烁现象

Loading…
Cancel
Save