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(); // ����ִ��
  }
}

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

相关文章
|
2天前
|
Java API 数据安全/隐私保护
【亮剑】如何使用Java整合Spring框架来发送邮件?
【4月更文挑战第30天】本文介绍了如何在Java项目中结合Spring框架实现邮件发送功能。首先,需在`pom.xml`添加Spring和JavaMail依赖。然后,在`applicationContext.xml`配置邮件发送器,包括SMTP服务器信息。接着,创建一个使用依赖注入的`EmailService`类,通过`JavaMailSender`发送邮件。最后,调用`EmailService`的`sendSimpleEmail`方法即可发送邮件。最佳实践包括:使用配置管理敏感信息,利用`MimeMessage`构造复杂邮件,异常处理和日志记录,以及在大量发送时考虑使用邮件队列。
|
2天前
|
人工智能 监控 Java
java互联网+智慧工地云平台SaaS源码
智慧工地以施工现场风险预知和联动预控为目标,将智能AI、传感技术、人像识别、监控、虚拟现实、物联网、5G、大数据、互联网等新一代科技信息技术植入到建筑、机械、人员穿戴设施、场地进出关口等各类设备中,实现工程管理与工程施工现场的整合
9 0
|
4天前
|
监控 Java BI
java基于云计算的SaaS医院his信息系统源码 HIS云平台源码
基于云计算技术的B/S架构的HIS系统源码,SaaS模式Java版云HIS系统,融合B/S版电子病历系统,支持电子病历四级,HIS与电子病历系统均拥有自主知识产权。
24 5
|
5天前
|
人工智能 监控 数据可视化
Java智慧工地云平台源码带APP SaaS模式 支持私有化部署和云部署
智慧工地是指应用智能技术和互联网手段对施工现场进行管理和监控的一种工地管理模式。它利用传感器、监控摄像头、人工智能、大数据等技术,实现对施工现场的实时监测、数据分析和智能决策,以提高工地的安全性、效率和质量(技术架构:微服务+Java+Spring Cloud +UniApp +MySql)。
20 4
|
7天前
|
Java 关系型数据库 MySQL
基于swing的java物业管理系统
基于swing的java物业管理系统
18 5
|
7天前
|
人工智能 监控 安全
JAVA基于SaaS模式的智慧工地云平台源码(云智慧工地解决方案)
智慧工地支持多端展示(PC端、手机端、平板端)SaaS微服务架构,项目监管端,工地管理端源码
14 0
|
7天前
|
搜索推荐 前端开发 Java
java医院绩效考核管理系统项目源码
系统需要和his系统进行对接,按照设定周期,从his系统获取医院科室和医生、护士、其他人员工作量,对没有录入信息化系统的工作量,绩效考核系统设有手工录入功能(可以批量导入),对获取的数据系统按照设定的公式进行汇算,且设置审核机制,可以退回修正,系统功能强大,完全模拟医院实际绩效核算过程,且每步核算都可以进行调整和参数设置,能适应医院多种绩效核算方式。
11 0
|
7天前
|
存储 Java 索引
深入探讨Java集合框架
深入探讨Java集合框架
深入探讨Java集合框架
|
7天前
|
设计模式 算法 Java
[设计模式Java实现附plantuml源码~行为型]定义算法的框架——模板方法模式
[设计模式Java实现附plantuml源码~行为型]定义算法的框架——模板方法模式
|
Java
Java并发编程笔记之FutureTask源码分析
FutureTask可用于异步获取执行结果或取消执行任务的场景。通过传入Runnable或者Callable的任务给FutureTask,直接调用其run方法或者放入线程池执行,之后可以在外部通过FutureTask的get方法异步获取执行结果,因此,FutureTask非常适合用于耗时的计算,主线程可以在完成自己的任务后,再去获取结果。
4259 0