【项目】某内Java巩固基础项目⑨(飞机大战)三

  • 将小敌机、大敌机、小蜜蜂数组合为FlyingObject数组,并测试
  • 在派生类中重写FlyingObject的step()方法
  • 画窗口

编程

  • 窗口
/** 整个窗口 */
public class World extends JPanel {
    
    
	Sky sky = new Sky();    //天空
	Hero hero = new Hero(); //英雄机
	FlyingObject[] enemies = {
    
    }; //敌人(小敌机、大敌机、小蜜蜂)数组
	Bullet[] bullets = {
    
    };  //子弹数组
	
	void action() {
    
     //测试代码
		enemies = new FlyingObject[5];
		enemies[0] = new Airplane();
		enemies[1] = new Airplane();
		enemies[2] = new BigAirplane();
		enemies[3] = new BigAirplane();
		enemies[4] = new Bee();
		for(int i=0;i<enemies.length;i++) {
    
     //遍历所有敌人
			FlyingObject f = enemies[i]; //获取每一个敌人
			System.out.println(f.x+","+f.y);
			f.step();
			//f被子弹射击 
			//f和英雄机撞
		}
	}
	
	public static void main(String[] args) {
    
    
		JFrame frame = new JFrame();
		World world = new World();
		frame.add(world);
		
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		frame.setSize(400,700);
		frame.setLocationRelativeTo(null); 
		frame.setVisible(true); 
		
		world.action();
	}
}

  • 飞行物父类
/** 飞行物 */
public class FlyingObject {
    
    
	int width;  //宽
	int height; //高
	int x;      //x坐标
	int y;      //y坐标
	/** 专门给小敌机、大敌机、小蜜蜂提供的 */
	FlyingObject(int width,int height){
    
    
		this.width = width;
		this.height = height;
		Random rand = new Random();
		x = rand.nextInt(400-this.width); //x:0到(400-敌人宽)之间的随机数
		y = -this.height; //y:负的敌人的高
	}
	/** 专门给英雄机、天空、子弹提供的 */
	FlyingObject(int width,int height,int x,int y){
    
    
		this.width = width;
		this.height = height;
		this.x = x;
		this.y = y;
	}
	
	/** 飞行物移动 */
	void step() {
    
    
		System.out.println("飞行物移动啦!");
	}
	
}
  • 飞行物重写父类step方法,如下图所示,添加step方法
/** 小敌机:是飞行物 */
public class Airplane extends FlyingObject {
    
    
	int speed; //移动速度
	/** 构造方法 */
	Airplane(){
    
    
		super(48,50);
		speed = 2;
	}
	
	/** 重写step()移动 */
	void step() {
    
    
		System.out.println("小敌机的y坐标向下移动了:"+speed);
	}
}

重写与重载的区别、super关键字、向上造型

图片

  • ariplane0.png
    请添加图片描述

  • ariplane1.png
    请添加图片描述

  • background.png
    请添加图片描述

  • background1.png
    请添加图片描述

  • bee0.png
    请添加图片描述

  • bee1.png
    请添加图片描述

  • bigairplane0.png
    请添加图片描述

  • bigairplane1.png
    请添加图片描述

  • bom1.png
    请添加图片描述

  • bom2.png
    请添加图片描述

  • bom3.png
    请添加图片描述

  • bom4.png
    请添加图片描述

  • bullet.png
    请添加图片描述

  • gameover.png
    -请添加图片描述

  • hero0.png
    请添加图片描述

  • hero1.png
    请添加图片描述

  • pause.png
    请添加图片描述

  • start.png

请添加图片描述

Guess you like

Origin blog.csdn.net/weixin_45511500/article/details/120311462