⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 playtanksprite.java

📁 在实际的项目中运用类的继承、覆盖及重载。
💻 JAVA
字号:
package tankgame611;
import java.applet.Applet;
import java.awt.Image;
import java.awt.event.*;

public class PlayTankSprite extends SpriteDrawing implements Runnable{
  int AppletWidth,AppletHeight;
  int myTankWidth,myTankHeight;
  int direction;
  int myTankX,myTankY;
  Image myTankImg[];
  Applet GameApplet;
  Thread newThread;
  static int speed=5;

  public PlayTankSprite(Image[] myTankImg,int myTankX,int myTankY,
                        Applet GameApplet) {
    super(myTankImg,myTankX,myTankY,GameApplet);
    this.myTankX=myTankX;
    this.myTankY=myTankY;
    this.myTankImg=myTankImg;
    myTankWidth=myTankImg[0].getWidth(GameApplet);
    myTankHeight=myTankImg[0].getHeight(GameApplet);
    this.GameApplet=GameApplet;
    AppletWidth=GameApplet.getWidth();
    AppletHeight=GameApplet.getHeight();
    setVisible(true);
    setActive(false);
    //为Applet加上键盘监听侦听
    GameApplet.addKeyListener(new KeyAction());
  }
  public void updatePos(int SpriteDirection){

    switch(SpriteDirection){
      case 0:
        myTankX=this.getX()-speed;
        if(myTankX<0)
           myTankX=0;
      break;
      case 1:
        myTankX=this.getX()+speed;
        if(myTankX>AppletWidth-myTankWidth)
          myTankX=AppletWidth-myTankWidth;
          break;
      case 2:
        myTankY=this.getY()-speed;
        if(myTankY<0)
           myTankY=0;
      break;
      case 3:
        myTankY=this.getY()+speed;
        if(myTankY>AppletHeight-myTankHeight)
          myTankY=AppletHeight-myTankHeight;
          break;
    }
    this.setPos(myTankX,myTankY);
  }
  //启用本类线程的接口方法
  public void startRunning(){
    newThread=new Thread(this);
    newThread.start();
  }
  public void stopRunning(){
    newThread=null;
  }
  public int getTankDirection(){
    return direction;
  }
  public void run(){
    while(newThread!=null){
      GameApplet.repaint();//调用主类的paint方法重绘画面
      try{Thread.sleep(10);}
      catch(InterruptedException E){}
      if(this.active==true){
        updatePos(direction);
      }
    }
  }
  //使用内部类实现按键事件处理
  class KeyAction extends KeyAdapter{
   public void keyPressed(KeyEvent e){
     if(e.getKeyCode()==e.VK_SPACE){
     }
     if(e.getKeyCode()==e.VK_LEFT){
       direction=0;
       setActive(true);
     }
     if(e.getKeyCode()==e.VK_RIGHT){
       direction=1;
       setActive(true);
     }
     if(e.getKeyCode()==e.VK_UP){
       direction=2;
       setActive(true);
     }
     if(e.getKeyCode()==e.VK_DOWN){
       direction=3;
       setActive(true);
     }
   }
   public void keyRealeased(KeyEvent e){
     setActive(false);
   }
  }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -