Java小项目 飞机大战源码(无Bug,可运行)
package shoot;
import java.util.Random;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.awt.Graphics;
/** 飞行物 */
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{
BufferedImage img = ImageIO.read(FlyingObject.class.getResource(fileName));
return img;
}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;
}
/** 画对象 g:画笔 */
public void paintObject(Graphics g){
g.drawImage(getImage(), x, y, null);
}
/** 检测飞行物是否越界 */
public abstract boolean outOfBounds();
/** 敌人与子弹/英雄机的碰撞 this:敌人 other:子弹或英雄机 */
public boolean hit(FlyingObject other){
int x1 = this.x-other.width; //x1:敌人的x
int x2 = this.x+this.width; //x2:敌人的x
int y1 = this.y-other.height; //y1:敌人的y
int y2 = this.y+this.height; //y2:敌人的y
int x = other.x; //x:子弹的x
int y = other.y; //y:子弹的y
return x>=x1 && x<=x2 && y>=y1 && y<=y2;
}
public void goDead(){
state = DEAD; //修改当前状态为死了的
}
}
---------------------------------------------------------------------------------------------------------------------------------------------
package shoot;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
/** 天空 */
public class Sky extends FlyingObject{
private static BufferedImage image;
static{
image = loadImage("background.png");
}
private int speed; //移动速度
private int y1; //y坐标(第2张图的)
/** 构造方法 */
public Sky(){
super(World.WIDTH,World.HEIGHT,0,0);
speed = 1;
y1 = -height;
}
public void step(){
y+=speed;
y1+=speed;
if(y>=this.height){ //若y>=窗口的高度
y = -this.height; //则y=负的窗口高度
}
if(y1>=this.height){ //若y1>=窗口的高度
y1 = -this.height; //则y1=负的窗口高度
}
}
/** 重写getImage() */
public BufferedImage getImage(){
return image;
}
/** 重写 paintObject() */
public void paintObject(Graphics g){
g.drawImage(getImage(), x, y1, null);
g.drawImage(getImage(), x, y, null);
}
public boolean outOfBounds(){
return false;
}
}