FlyingObject,作为飞行物的父类,这里的飞行物指的就是敌机,小蜜蜂,子弹,英雄机
package com.tarena.shoot;
import java.awt.image.BufferedImage;
//飞行物类
public abstract class FlyingObject {
protected BufferedImage image; //图片
protected int width; //宽
protected int height; //高
protected int x; //坐标
protected int y;
// 飞行物走一步
public abstract void step();
//检查是否出界,,返回true表示已越界
public abstract boolean outOfBounds();
public boolean shootBy(Bullet b) {
return false;
};
}
敌机类,图片取自ShootGame的入口类(在下面),打掉一个敌机得五分,敌机只能向下走
图片在主类 ShootGame中静态引入了
package com.tarena.shoot;
import java.util.Random;
//敌机
public class Airplane extends FlyingObject implements Enemy{
private int speed = 2; //走的步数
public Airplane() { // 全部都在构造方法中初始化数据
image = ShootGame.airplane;
width = image.getWidth(); //获取图片的宽
height = image.getHeight(); //获取图片的高
Random rand = new Random(); //随机数对象
x = rand.nextInt(ShootGame.WIDTH-this.width+1);
y = -this.height;
}
public int getScore() {
return 5; //打掉一个敌机得5分
}
// 重写
public void step() {
y+=speed;
}
// 重写是否越界函数---越界删除该对象
public boolean outOfBounds() {
if(y>ShootGame.HEIGHT) {
return true;
}else {
return false;
}
}
// 敌人被子弹射击----也就是检测图片与图片之间检测碰撞
public boolean shootBy(Bullet bullet) {
int x1 = this.x;
int x2 = this.x + this.width;
int y1 = this.y;
int y2 = this.y + this.height;
// x在 x1 和 x2 之间,y在y1和y2之间,既是碰撞了
if(bullet.xx1 && bullet.yy1) {
return true;
}else {
return false;
}
}
}
Bee,小蜜蜂类,也是敌人的一种,和上面敌机不同的是,小蜜蜂还会横着走,碰到边界反弹,打掉一个小蜜蜂还会获得奖励,也就是继承的接口 Award
package com.tarena.shoot;
import java.util.Random;
public class Bee extends FlyingObject implements Award{
private int xSpeed = 1; //X坐标速度
private int ySpeed = 2; //Y坐标速度
private int awardType; //奖励的类型 0/1
public Bee() {
image = ShootGame.bee;
width = image.getWidth();
height = image.getHeight();
Random rand = new Random();
x = rand.nextInt(ShootGame.WIDTH - this.width+1);
y = -this.height;
awardType = rand.nextInt(2); //0到1之间
int xSymbol = rand.nextInt(2);
if(xSymbol == 0) {
xSpeed = -xSpeed;
}
}
public int getType() {
return awardType; //返回奖励类型 0/1 在ShootGame 中根据0、1判断奖励的类型分别调用方法
}
// 重写
public void step() {
y+=ySpeed;
x+=xSpeed;
if(x>ShootGame.WIDTH-this.width || x<=0) {
xSpeed = -xSpeed;
}
}
// 重写是否越界函数
public boolean outOfBounds() {
if(y>ShootGame.HEIGHT) {
return true;
}else {
return false;
}
}
// 敌人被子弹射击
public boolean shootBy(Bullet bullet) {
int x1 = this.x;
int x2 = this.x + this.width;
int y1 = this.y;
int y2 = this.y + this.height;