操作方法
分析游戏中的所有图片。他们都有共同的特性。 所以建立一个父类,
import java.awt.image.BufferedImage; /** * ShootGame游戏中所有对象的父类 */public abstract class FlyingObject { public BufferedImage image; public int width; public int height; public int x; public int y; //所有的飞行物都会走路,但是走路的方式各不相同 public abstract void step(); //检查飞行物是否越界 public abstract boolean checkOut(); //飞行物被子弹撞 /** * 撞上了 返回 true 没撞上 false * 一个飞行物和一个子弹碰撞 */ public boolean shootBy(Bullet b) { //获取 子弹的 x,y坐标 int bx=b.x; int by=b.y; //获取 x1,x2 int x1=this.x-b.width; int x2=this.x+this.width; //获取 y1,y2 int y1=this.y-b.height; int y2=this.y+this.height; return bx>x1 && bx<x2 && by>y1 && by<y2; } }
public class Airplane extends FlyingObject implements Enemy{ int speed; public Airplane() { image=ShootGame.airplane; width=image.getWidth(); height=image.getHeight(); x=(int) (Math.random()*(ShootGame.WIDTH-width)); y=-height; speed=3; } //敌机的走路 是从上往下 则是Y轴增大 public void step() { y+=speed; } @Override public boolean checkOut() { return y>ShootGame.HEIGHT; } public int getScore() { return 5; }}
package shootgame;/** * 奖励类型接口 * 实现该接口的 死亡 都有奖励 */public interface Award { //定义2个常量用来定义奖励类型 int DOUBLE_FIRE=0;//奖励双倍火力值 int LIFE=1;//奖励生命 int JG=2; //获取奖励类型 int getType();}
package shootgame;/** * 蜜蜂既是飞行物也是奖励类型 */public class Bee extends FlyingObject implements Award{ int xSpeed; int ySpeed; public Bee() { image=ShootGame.bee; width=image.getWidth(); height=image.getHeight(); x=(int) (Math.random()*(ShootGame.WIDTH-width)); y=-height; xSpeed=1; ySpeed=1; } public void step() { if(x<0 || x>ShootGame.WIDTH-this.width) { xSpeed=-xSpeed; } y+=ySpeed; x+=xSpeed; } @Override public boolean checkOut() { return y>ShootGame.HEIGHT; } public int getType() { //生成一个0-1之间的随机整数 return (int) (Math.random()*3); } }
package shootgame; public class Boss extends FlyingObject{ int life; int speed; public Boss(){ life=130; image=ShootGame.boss1; height=image.getHeight(); width=image.getWidth(); x=5; y=5; speed=2; } public Boss(int x,int y){ life=10; image=ShootGame.boss1; height=image.getHeight(); width=image.getWidth(); this.x=x; this.y=y; speed=2; } //boss移动 public void step() { if(x<0||x>ShootGame.WIDTH-this.width){ speed=-speed; } x+=speed; } //发射子弹 public BossBullet [] shoot(){ BossBullet[] bbs = new BossBullet[1]; // 第一发子弹 是 英雄机的x+英雄机1/4宽度 bbs[0] = new BossBullet(this.x + this.width / 4, this.y +this.height); return bbs; } //永不越界 public boolean checkOut() { return false; } }