本项目为一个基于Java编程语言开发的“飞机大战”游戏,经过全面测试确保代码中没有明显错误。适合初学者学习和参考。
```java
public abstract class FlyingObject {
public static final int LIFE = 0; // 表示对象存活状态
public static final int DEAD = 1; // 表示对象死亡状态(先爆破)
public static final int REMOVE = 2; // 表示对象被移除(爆破后删除)
protected int state = LIFE; // 当前的状态,默认为生存
protected int width; // 宽度
protected int height; // 高度
protected int x; // X坐标位置
protected int y; // Y坐标位置
public FlyingObject() {}
/**
* 构造方法,适用于小敌机、大敌机和蜜蜂等对象。
*/
public FlyingObject(int width, int height) {
this.width = width;
this.height = height;
Random rand = new Random();
x = rand.nextInt(World.WIDTH - width); // X坐标在0到(窗口宽度-物体宽度)之间的随机值
y = -height; // Y坐标的初始位置为负高度,表示从屏幕外开始移动
}
/**
* 构造方法,适用于英雄机、子弹和天空等对象。
*/
public FlyingObject(int width, int height, int x, int y) {
this.width = width;
this.height = height;
this.x = x;
this.y = y;
}
/**
* 加载图片资源
*/
public static BufferedImage loadImage(String fileName){
try{
return ImageIO.read(FlyingObject.class.getResource(fileName));
}catch(Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}
/**
* 抽象方法,定义飞行物的移动逻辑。
*/
public abstract void step();
/**
* 获取对象对应的图片资源
*/
public abstract BufferedImage getImage();
/**
* 检查当前飞行物体是否处于存活状态
*/
public boolean isLife() {
return state == LIFE;
}
/**
* 判断飞行物是否已经死亡。
*/
public boolean isDead(){
return state==DEAD;
}
/**
* 检查对象是否已经被移除(删除)。
*/
public boolean isRemove(){
return state == REMOVE;
}
/**
* 画出飞行物
*/
public void paintObject(Graphics g){
g.drawImage(getImage(), x, y, null);
}
/** 检测物体是否超出边界。*/
public abstract boolean outOfBounds();
/**
* 判断两个对象(敌人与子弹或英雄机)之间是否有碰撞
*/
public boolean hit(FlyingObject other){
int enemyX1 = this.x - other.width;
int enemyX2 = this.x + this.width;
int enemyY1 = this.y - other.height;
int enemyY2 = this.y + this.height;
return (other.x >= enemyX1 && other.x <= enemyX2) &&
(other.y >= enemyY1 && other.y <= enemyY2);
}
/**
* 将对象的状态设置为已死亡。
*/
public void goDead(){
state = DEAD;
}
}
```