Java小游戏之Swing框架实现飞机大战(附源码 超详细必看)

简介: Java小游戏之Swing框架实现飞机大战(附源码 超详细必看)

需要源码和图片集请点赞关注收藏后评论区留言~~~

1.项目主要工作

本次项目的题目——基于Java的飞机大战游戏的设计与实现,主要目的是实现飞机大战这个游戏。期望结果游戏无BUG现在人们将在电脑系统或程序中,隐藏着的一些未被发现的缺陷或问题统称为BUG——漏洞,简单易上手,老少皆宜,让玩家“玩不释手”。

从游戏的玩法来说,主要就是我方飞机(Hero airplane)和敌方飞机(Enemy airplane)的对决,首先是游戏的开始界面与结束界面,然后就是我方飞机(Hero airplane)的移动方式(鼠标移动或者键盘移动,我打算选择鼠标移动,因为鼠标移动可以转移到手机上,现在大多数手机都没有键盘,基本靠手指滑动操作),接下来就是我方飞机(Hero airplane)子弹的生成,然后是敌方飞机(Enemy airplane)的出现坐标的选择,然后飞机与子弹防碰撞,飞机与飞机的防碰撞,最后是我方飞机(Hero airplane)与敌方飞机(Enemy airplane)的对战结果。

该游戏要满足以下功能性需求:

(1)游戏状态控制功能

   游戏的状态控制包括运行、暂停、恢复及结束游戏,首先是游戏的开始页面,在游戏正在进行时,如果你有其他的事情又不想结束游戏你可以将鼠标移出游戏界面或者鼠标在游戏界面单击即可暂停游戏,当你的其他事情解决后你还可以选择恢复游戏,继续玩下去,当游戏结束时会显示游戏结束界面。

(2)游戏难度的调整

    玩家随着玩游戏的时间的增加,敌方飞机的数量会增加,出现的频率会有所提高,移动速度也会提高。

(3)游戏界面绘画功能

    在右上角显示游戏时间(游戏难度于时间成正比,即游戏时间越长难度越高),玩家游戏得分,与我方飞机生命值,游戏主屏用来显示玩家对我方飞机(Hero airplane)的控制与敌方飞机(Enemy airplane)的出现及移动的显示。

(4)玩家游戏控制功能

    玩家可以通过控制移动鼠标或者键盘来控制友机的移动。

项目分解结构(WBS)如下

 

效果图如下

部分源码

package main;
import java.util.Random;
//Airplane----�л����Ƿ����
public class Airplane extends FlyingObject implements Enemy {
  private int speed = 2;// �л��߲��IJ���
  public Airplane() {
    image = ShootGame.airplane;
    width = image.getWidth();
    height = image.getHeight();
    Random rand = new Random();
    x = rand.nextInt(ShootGame.WIDTH - this.width);
    y = -this.height; // y:���ĵл��ĸ�
  }
  // ��д getScore();
  public int getScore() {
    return 5;
  }
  public void step() {
    y += speed;
  }
  public boolean outOfBounds() {
    return this.y > ShootGame.HEIGHT; // �л���y������ڴ��ڵĸ�
  }
}
-------------
package main;
import java.util.Random;
//Be---С�۷�  ���Ƿ����Ҳ�ܻ�ȡ����
public class Bee extends FlyingObject implements Award{
  private int xSpeed = 1;     //x�����߲�����
  private int ySpeed = 2;     //y�����߲�����
  private int awardType;      //��������
  public Bee(){
    image = ShootGame.bee;
    width = image.getWidth();
    height = image.getHeight();
    Random rand = new Random();
    x = rand.nextInt(ShootGame.WIDTH - this.width);
      y = -this.height; 
    awardType = rand.nextInt(2);//������ɽ�������
  }
  public int getType(){
    return awardType;
  }
    public void step(){     
      if(x >= ShootGame.WIDTH - this.width){
        xSpeed = -1;
      }
      if(x <= 0){
        xSpeed = 1;
      }
      x += xSpeed;
      y += ySpeed;    
  }
    public boolean outOfBounds(){
      return this.y > ShootGame.HEIGHT;  
  }
}
-----------
package main;
//�ӵ�--ֻ�Ƿ����� 
public class Bullet extends FlyingObject{
  private int speed = 3;  //�ӵ��߲�������ֻ��y�����ڱ�
  public Bullet(int x,int y){//�ӵ�����������Ӣ�ۻ��ı仯���仯   
    image = ShootGame.bullet;
    width = image.getWidth();
    height = image.getHeight();
    this.x = x;
    this.y = y;
  }
    public void step(){
    y -= speed;
  }
    public boolean outOfBounds(){
    return this.y < -this.height;
  }
}
------------
package main;
import java.awt.image.BufferedImage;
public abstract class FlyingObject {
  protected BufferedImage image;//ͼƬ����--java�����е�
  protected int width;     //��
  protected int height;    //��
  protected int x;         //x����
  protected int y;         //y����
  //�������߲�
  public abstract void step();
  //Խ�緽��
  public abstract boolean outOfBounds();
  //���˱��ӵ�ײ 
  public boolean shootBy(Bullet bullet){
    //this:����       other���ӵ�
    int x1 = this.x;
    int x2 = this.x + this.width;
    int y1 = this.y;
    int y2 = this.y + this.height;
    int x = bullet.x;
    int y = bullet.y;
    return x > x1 && x < x2
        &&
        y > y1 && y < y2;
  }
}
-------------
package main;
import java.awt.image.BufferedImage;
//Ӣ�ۻ��Ƿ�����
public class Hero extends FlyingObject{
  private int life;                 //��
  private int doubleFire;           //����ֵ
  private BufferedImage[] images;   //ͼƬ����
  private int index;                //Э��ͼƬ�л�
  public Hero(){
    image = ShootGame.hero0;
    width = image.getWidth();
    height = image.getHeight();
    x = 150;
    y = 400;                
    life = 3;              //3����
    doubleFire = 0;        //��������
    images = new BufferedImage[]{ShootGame.hero0,ShootGame.hero1};
    index = 0;
  }
  public void step(){
    //ÿ100������һ��
    image = images[index++/10%images.length];   
    /*
    index++;
    int a = index / 10;
    int b = a % 2;
    image = images[b];
    */
  }
  public Bullet[] shoot(){
    int xStep = this.width/4;
    if(doubleFire > 0){           //˫��
      Bullet[] bullets = new Bullet[2];
      bullets[0] = new Bullet(this.x + 1 * xStep,this.y - 20);
      bullets[1] = new Bullet(this.x + 3 * xStep,this.y - 20);
      doubleFire -= 2;      //����˫��������ÿ�μ�2��ʵ�ʾ���2�������ij���ʱ��
      return bullets;
    }else{                        //����
      Bullet[] bullets = new Bullet[1];
      bullets[0] = new Bullet(this.x + 2 * xStep,this.y - 20);
      return bullets;
    }
  }
  public void moveTo(int x,int y){
    this.x = x - this.width/2;
    this.y = y - this.height/2;
  }
  public boolean outOfBounds(){
    return false;              //Ӣ�ۻ�����Խ��
  }
    //����
    public void addLife(){
      life++;
    }
    //��ȡ��
    public int getLife(){
      return life;
    }
    public void addDoubleFire(){
      doubleFire += 40;
    }
    //����ֵ����
    public void setDoubleFire(int doubleFire){
      this.doubleFire = doubleFire;
    }
    //Ӣ�ۻ�ײ����
    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;
      int hx = this.x + this.width/2;
      int hy = this.y + this.height/2;
      return hx > x1 && hx < x2
          &&
           hy > y1 && hy < y2;
    }
    //����
    public void subtractLife(){
      life--;
    }    
}
-----------------package main;
import java.applet.Applet;
import java.applet.AudioClip;
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.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
//�����������
public class ShootGame extends JPanel {
  /**
   * 
   */
  private static final long serialVersionUID = 9158805858745581422L;
  public static final int WIDTH = 400; // ���ڵĿ�
  public static final int HEIGHT = 654; // ���ڵĸ�
  // ��̬��Դ
  public static BufferedImage background; // ����ͼ
  public static BufferedImage start; // ��ʼͼ
  public static BufferedImage pause; // ��ͣͼ
  public static BufferedImage gameover; // ��Ϸ����ͼ
  public static BufferedImage airplane; // �л�ͼ
  public static BufferedImage bee; // �۷�ͼ
  public static BufferedImage bullet; // �ӵ�ͼ
  public static BufferedImage hero0; // Ӣ�ۻ�0ͼ
  public static BufferedImage hero1; // Ӣ�ۻ�1ͼ
  public static AudioClip music;
  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 state = 0; // ��ǰ״̬
  private Hero hero = new Hero(); // Ӣ�ۻ�
  private Bullet[] bullets = {}; // �ӵ�����
  private FlyingObject[] flyings = {}; // ��������
  private Timer timer;
  private int intervel = 10; // ���ʱ�䣺��λ--����
  // ��̬��
  static {
    try {
      background = ImageIO.read(ShootGame.class.getResource("background.png"));
      start = ImageIO.read(ShootGame.class.getResource("start.png"));
      pause = ImageIO.read(ShootGame.class.getResource("pause.png"));
      gameover = ImageIO.read(ShootGame.class.getResource("gameover.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"));
      URL musicPath = ShootGame.class.getResource("game_music.wav");
      music = Applet.newAudioClip(musicPath);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public static FlyingObject nextOne() {
    Random rand = new Random();
    int type = rand.nextInt(20); // ����0��19�������
    if (type == 0) { // �����Ϊ0������bee;���򷵻صл�
      return new Bee();
    } else {
      return new Airplane();
    }
  }
  int flyEnteredIndex = 0;
  // ���˵dz�
  public void enterAction() {// 10������һ��
    flyEnteredIndex++; // ÿ10������1
    if (flyEnteredIndex % 40 == 0) {
      FlyingObject obj = nextOne();
      flyings = Arrays.copyOf(flyings, flyings.length + 1);
      flyings[flyings.length - 1] = obj;// �����˸�ֵ��flyings��������һ��Ԫ��
    }
  }
  public void stepAction() { // 10������һ��
    hero.step(); // Ӣ�ۻ���һ��
    int num = time1 / 15;
    for (int i = 0; i < flyings.length; i++) {
      for(int j = 0; j <= num; j++) {
        flyings[i].step(); // ������һ��
      }
    }
    for (int i = 0; i < bullets.length; i++) {
      for(int j = 0; j <= num/2; j++) {
        bullets[i].step(); // �ӵ���һ��
      }
    }
  }
  int shootIndex = 0;
  public void shootAction() { // 10������һ��
    shootIndex++; // ÿ10������1
    if (shootIndex % 30 == 0) { // 300���뷢��һ���ӵ�
      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 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;// ��Խ�磬����װ��flyingLives[]������
        index++;
      }
    }
    flyings = Arrays.copyOf(flyingLives, index);
    index = 0;
    Bullet[] bulletsLives = new Bullet[bullets.length];
    for (int i = 0; i < bullets.length; i++) {
      Bullet bs = bullets[i];
      if (!bs.outOfBounds()) {
        bulletsLives[index] = bs;// ��Խ�磬����װ��flyingLives[]������
        index++;
      }
    }
    bullets = Arrays.copyOf(bulletsLives, index);
  }
  int score = 0; // �÷�
  static double time = 0.00;//ʱ��
  static int time1 = 0;
  // �����ӵ������е���ײ
  public void bangAction() {
    for (int i = 0; i < bullets.length; i++) {
      bang(bullets[i]);
    }
  }
  // һ���ӵ������е���ײ
  public void bang(Bullet b) {
    int index = -1;// ��ײ���˵�����
    for (int i = 0; i < flyings.length; i++) {// �������еĵ���
      if (flyings[i].shootBy(b)) {// �ж��Ƿ�ײ��
        index = i; // ��¼��ײ���˵�����
        break;
      }
    }
    if (index != -1) {// ײ����
      FlyingObject one = flyings[index];
      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;
        }
      }
      // ��ײ������flyings�����е����һ��Ԫ�ؽ���
      FlyingObject t = flyings[index];
      flyings[index] = flyings[flyings.length - 1];
      flyings[flyings.length - 1] = t;
      // ���ݣ�ɾ�����һ��Ԫ��---����ײ�Ķ���
      flyings = Arrays.copyOf(flyings, flyings.length - 1);
    }
  }
  public void checkGameOverAction() {
    if (isGameOver()) { // ������Ϸ
      state = GAME_OVER;
      time1 = 0;
      time = 0;
    }
  }
  public boolean isGameOver() {
    for (int i = 0; i < flyings.length; i++) { // ײ���ˣ�
      if (hero.hit(flyings[i])) {
        hero.subtractLife(); // ������1
        hero.setDoubleFire(0); // ����ֵ����
        // ��ײ֮�󣬽�������
        FlyingObject t = flyings[i];
        flyings[i] = flyings[flyings.length - 1];
        flyings[flyings.length - 1] = t;
        flyings = Arrays.copyOf(flyings, flyings.length - 1);
      }
    }
    return hero.getLife() <= 0; // Ӣ�ۻ�����<=0,��Ϸ����
  }
  // ����ִ�д���
  public void action() {
    MouseAdapter l = new MouseAdapter() {
      public void mouseMoved(MouseEvent e) {
        if (state == RUNNING) { // ����״̬��ִ��
          int x = e.getX(); // ���Y����
          int y = e.getY(); // ���X����
          hero.moveTo(x, y); // Ӣ�ۻ���������ƶ����ƶ�
        }
      }
      // ���ĵ���¼�
      public void mouseClicked(MouseEvent e) {
        switch (state) {
        case PAUSE:
          state = RUNNING;
          music.stop();
          music.loop();
          break;
        case RUNNING:
          state = PAUSE;
          music.stop();
          break;
        case START:
          state = RUNNING;
          music.stop();
          music.loop();
          break;
        case GAME_OVER:
          hero = new Hero();// �����ֳ�
          flyings = new FlyingObject[0];
          bullets = new Bullet[0];
          score = 0;
          state = START;
          music.stop();
          break;
        }
      }
      public void mouseEntered(MouseEvent e) {
        if (state == PAUSE) {
          state = RUNNING;
        }
      }
      public void mouseExited(MouseEvent e) {
        if (state == RUNNING) {
          state = PAUSE;
        }
      }
    };
    this.addMouseListener(l); // �����������¼�
    this.addMouseMotionListener(l);// ��������ƶ��¼�
    timer = new Timer(); // ������ʱ������
    timer.schedule(new TimerTask() {
      public void run() { // ��ʱ�ɵ��Ǹ���--10������һ��
        if (state == RUNNING) { // ����״̬��ִ��
          enterAction();
          stepAction();// ��������һ��
          shootAction();// �ӵ��볡
          outOfBoundsAction();// ɾ��Խ�������
          bangAction(); // �ӵ������ײ
          time = time +0.01;
          time1 = (int)time;
          checkGameOverAction();
        }
        repaint(); // �ػ�������paint()
      }
    }, intervel, intervel);
  }
  // ��дpaint()���� g����ʾ����
  public void paint(Graphics g) {
    g.drawImage(background, 0, 0, null); // ������ͼ
    paintHero(g);
    paintFlyingObjects(g);
    paintBullets(g);
    paintScore(g); // ���֣�����
    paintState(g);
  }
  // ��״̬
  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 void paintHero(Graphics g) {
    g.drawImage(hero.image, hero.x, hero.y, null); // ��Ӣ�ۻ�����
  }
  public void paintFlyingObjects(Graphics g) {
    for (int i = 0; i < flyings.length; i++) {
      FlyingObject f = flyings[i];
      g.drawImage(f.image, f.x, f.y, null);
    }
  }
  public void paintBullets(Graphics g) {
    for (int i = 0; i < bullets.length; i++) {
      Bullet b = bullets[i];
      g.drawImage(b.image, b.x, b.y, null);
    }
  }
  public void paintScore(Graphics g) { // ���֣�����
    g.setColor(new Color(0xFF0000));
    g.setFont(new Font(Font.SANS_SERIF, Font.BOLD, 20));
    g.drawString("SCORE: " + score, 20, 25);
    g.drawString("LIFE: " + hero.getLife(), 20, 45);
    g.drawString("TIME:" +time1,20,65);
  }
  public static void main(String[] args) {
    JFrame frame = new JFrame("�ɻ���ս"); // ���ڶ���
    ShootGame game = new ShootGame(); // ���
    frame.add(game); // �������ӵ�������
      BufferedImage image;
    try {
      image = ImageIO.read(ShootGame.class.getResource("icon.jpg"));
      frame.setIconImage(image);
    } catch (FileNotFoundException e) {
    } catch (IOException e) {
    }  
    frame.setSize(WIDTH, HEIGHT); // ���ô��ڵĿ�͸�
    frame.setAlwaysOnTop(true); // ����һֱ��������
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // ����Ĭ�ϹرյIJ��������ڹر�ʱ�˳�����
    frame.setLocationRelativeTo(null); // ���ô��ڳ�ʼλ�ã�����)
    frame.setVisible(true); // ���ô���ɼ�
    game.action(); // ����ִ��
  }
}

