📄 enemytanksprite.java
字号:
package tankgame611;
import java.applet.Applet;
import java.awt.Image;
import java.util.Random;
public class EnemyTankSprite extends SpriteDrawing implements Runnable{
int AppletWidth, AppletHeight;
int enemyTankWidth, enemyTankHeight;
int direction;
int enemyTankX, enemyTankY;
Image enemyTankImg[];
Applet GameApplet;
Thread newThread;
Random rand;
static int speed = 2;
public EnemyTankSprite(Image[] enemyTankImg,
int enemyTankX,
int enemyTankY,
Applet GameApplet){
super(enemyTankImg, enemyTankX, enemyTankY, GameApplet); //调用父类的创建方法
this.enemyTankX = enemyTankX;
this.enemyTankY = enemyTankY;
this.enemyTankImg = enemyTankImg;
this.GameApplet=GameApplet;
AppletWidth=GameApplet.getWidth();
AppletHeight=GameApplet.getHeight();
setVisible(true);
setActive(true);
rand=new Random();
}
public void updateState(int SpriteDirection){
//移动坦克
enemyTankWidth=enemyTankImg[0].getWidth(GameApplet);
enemyTankHeight=enemyTankImg[0].getHeight(GameApplet);
switch (SpriteDirection) {
case 0: //左
enemyTankX = this.getX() - speed;
if (enemyTankX < 0) { //设定坦克的左边界
enemyTankX = 0;
this.direction = rand.nextInt(10) % 4;
}
break;
case 1: //右
enemyTankX = this.getX() + speed;
if (enemyTankX >AppletWidth - enemyTankWidth) { //设定坦克的右边界
enemyTankX = AppletWidth - enemyTankWidth;
this.direction = rand.nextInt(10) % 4;
}
break;
case 2: //上
enemyTankY = this.getY() - speed;
if (enemyTankY < 0) { //设定坦克的上边界
enemyTankY = 0;
this.direction = rand.nextInt(10) % 4;
}
break;
case 3: //下
enemyTankY = this.getY() + speed;
if (enemyTankY >= AppletHeight - enemyTankHeight) { //设定坦克的下边界
enemyTankY = AppletHeight - enemyTankHeight;
this.direction = rand.nextInt(10) % 4;
}
break;
}
this.setPos(enemyTankX,enemyTankY);
}
//启用本类线程的接口方法
public void startRunning(){
newThread=new Thread(this);
newThread.start();
}
public void stopRunning(){
newThread=null;
}
public int getTankDirection(){
return direction;
}
public void setTankDirection(int direction){
this.direction = direction;
}
public void run(){
while(newThread!=null){
GameApplet.repaint();//调用主类的paint方法重绘画面
try{Thread.sleep(10);}
catch(InterruptedException E){}
if(this.active==true){
updateState(direction);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -