Tank.java
上传用户:cswwx88
上传日期:2021-03-26
资源大小:9k
文件大小:3k
- import java.awt.*;
- import java.awt.event.KeyEvent;
- public class Tank {
-
- private int x,y;
- private int XSpeed = 4;
- private int YSpeed = 4;
- public static final int WIDTH = 20;
- public static final int HEIGHT = 20;
- private TankClient tc =null;
-
- enum Direction{U,RU,R,RD,D,LD,L,LU,STOP};
- private Direction dir = Direction.STOP;
- boolean keyU = false, keyD = false, keyR = false, keyL = false;
-
- public Tank (int x ,int y){
- this.x = x;
- this.y = y;
-
- }
-
- public Tank(int x,int y,TankClient tc){
- this(x,y);
- this.tc = tc;
- }
-
- public void draw(Graphics g){
- Color c = g.getColor();
- g.setColor(Color.red);
- g.fillOval(x,y,WIDTH,HEIGHT);
- g.setColor(c);
- move();
- }
-
- public void keyPressed(KeyEvent e){
- int key = e.getKeyCode();
- switch(key){
- case KeyEvent.VK_CONTROL:
- tc.myMissile = fire();
- break;
- case KeyEvent.VK_UP:
- keyU = true;
- break;
- case KeyEvent.VK_DOWN:
- keyD = true;
- break;
- case KeyEvent.VK_LEFT:
- keyL = true;
- break;
- case KeyEvent.VK_RIGHT:
- keyR = true;
- break;
- }
- tankDirection();
- }
-
- public void keyReleased(KeyEvent e){
- int key = e.getKeyCode();
- switch(key){
- case KeyEvent.VK_UP:
- keyU = false;
- break;
- case KeyEvent.VK_DOWN:
- keyD = false;
- break;
- case KeyEvent.VK_LEFT:
- keyL = false;
- break;
- case KeyEvent.VK_RIGHT:
- keyR = false;
- break;
- }
- }
-
- public void tankDirection (){
- if (keyU&&!keyR&&!keyD&&!keyL){
- dir = Direction.U;
- }
- else if (keyU&&keyR&&!keyD&&!keyL){
- dir = Direction.RU;
- }
- else if (!keyU&&keyR&&!keyD&&!keyL){
- dir = Direction.R;
- }
- else if (!keyU&&keyR&&keyD&&!keyL){
- dir = Direction.RD;
- }
- else if (!keyU&&!keyR&&keyD&&!keyL){
- dir = Direction.D;
- }
- else if (!keyU&&!keyR&&keyD&&keyL){
- dir = Direction.LD;
- }
- else if (!keyU&&!keyR&&!keyD&&keyL){
- dir = Direction.L;
- }
- else if (keyU&&!keyR&&!keyD&&keyL){
- dir = Direction.LU;
- }
- else if (!keyU&&!keyR&&!keyD&&!keyL){
- dir = Direction.STOP;
- }
- }
- public void move(){
- switch (dir){
- case U :
- y-=YSpeed;
- break;
- case RU :
- x+=XSpeed;
- y-=YSpeed;
- break;
- case R :
- x+=XSpeed;
- break;
- case RD :
- x+=XSpeed;
- y+=YSpeed;
- break;
- case D :
- y+=YSpeed;
- break;
- case LD:
- x-=XSpeed;
- y+=YSpeed;
- break;
- case L :
- x-=XSpeed;
- break;
- case LU :
- x-=XSpeed;
- y-=YSpeed;
- break;
- }
-
- }
-
- public Missile fire(){
- int x = this.x +Tank.WIDTH/2-Missile.WIDTH/2;
- int y =this.x +Tank.HEIGHT/2 -Missile.HEIGHT/2;
- Missile myMissile = new Missile(x,y,dir);
- return myMissile;
- }
- }