创作不易 觉得有帮助请点赞关注收藏~~~

相关文章
|
1月前
|
安全 前端开发 Java
《深入理解Spring》:现代Java开发的核心框架
Spring自2003年诞生以来,已成为Java企业级开发的基石,凭借IoC、AOP、声明式编程等核心特性,极大简化了开发复杂度。本系列将深入解析Spring框架核心原理及Spring Boot、Cloud、Security等生态组件,助力开发者构建高效、可扩展的应用体系。(238字)
|
1月前
|
存储 安全 Java
《数据之美》:Java集合框架全景解析
Java集合框架是数据管理的核心工具,涵盖List、Set、Map等体系,提供丰富接口与实现类,支持高效的数据操作与算法处理。
|
1月前
|
消息中间件 缓存 Java
Spring框架优化:提高Java应用的性能与适应性
以上方法均旨在综合考虑Java Spring 应该程序设计原则, 数据库交互, 编码实践和系统架构布局等多角度因素, 旨在达到高效稳定运转目标同时也易于未来扩展.
121 8
|
1月前
|
存储 算法 安全
Java集合框架:理解类型多样性与限制
总之,在 Java 题材中正确地应对多样化与约束条件要求开发人员深入理解面向对象原则、范式编程思想以及JVM工作机理等核心知识点。通过精心设计与周密规划能够有效地利用 Java 高级特征打造出既健壮又灵活易维护系统软件产品。
76 7
|
2月前
|
存储 小程序 Java
热门小程序源码合集:微信抖音小程序源码支持PHP/Java/uni-app完整项目实践指南
小程序已成为企业获客与开发者创业的重要载体。本文详解PHP、Java、uni-app三大技术栈在电商、工具、服务类小程序中的源码应用,提供从开发到部署的全流程指南,并分享选型避坑与商业化落地策略,助力开发者高效构建稳定可扩展项目。
|
2月前
|
消息中间件 人工智能 Java
抖音微信爆款小游戏大全:免费休闲/竞技/益智/PHP+Java全筏开源开发
本文基于2025年最新行业数据,深入解析抖音/微信爆款小游戏的开发逻辑,重点讲解PHP+Java双引擎架构实战,涵盖技术选型、架构设计、性能优化与开源生态,提供完整开源工具链,助力开发者从理论到落地打造高留存、高并发的小游戏产品。
|
2月前
|
人工智能 Java 开发者
阿里出手!Java 开发者狂喜!开源 AI Agent 框架 JManus 来了,初次见面就心动~
JManus是阿里开源的Java版OpenManus,基于Spring AI Alibaba框架,助力Java开发者便捷应用AI技术。支持多Agent框架、网页配置、MCP协议及PLAN-ACT模式,可集成多模型,适配阿里云百炼平台与本地ollama。提供Docker与源码部署方式,具备无限上下文处理能力,适用于复杂AI场景。当前仍在完善模型配置等功能,欢迎参与开源共建。
1414 58
阿里出手!Java 开发者狂喜!开源 AI Agent 框架 JManus 来了,初次见面就心动~
|
2月前
|
SQL Java 数据库连接
区分iBatis与MyBatis:两个Java数据库框架的比较
总结起来:虽然从技术角度看,iBATIS已经停止更新但仍然可用;然而考虑到长期项目健康度及未来可能需求变化情况下MYBATISS无疑会是一个更佳选择因其具备良好生命周期管理机制同时也因为社区力量背书确保问题修复新特征添加速度快捷有效.
193 12
|
3月前
|
存储 缓存 安全
Java集合框架(三):Map体系与ConcurrentHashMap
本文深入解析Java中Map接口体系及其实现类,包括HashMap、ConcurrentHashMap等的工作原理与线程安全机制。内容涵盖哈希冲突解决、扩容策略、并发优化,以及不同Map实现的适用场景,助你掌握高并发编程核心技巧。
|
3月前
|
存储 缓存 安全
Java集合框架(二):Set接口与哈希表原理
本文深入解析Java中Set集合的工作原理及其实现机制,涵盖HashSet、LinkedHashSet和TreeSet三大实现类。从Set接口的特性出发,对比List理解去重机制,并详解哈希表原理、hashCode与equals方法的作用。进一步剖析HashSet的底层HashMap实现、LinkedHashSet的双向链表维护顺序特性,以及TreeSet基于红黑树的排序功能。文章还包含性能对比、自定义对象去重、集合运算实战和线程安全方案,帮助读者全面掌握Set的应用与选择策略。
258 23
下一篇
oss云网关配置