From 29c1d47f42462c98af6bb64340e0569eb37693c1 Mon Sep 17 00:00:00 2001 From: bingor_yhj Date: Fri, 30 Sep 2022 16:31:48 +0800 Subject: [PATCH] =?UTF-8?q?=E5=9D=A6=E5=85=8B=E5=A4=A7=E6=88=98(=E4=B8=80?= =?UTF-8?q?=E6=9C=9F)-=E8=A7=A3=E5=86=B3=E9=97=AA=E7=83=81=E9=97=AE?= =?UTF-8?q?=E9=A2=98=EF=BC=88=E9=80=9A=E8=BF=87=E5=8F=8C=E7=BC=93=E5=86=B2?= =?UTF-8?q?=E8=A7=A3=E5=86=B3=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/com/msb/Bullet.java | 4 ++-- src/com/msb/Tank.java | 3 +++ src/com/msb/TankFrame.java | 24 ++++++++++++++++++++++-- 3 files changed, 27 insertions(+), 4 deletions(-) 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 {