course2 tank move and stop

master
Jian Hu 3 years ago
parent a5dc4a3a21
commit 680f087b25

Binary file not shown.

@ -1,10 +1,11 @@
package com.demo.tank.coruse2; package com.demo.tank.coruse2;
import com.demo.tank.coruse1.TankFrame;
public class MainV2 { public class MainV2 {
public static void main(String[] args){ public static void main(String[] args) throws InterruptedException {
TankFrame tf = new TankFrame(); TankFrame tf = new TankFrame();
while (true){
Thread.sleep(50);
tf.repaint(); tf.repaint();
} }
}
} }

@ -1,11 +1,11 @@
package com.demo.tank.coruse2; package com.demo.tank.coruse2;
import java.awt.*; import java.awt.*;
public class Tank { public class Tank {
private int x,y; private int x,y;
private Direction dir; private Direction dir;
private static final int SPEED = 10; private static final int SPEED = 10;
private boolean moving;
public Tank(int x, int y, Direction dir) { public Tank(int x, int y, Direction dir) {
@ -16,6 +16,12 @@ public class Tank {
public void paint(Graphics g) { public void paint(Graphics g) {
g.fillRect(x, y,50,50); g.fillRect(x, y,50,50);
move();
}
public void move(){
//如果没有移动 return
if(!moving) return;
switch (dir){ switch (dir){
case UP: y -= SPEED; case UP: y -= SPEED;
break; break;
@ -53,4 +59,12 @@ public class Tank {
public void setDir(Direction dir) { public void setDir(Direction dir) {
this.dir = dir; this.dir = dir;
} }
public boolean isMoving() {
return moving;
}
public void setMoving(boolean moving) {
this.moving = moving;
}
} }

@ -77,10 +77,15 @@ public class TankFrame extends Frame {
} }
public void setTankDirection(){ public void setTankDirection(){
if(!bL && !bR && !bU && !bD){
tank.setMoving(false);
}else{
tank.setMoving(true);
if(bL) tank.setDir(Direction.LEFT); if(bL) tank.setDir(Direction.LEFT);
if(bR) tank.setDir(Direction.RIGHT); if(bR) tank.setDir(Direction.RIGHT);
if(bU) tank.setDir(Direction.UP); if(bU) tank.setDir(Direction.UP);
if(bD) tank.setDir(Direction.DOWN); if(bD) tank.setDir(Direction.DOWN);
} }
} }
}
} }

Loading…
Cancel
Save