抽象出坦克类,封装相应的属性和方法

Network
bingor_yhj 2 years ago
parent 941e07407c
commit a721578f24

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

@ -14,10 +14,7 @@ import java.awt.event.WindowEvent;
*/ */
public class TankFrame extends Frame { public class TankFrame extends Frame {
private int x = 200; Tank tank = new Tank(200, 200, DirEnum.RIGHT);
private int y = 200;
private DirEnum dir = DirEnum.RIGHT;
private static final int SPEED = 10;
public TankFrame() { public TankFrame() {
@ -41,15 +38,7 @@ public class TankFrame extends Frame {
@Override @Override
public void paint(Graphics g) { public void paint(Graphics g) {
super.paint(g); super.paint(g);
g.fillRect(x, y, 50, 50); tank.paint(g);
switch (dir) {
case UP: y -= SPEED; break;
case DOWN: y += SPEED; break;
case LEFT: x -= SPEED; break;
case RIGHT: x += SPEED; break;
default: break;
}
} }
//这里使用内部内的原因是只有TankFrame用到 //这里使用内部内的原因是只有TankFrame用到
@ -88,10 +77,10 @@ public class TankFrame extends Frame {
private void setDir() { private void setDir() {
//为什么不用if-else 因为有可能是一起按两个方向键,那最后拿到哪个算哪个 //为什么不用if-else 因为有可能是一起按两个方向键,那最后拿到哪个算哪个
if(bL) dir = DirEnum.LEFT; if(bL) tank.setDir(DirEnum.LEFT);
if(bR) dir = DirEnum.RIGHT; if(bR) tank.setDir(DirEnum.RIGHT);
if(bU) dir = DirEnum.UP; if(bU) tank.setDir(DirEnum.UP);
if(bD) dir = DirEnum.DOWN; if(bD) tank.setDir(DirEnum.DOWN);
} }
} }

Loading…
Cancel
Save