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