飞机大战

文章目录

  • 飞机大战
    • 游戏需求
    • 代码实现
      • 子弹类
      • 英雄机类
      • 小敌机类
      • 大敌机类
      • 小蜜蜂类
      • 飞行物类
      • 接口类
      • 爆炸类
      • 游戏窗口类

游戏需求

  1. 所参与角色:英雄机、子弹、小敌机、大敌机、小蜜蜂、天空
  2. 角色间关系:
    • 英雄机发射子弹(单倍火力、双倍火力)
    • 子弹打敌人(小敌机、大敌机、小蜜蜂)
    • 若击中,子弹直接消失、敌机先爆破再消失
    • 若击中小敌机,玩家得1分、大敌机得3分、小蜜蜂则奖励1条命或40火力值
    • 敌人(小敌机、大敌机、小蜜蜂)撞到英雄机,敌人先爆破再消失。且英雄机减1条命,且火力值清空,命数为0则游戏结束
    • 英雄机、小敌机、大敌机、小蜜蜂都在天空中飞

代码实现

子弹类

package com.liner.shoot;/*** 子弹类*/
public class Bullet extends FlyingObject {private int speed = 3;  //移动的速度private boolean bomb;public Bullet(int x,int y){this.x = x;this.y = y;this.image = ShootGame.bullet;}public void setBomb(boolean bomb) {this.bomb = bomb;}public boolean isBomb() {return bomb;}@Overridepublic void step(){   //移动方法y-=speed;}@Overridepublic boolean outOfBounds() {return y<-height;}}

英雄机类

package com.liner.shoot;import java.awt.image.BufferedImage;/*** 英雄机* * @author Administrator* */
public class Hero extends FlyingObject {protected BufferedImage[] images = {};protected int index = 0;//private boolean doubleFire;private int doubleFire;private int life;public Hero() {life = 3;doubleFire = 0;this.image = ShootGame.hero0;this.ember = ShootGame.heroEmber;images = new BufferedImage[]{ShootGame.hero0, ShootGame.hero1};width = image.getWidth();height = image.getHeight();x = 150;y = 400;}public int isDoubleFire() {return doubleFire;}public void addDoubleFire(){doubleFire = 40;}public void setDoubleFire(int doubleFire) {this.doubleFire = doubleFire;}public void addLife() { // 增命life++;}public void subtractLife() { // 减命life--;}public int getLife() {return life;}/*** 当前物体移动了一下,相对距离, x,y鼠标位置*/public void moveTo(int x, int y) {this.x = x - width / 2;this.y = y - height / 2;}@Overridepublic boolean outOfBounds() {return x < 0 || x > ShootGame.WIDTH - width || y < 0|| y > ShootGame.HEIGHT - height;}public Bullet[] shoot() { // 发射子弹int xStep = width / 4; // 子弹步分为飞机宽度4半int yStep = 20;if (doubleFire>0) {Bullet[] bullets = new Bullet[2];bullets[0] = new Bullet(x + xStep, y - yStep);bullets[1] = new Bullet(x + 3 * xStep, y - yStep);doubleFire -= 2;return bullets;} else { // 单倍Bullet[] bullets = new Bullet[1];bullets[0] = new Bullet(x + 2 * xStep, y - yStep); // y-yStep(子弹距飞机的位置)return bullets;}}@Overridepublic void step() {if(images.length>0){image = images[index++/10%images.length];}}public boolean hit(FlyingObject other) { // 碰撞算法int x1 = other.x - this.width / 2;int x2 = other.x + other.width + this.width / 2;int y1 = other.y - this.height / 2;int y2 = other.y + other.height + this.height / 2;return this.x + this.width / 2 > x1 && this.x + this.width / 2 < x2&& this.y + this.height / 2 > y1&& this.y + this.width / 2 < y2;}}

小敌机类

package com.liner.shoot;/*** 敌飞机: 是飞行物,也是敌人*/
public class Airplane extends FlyingObject implements Enemy {int speed = 2;  //移动步骤public Airplane(){this.image = ShootGame.airplane;this.ember = ShootGame.airplaneEmber;width = image.getWidth();height = image.getHeight();y = -height;          x = (int)(Math.random()*(ShootGame.WIDTH - width));}@Overridepublic int getScore() {  //获取分数return 5;}@Overridepublic  boolean outOfBounds() {   //越界处理return y>ShootGame.HEIGHT;}@Overridepublic void step() {   //移动y += speed;}}

大敌机类

package com.liner.shoot;import java.util.Random;public class BigPlane extends FlyingObject implements Enemy, Award{private int speed = 1; private int life;private int awardType;public BigPlane() {life = 4;this.image = ShootGame.bigPlane;this.ember = ShootGame.bigPlaneEmber;width = image.getWidth();height = image.getHeight();y = -height;       Random rand = new Random();x = rand.nextInt(ShootGame.WIDTH - width);awardType = rand.nextInt(2);}public int getType() {return awardType;}@Overridepublic int getScore() {return 50;}@Overridepublic boolean outOfBounds() {return false;}//    @Override
//  public BufferedImage getImage() {//      Graphics g = image.getGraphics();
//      g.setColor(Color.white);
//      g.fillRect(0, 0, 40, 30);
//      g.setColor(Color.black);
//      g.drawString("L:"+life, 10, 20);
//      return image;
//  }@Overridepublic void step() {   //移动y += speed;}public boolean shootBy(Bullet bullet) {if(super.shootBy(bullet)){life--;}return life==0;}
}

小蜜蜂类

package com.liner.shoot;import java.util.Random;public class Bee extends FlyingObject implements Award{private int xSpeed = 1;private int ySpeed = 2;private int awardType;public Bee(){this.image = ShootGame.bee;this.ember = ShootGame.beeEmber;width = image.getWidth();height = image.getHeight();y = -height;Random rand = new Random();x = rand.nextInt(ShootGame.WIDTH - width);awardType = rand.nextInt(2);   //初始化时给奖励}public int getType(){return awardType;}@Overridepublic boolean outOfBounds() {return y>ShootGame.HEIGHT;}@Overridepublic void step() {      //可斜飞x += xSpeed;y += ySpeed;if(x > ShootGame.WIDTH-width){xSpeed = -1;}if(x < 0){xSpeed = 1;}}
}

飞行物类

package com.liner.shoot;import java.awt.image.BufferedImage;/*** 飞行物(敌机,蜜蜂,子弹,英雄机)*/
public abstract class FlyingObject {protected int x;protected int y;protected int width;   protected int height;protected BufferedImage image;protected BufferedImage[] ember;public int getX() {return x;}public void setX(int x) {this.x = x;}public int getY() {return y;}public void setY(int y) {this.y = y;}public int getWidth() {return width;}public void setWidth(int width) {this.width = width;}public int getHeight() {return height;}public void setHeight(int height) {this.height = height;}public BufferedImage getImage() {return image;}public void setImage(BufferedImage image) {this.image = image;}/*** 检查是否出界* @param width  边界宽* @param height 边界高* @return true 出界与否*/public abstract boolean outOfBounds();/*** 飞行物移动一步*/public abstract void step();/*** 检查当前飞行物体是否被子弹(x,y)击(shoot)中,* true表示击中,飞行物可以被击中* @param Bullet 子弹对象* @return true表示被击中了*/public boolean shootBy(Bullet bullet){if(bullet.isBomb()){return false;}int x = bullet.x;  //子弹横坐标int y = bullet.y;  //子弹纵坐标boolean shoot = this.x<x && x<this.x+width && this.y<y && y<this.y+height;if(shoot){bullet.setBomb(true);}return shoot;}}

接口类

  • 奖励接口
package com.liner.shoot;
/*** 奖励*/
public interface Award {int DOUBLE_FIRE = 0;  //双倍火力int LIFE = 1;   //1条命/** 获得奖励类型(上面的0或1) */int getType();
}
  • 得分接口
package com.liner.shoot;/*** 敌人,可以有分数*/
public interface Enemy {//敌人的分数int getScore();
}

爆炸类

package com.liner.shoot;import java.awt.image.BufferedImage;/*** 灰烬 飞机被打掉以后的残影* @author Robin*/
public class Ember {private BufferedImage[] images={};private int index;private int i;private BufferedImage image;private int intevel = 10;private int x,y;public Ember(FlyingObject object) {images = object.ember;image = object.image;x = object.x;y = object.y;index = 0;i = 0;}public boolean burnDown(){i++;if(i%intevel==0){if(index == images.length){return true;}image = images[index++];}return false;}public int getX() {return x;}public int getY() {return y;}public BufferedImage getImage() {return image;}
}

游戏窗口类

package com.liner.shoot;import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;public class ShootGame extends JPanel {public static final int WIDTH = 400; // 面板宽public static final int HEIGHT = 654; // 面板高/** 游戏的当前状态: START RUNNING PAUSE GAME_OVER */private int state;public static final int START = 0;public static final int RUNNING = 1;public static final int PAUSE = 2;public static final int GAME_OVER = 3;private int score = 0; // 得分private Timer timer; // 定时器private int intervel = 1000/100; // 时间间隔(毫秒)public static BufferedImage background;public static BufferedImage start;public static BufferedImage pause;public static BufferedImage gameover;public static BufferedImage bullet;public static BufferedImage airplane;public static BufferedImage[] airplaneEmber=new BufferedImage[4];public static BufferedImage bee;public static BufferedImage[] beeEmber=new BufferedImage[4];;public static BufferedImage hero0;public static BufferedImage hero1;public static BufferedImage[] heroEmber=new BufferedImage[4];;public static BufferedImage bigPlane;public static BufferedImage[] bigPlaneEmber=new BufferedImage[4];;private FlyingObject[] flyings = {}; // 敌机数组private Bullet[] bullets = {}; // 子弹数组private Hero hero = new Hero(); // 英雄机private Ember[] embers = {}; // 灰烬static {// 静态代码块try {background = ImageIO.read(ShootGame.class.getResource("background.png"));bigPlane = ImageIO.read(ShootGame.class.getResource("bigplane.png"));airplane = ImageIO.read(ShootGame.class.getResource("airplane.png"));bee = ImageIO.read(ShootGame.class.getResource("bee.png"));bullet = ImageIO.read(ShootGame.class.getResource("bullet.png"));hero0 = ImageIO.read(ShootGame.class.getResource("hero0.png"));hero1 = ImageIO.read(ShootGame.class.getResource("hero1.png"));pause = ImageIO.read(ShootGame.class.getResource("pause.png"));gameover = ImageIO.read(ShootGame.class.getResource("gameover.png"));start = ImageIO.read(ShootGame.class.getResource("start.png"));for(int i=0; i<4; i++){beeEmber[i] = ImageIO.read(ShootGame.class.getResource("bee_ember"+i+".png"));airplaneEmber[i] = ImageIO.read(ShootGame.class.getResource("airplane_ember"+i+".png"));bigPlaneEmber[i] = ImageIO.read(ShootGame.class.getResource("bigplane_ember"+i+".png"));heroEmber[i] = ImageIO.read(ShootGame.class.getResource("hero_ember"+i+".png"));}} catch (Exception e) {e.printStackTrace();}}@Overridepublic void paint(Graphics g) {g.drawImage(background, 0, 0, null); // 画背景图paintEmber(g);paintHero(g); // 画英雄机paintBullets(g); // 画子弹paintFlyingObjects(g); // 画飞行物paintScore(g); // 画分数paintState(g); // 画游戏状态}/** 画英雄机 */public void paintHero(Graphics g) {g.drawImage(hero.getImage(), hero.getX(), hero.getY(), null);}public void paintEmber(Graphics g) {for (int i = 0; i < embers.length; i++) {Ember e = embers[i];g.drawImage(e.getImage(), e.getX(), e.getY(), null);}}/** 画子弹 */public void paintBullets(Graphics g) {for (int i = 0; i < bullets.length; i++) {Bullet b = bullets[i];if(! b.isBomb())g.drawImage(b.getImage(), b.getX() - b.getWidth() / 2, b.getY(),null);}}/** 画飞行物 */public void paintFlyingObjects(Graphics g) {for (int i = 0; i < flyings.length; i++) {FlyingObject f = flyings[i];g.drawImage(f.getImage(), f.getX(), f.getY(), null);}}/** 画分数 */public void paintScore(Graphics g) {int x = 10;int y = 25;Font font = new Font(Font.SANS_SERIF,Font.BOLD, 14);g.setColor(new Color(0x3A3B3B));g.setFont(font); // 设置字体g.drawString("SCORE:" + score, x, y); // 画分数y+=20;g.drawString("LIFE:" + hero.getLife(), x, y);}/** 画游戏状态 */public void paintState(Graphics g) {switch (state) {case START:g.drawImage(start, 0, 0, null);break;case PAUSE:g.drawImage(pause, 0, 0, null);break;case GAME_OVER:g.drawImage(gameover, 0, 0, null);break;}}public static void main(String[] args) {JFrame frame = new JFrame("Shoot Game");ShootGame game = new ShootGame(); // 面板对象frame.add(game); // 将面板添加到JFrame中frame.setSize(WIDTH, HEIGHT); // 大小frame.setAlwaysOnTop(true); // 其总在最上frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // 默认关闭操作frame.setIconImage(new ImageIcon("images/icon.jpg").getImage()); // 设置窗体的图标frame.setLocationRelativeTo(null); // 设置窗体初始位置frame.setVisible(true); // 尽快调用paintgame.action(); // 启动执行}public void action() { // 启动执行代码// 鼠标监听事件MouseAdapter l = new MouseAdapter() {@Overridepublic void mouseMoved(MouseEvent e) { // 鼠标移动if (state == RUNNING) { // 运行时移动英雄机int x = e.getX();int y = e.getY();hero.moveTo(x, y);}}@Overridepublic void mouseEntered(MouseEvent e) { // 鼠标进入if (state == PAUSE) { // 暂停时运行state = RUNNING;}}@Overridepublic void mouseExited(MouseEvent e) { // 鼠标退出if (state != GAME_OVER) {state = PAUSE; // 游戏未结束,则设置其为暂停}}@Overridepublic void mouseClicked(MouseEvent e) { // 鼠标点击switch (state) {case START:state = RUNNING;break;case GAME_OVER: // 游戏结束,清理现场flyings = new FlyingObject[0];bullets = new Bullet[0];hero = new Hero();score = 0;state = START;break;}}};this.addMouseListener(l); // 处理鼠标点击操作this.addMouseMotionListener(l); // 处理鼠标滑动操作timer = new Timer(); // 主流程控制timer.schedule(new TimerTask() {@Overridepublic void run() {if (state == RUNNING) {enterAction(); // 飞行物入场stepAction(); // 走一步shootAction(); // 射击bangAction(); // 子弹打飞行物outOfBoundsAction(); // 删除越界飞行物及子弹checkGameOverAction(); // 检查游戏结束emberAction();}repaint(); // 重绘,调用paint()方法}}, intervel, intervel);}private void emberAction() {Ember[] live = new Ember[embers.length];int index = 0;for (int i = 0; i < embers.length; i++) {Ember ember = embers[i];if(! ember.burnDown()){live[index++]=ember;}}embers = Arrays.copyOf(live, index);}int flyEnteredIndex = 0; // 飞行物入场计数/** 飞行物入场 */public void enterAction() {flyEnteredIndex++;if (flyEnteredIndex % 40 == 0) { // 300毫秒--10*30FlyingObject obj = nextOne(); // 随机生成一个飞行物flyings = Arrays.copyOf(flyings, flyings.length + 1);flyings[flyings.length - 1] = obj;}}public void stepAction() {/** 飞行物走一步 */for (int i = 0; i < flyings.length; i++) { // 飞行物走一步FlyingObject f = flyings[i];f.step();}/** 子弹走一步 */for (int i = 0; i < bullets.length; i++) {Bullet b = bullets[i];b.step();}hero.step();}int shootIndex = 0; // 射击计数/** 射击 */public void shootAction() {shootIndex++;if (shootIndex % 30 == 0) { // 100毫秒发一颗Bullet[] bs = hero.shoot(); // 英雄打出子弹bullets = Arrays.copyOf(bullets, bullets.length + bs.length); // 扩容System.arraycopy(bs, 0, bullets, bullets.length - bs.length,bs.length); // 追加数组}}/** 子弹与飞行物碰撞检测 */public void bangAction() {for (int i = 0; i < bullets.length; i++) { // 遍历所有子弹Bullet b = bullets[i];bang(b);}}/** 删除越界飞行物及子弹 */public void outOfBoundsAction() {int index = 0;FlyingObject[] flyingLives = new FlyingObject[flyings.length]; // 活着的飞行物for (int i = 0; i < flyings.length; i++) {FlyingObject f = flyings[i];if (!f.outOfBounds()) {flyingLives[index++] = f; // 不越界的留着}}flyings = Arrays.copyOf(flyingLives, index); // 将不越界的飞行物都留着index = 0; // 重置为0Bullet[] bulletLives = new Bullet[bullets.length];for (int i = 0; i < bullets.length; i++) {Bullet b = bullets[i];if (!b.outOfBounds()) {bulletLives[index++] = b;}}bullets = Arrays.copyOf(bulletLives, index); // 将不越界的子弹留着}/** 检查游戏结束 */public void checkGameOverAction() {if (isGameOver()) {state = GAME_OVER; // 改变状态}}/** 检查游戏是否结束 */public boolean isGameOver() {int index = -1;for (int i = 0; i < flyings.length; i++) {FlyingObject obj = flyings[i];if (hero.hit(obj)) { // 检查英雄机与飞行物是否碰撞hero.subtractLife();hero.setDoubleFire(0);index = i;Ember ember = new Ember(hero);embers = Arrays.copyOf(embers, embers.length+1);embers[embers.length-1]=ember;}}if(index!=-1){FlyingObject t = flyings[index];flyings[index] = flyings[flyings.length-1];flyings[flyings.length-1] = t;flyings = Arrays.copyOf(flyings, flyings.length-1);Ember ember = new Ember(t);embers = Arrays.copyOf(embers, embers.length+1);embers[embers.length-1]=ember;}return  hero.getLife() <= 0;}/** 子弹和飞行物之间的碰撞检查 */public void bang(Bullet bullet) {int index = -1; // 击中的飞行物索引for (int i = 0; i < flyings.length; i++) {FlyingObject obj = flyings[i];if (obj.shootBy(bullet)) { // 判断是否击中index = i; // 记录被击中的飞行物的索引break;}}if (index != -1) { // 有击中的飞行物FlyingObject one = flyings[index]; // 记录被击中的飞行物FlyingObject temp = flyings[index]; // 被击中的飞行物与最后一个飞行物交换flyings[index] = flyings[flyings.length - 1];flyings[flyings.length - 1] = temp;flyings = Arrays.copyOf(flyings, flyings.length - 1); // 删除最后一个飞行物(即被击中的)// 检查one的类型 如果是敌人, 就算分if (one instanceof Enemy) { // 检查类型,是敌人,则加分Enemy e = (Enemy) one; // 强制类型转换score += e.getScore(); // 加分} if (one instanceof Award) { // 若为奖励,设置奖励Award a = (Award) one;int type = a.getType(); // 获取奖励类型switch (type) {case Award.DOUBLE_FIRE:hero.addDoubleFire(); // 设置双倍火力break;case Award.LIFE:hero.addLife(); // 设置加命break;}}//飞行物变成灰烬Ember ember = new Ember(one);embers = Arrays.copyOf(embers, embers.length+1);embers[embers.length-1]=ember;}}/*** 随机生成飞行物* * @return 飞行物对象*/public static FlyingObject nextOne() {Random random = new Random();int type = random.nextInt(20); // [0,4)if (type==0) {return new Bee();}else if(type<=2){return new BigPlane();}else{return new Airplane();}}
}

飞机大战——Java小游戏相关推荐

  1. c语言小程序飞机大战,飞机大战微信小游戏:经典像素飞机大战小程序,点开即玩...

    50000+游戏爱好者已加入我们! 每天推荐好玩游戏! 关注我们,沐沐带你发现好游戏! <经典像素飞机大战>游戏小程序好玩吗? <经典像素飞机大战>小游戏怎么玩? 怎么进入&l ...

  2. python轰炸敌机小游戏_python实现飞机大战微信小游戏

    0.前言 我学一种语言,可以说学任何东西都喜欢自己动手实践,总感觉自己动手一遍,就可以理解的更透彻,学python也一样,自己动手写代码,但更喜欢做点小东西出来,一边玩一边学.下面我就展示一下我最近做 ...

  3. HTML+CSS+JS制作【飞机大战】小游戏(键盘版和鼠标版)

    文章目录 一.效果演示 设计思路 二.鼠标版飞机大战代码展示 1.HTML结构代码 2.CSS样式代码 3.JavaScript代码 js.js文件 plane.js文件 三.键盘版飞机大战代码展示 ...

  4. 飞机大战python小游戏

    python飞机大战 #导入模块 import pygame import random from pygame.locals import * from os import path #获取图片库和 ...

  5. python飞机大战游戏素材_python实现飞机大战微信小游戏

    0.前言 我学一种语言,可以说学任何东西都喜欢自己动手实践,总感觉自己动手一遍,就可以理解的更透彻,学python也一样,自己动手写代码,但更喜欢做点小东西出来,一边玩一边学.下面我就展示一下我最近做 ...

  6. 基于Python/Tkinter的飞机大战单机小游戏

    这是很早之前课余时间写的基于Python/Tkinter单机小游戏,用来练手,今天将代码贴出来,方便大家一起学习,通过Py/Tk对于学习GUI作为一个入口,其实是个不错入口,在这里推荐一下Tcl/Tk ...

  7. 关于Python初级阶段模仿飞机大战的小游戏制作源码

    # main.py import pygame import sys import traceback import king import face import bb import supply ...

  8. c语言实现的运用easyx完成的飞机大战简单小游戏(内含道具掉落,攻击转换)

    素材链接: https://share.weiyun.com/6NlDMrJU 代码如下: //游戏名:[星球大战].//游戏玩法:玩家操控火箭攻击boss,期间通过走位躲避boss的炮弹和小怪,(小 ...

  9. 贪吃蛇大战 java小游戏百度云源码

    第一次实践做了贪吃蛇,感觉还不错分享一下吧 https://pan.baidu.com/s/1TylyNo3t9M_6R7To6I29hg 提取码:8488

最新文章

  1. boost::mp11模块使用一些节点生成并行蒙特卡罗模拟的示例
  2. 建立基于以太坊的私有网络和智能合约
  3. vim 代码提示功能,让vim可以媲美IDE
  4. docker php composer 使用_如何使用Docker部署PHP开发环境
  5. 系统架构师学习笔记-系统开发基础知识(一)
  6. python数据库实现注册函数_10.注册和登录功能实现(3)—— 注册数据写入数据库...
  7. java在dos命令_JAVA中如何执行DOS命令
  8. 李宏毅自然语言处理——成分句法分析
  9. matlab+yalmip+mosek/cplex安装配置
  10. FB OpenGraph og:image无法提取图像(可能是https?)
  11. 把标清视频转高清Video Enhance AI for mac
  12. 绘画技巧:怎样才能画好拟人化兽人?
  13. 洛谷 P1957 口算练习题
  14. Python 内建函数大全
  15. 模具冲压与模具设计知识点
  16. matlab基本操作与矩阵输入简单表示
  17. AIX日志型文件系统的nbpi
  18. preempt-RT patches
  19. Python之pip:pip包管理工具的简介、安装、使用方法之详细攻略
  20. 使用Fiddler实现网络限速,模拟低速网络

热门文章

  1. Kay-2023.4.18
  2. js 直接打开选择文件窗口_基于HTML5 构建的 Web端现代化PDF在线预览插件——PDF.js...
  3. 程序员-建立你的商业意识 闫辉 著
  4. 知乎问答:如果你去摆地摊,卖什么商品最合适?
  5. 服务器性能计数器驱动,windows性能计数器(常见)
  6. python中numpy是什么意思_python中numpy什么意思
  7. EffectCreator 6.1.0中文版 抖音短视频编辑工具
  8. 【软件定义汽车】SOA协议DDS和Some/IP对比
  9. 故障处理 软件 需求_软件的质量模型(二)
  10. C++ wifi共享工具