diff --git a/src/com/msb/Bullet.java b/src/com/msb/Bullet.java index 9e98e77..e3f4e2c 100644 --- a/src/com/msb/Bullet.java +++ b/src/com/msb/Bullet.java @@ -12,8 +12,8 @@ public class Bullet extends Frame { private int x, y; private DirEnum dir; - public static final int WIDTH = 8; - public static final int HEIGHT = 8; + public static final int WIDTH = 20; + public static final int HEIGHT = 20; public static final int SPEED = 5; public Bullet(int x, int y, DirEnum dir) { diff --git a/src/com/msb/Tank.java b/src/com/msb/Tank.java index 8efc0c6..13c59ea 100644 --- a/src/com/msb/Tank.java +++ b/src/com/msb/Tank.java @@ -22,7 +22,10 @@ public class Tank { } public void paint(Graphics g) { + Color color = g.getColor(); + g.setColor(Color.YELLOW); g.fillRect(x, y, 50, 50); + g.setColor(color); moving(); } diff --git a/src/com/msb/TankFrame.java b/src/com/msb/TankFrame.java index 3260ece..45eb69b 100644 --- a/src/com/msb/TankFrame.java +++ b/src/com/msb/TankFrame.java @@ -5,6 +5,7 @@ import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; +import java.util.Objects; /** * @Author bingor @@ -16,11 +17,13 @@ public class TankFrame extends Frame { Tank tank = new Tank(200, 200, DirEnum.RIGHT); Bullet bullet = new Bullet(200, 200, DirEnum.DOWN); + public static final int GAME_WIDTH = 800; + public static final int GAME_HEIGHT = 600; public TankFrame() { setTitle("Tank war"); - setSize(800, 600); + setSize(GAME_WIDTH, GAME_HEIGHT); setResizable(true); setVisible(true); @@ -38,11 +41,28 @@ public class TankFrame extends Frame { @Override public void paint(Graphics g) { - super.paint(g); +// super.paint(g); tank.paint(g); bullet.paint(g); } + //双缓冲,解决闪烁现象 + Image offScreenImage = null; + @Override //在paint方法之前会被调用,但是我做实验了,闪烁现象似乎还是存在 + public void update(Graphics g) { +// super.update(g); + if(Objects.isNull(offScreenImage)) { + offScreenImage = this.createImage(GAME_WIDTH, GAME_HEIGHT); + } + Graphics gOffScreen = offScreenImage.getGraphics(); + Color color = gOffScreen.getColor(); + gOffScreen.setColor(Color.WHITE); + gOffScreen.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT); + gOffScreen.setColor(color); + paint(gOffScreen); + g.drawImage(offScreenImage, 0, 0, null); + } + //这里使用内部内的原因是,只有TankFrame用到 class MyKeyListener extends KeyAdapter {