From a721578f240d263471680edd6bd0230454652dd3 Mon Sep 17 00:00:00 2001 From: bingor_yhj Date: Fri, 30 Sep 2022 11:10:17 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8A=BD=E8=B1=A1=E5=87=BA=E5=9D=A6=E5=85=8B?= =?UTF-8?q?=E7=B1=BB=EF=BC=8C=E5=B0=81=E8=A3=85=E7=9B=B8=E5=BA=94=E7=9A=84?= =?UTF-8?q?=E5=B1=9E=E6=80=A7=E5=92=8C=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/com/msb/Tank.java | 38 ++++++++++++++++++++++++++++++++++++++ src/com/msb/TankFrame.java | 23 ++++++----------------- 2 files changed, 44 insertions(+), 17 deletions(-) create mode 100644 src/com/msb/Tank.java diff --git a/src/com/msb/Tank.java b/src/com/msb/Tank.java new file mode 100644 index 0000000..74ba32f --- /dev/null +++ b/src/com/msb/Tank.java @@ -0,0 +1,38 @@ +package com.msb; + +import java.awt.*; + +/** + * @Author bingor + * @Date 2022-09-29 21:53 + * @Description: com.msb + * @Version: 1.0 + */ +public class Tank { + + private int x,y; + private DirEnum dir; + private static final int SPEED = 10; + + public Tank(int x, int y, DirEnum dir) { + this.x = x; + this.y = y; + this.dir = dir; + } + + public void paint(Graphics g) { + g.fillRect(x, y, 50, 50); + + switch (dir) { + case UP: y -= SPEED; break; + case DOWN: y += SPEED; break; + case LEFT: x -= SPEED; break; + case RIGHT: x += SPEED; break; + default: break; + } + } + + public void setDir(DirEnum dir) { + this.dir = dir; + } +} diff --git a/src/com/msb/TankFrame.java b/src/com/msb/TankFrame.java index 2381bfc..eb100e6 100644 --- a/src/com/msb/TankFrame.java +++ b/src/com/msb/TankFrame.java @@ -14,10 +14,7 @@ import java.awt.event.WindowEvent; */ public class TankFrame extends Frame { - private int x = 200; - private int y = 200; - private DirEnum dir = DirEnum.RIGHT; - private static final int SPEED = 10; + Tank tank = new Tank(200, 200, DirEnum.RIGHT); public TankFrame() { @@ -41,15 +38,7 @@ public class TankFrame extends Frame { @Override public void paint(Graphics g) { super.paint(g); - g.fillRect(x, y, 50, 50); - - switch (dir) { - case UP: y -= SPEED; break; - case DOWN: y += SPEED; break; - case LEFT: x -= SPEED; break; - case RIGHT: x += SPEED; break; - default: break; - } + tank.paint(g); } //这里使用内部内的原因是,只有TankFrame用到 @@ -88,10 +77,10 @@ public class TankFrame extends Frame { private void setDir() { //为什么不用if-else 因为有可能是一起按两个方向键,那最后拿到哪个算哪个 - if(bL) dir = DirEnum.LEFT; - if(bR) dir = DirEnum.RIGHT; - if(bU) dir = DirEnum.UP; - if(bD) dir = DirEnum.DOWN; + if(bL) tank.setDir(DirEnum.LEFT); + if(bR) tank.setDir(DirEnum.RIGHT); + if(bU) tank.setDir(DirEnum.UP); + if(bD) tank.setDir(DirEnum.DOWN); } }