1. ホーム
  2. ジャワ

航空機戦争ゲームのJava実装 (ソースコード+コメント)

2022-02-26 07:25:19
<パス <ブロッククオート

全体的な考え方は、ブログ主の他のブログ記事と同じです 蛇のミニゲームのJava実装 (ソースコード+コメント) 2048ミニゲームのJava実装 (ソースコード+コメント) は同じで、どちらも Frame を使用してフォームを作成し、Panel を使用してコンポーネントを追加し、事前にレイアウトを計画し、マウスとキーボードのリスナーを呼び出し、画像要素を参照します。
ここでは、敵のコレクションと弾丸のコレクションを常に更新して、ダイナミックな効果を実現することを目的としています。

記事の目次

I. プロジェクトファイル

II.Main.java

<ブロッククオート

メイン関数、実装クラス

package ui;

// Main function implementation
public class Main {
    public static void main(String[] args) {
        //create the form
        GameFrame frame = new GameFrame();
        //create panel
        GamePanel panel = new GamePanel(frame);
        // call the start game method to start the game
        panel.action();
        //add the panel to the form
        frame.add(panel);
        //set the form visible
        frame.setVisible(true);
    }
}



III.ゲームフレーム.java

<ブロッククオート

フォームを描画するフォームクラス

package ui;

import javax.swing.*;

// Create the form
public class GameFrame extends JFrame {
    //constructor method, initialize the form properties
    public GameFrame(){
        // set the title, from JFrame
        setTitle("Airplane war");
        // set the size
        setSize(512,768);
        //set centering
        setLocationRelativeTo(null);
        //set the form visible
        //setVisible(true);
        //do not allow the player to modify the interface size
        setResizable(false);
        //set the default close option
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}




IV.GamePanel.java

<ブロッククオート

要素をアウトライン化するためのCanvasクラス

package ui;

import javax.swing.*;
import java.awt.*;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event;
BufferedImage; import java.awt.image;
import java.util.ArrayList;
import java.util.List;
import java.util;

// custom game panel (create canvas)
public class GamePanel extends JPanel {

    //define the background image
    BufferedImage bg;

    //construct the game machine
    Hero hero = new Hero();
    //Enemy machine collection
    List
 eps = new ArrayList
();
    //The ammunition collection
    List
 fs = new ArrayList
();
    //define score
    int score;
    //set the game switch
    Boolean gameover=false;
    //set firepower
    int power = 1;

    // action function, depicting the movement of flying objects in the scene
    public void action(){
        //create threads (basic template)
        new Thread(){
            public void run(){
                // wireless loop creation
                while (true){
                    //judge if the game has not failed, then perform the following actions
                    if(!gameover){
                        //Enemy aircraft enter
                        epEnter();
                        //call the enemy aircraft move method
                        epMove();
                        //Fire bullets
                        shoot();
                        //Bullet move
                        fireMove();
                        //judge whether the bullet hit the enemy plane
                        shootEp();
                        //Detect whether the enemy plane hit the game machine or not
                        hit();
                    }
                    //Sleep the thread for a while after each execution
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // Redraw the interface
                    repaint();
                }
            }
        }.start();//Get the thread running
    }

    //every 20 executions, release an enemy machine and create a counter to count
    int index = 0;
    protected void epEnter(){
        index++;
        //create the enemy machine
        if(index
            //reset counter
            index = 0;
        }
    }

    //Make the enemy machine move
    protected void epMove(){
        //Iterate through the set of enemy machines and move them in order
        for (int i = 0; i < eps.size(); i++) {
            //Get the set of enemy planes
            Ep e = eps.get(i);
            // call the move method in the enemy machine class
            e.move();
        }
    }

    //every 20 executions, create a bullet, create counter count
    int findex = 0;
    protected void shoot(){
        findex++;
        if(findex>=20){
            //judge the number of rows of bullets based on firepower
            //one row of bullets
            if(power==1){
                //create bullets
                Fire fire1 = new Fire(hero.x+45,hero.y,1);
                //put the bullets into the bullet collection
                fs.add(fire1);
            }
            //two rows of bullets
            else if(power==2){
                //create bullets
                Fire fire1 = new Fire(hero.x+15,hero.y,0);
                //put the bullets into the bullet collection
                fs.add(fire1);
                //create bullets
                Fire fire2 = new Fire(hero.x+75,hero.y,2);
                //put the bullets into the bullet collection
                fs.add(fire2);
            }
            //three rows of bullets
            else{
                //create bullets
                Fire fire1 = new Fire(hero.x+15,hero.y,0);
                //put the bullets into the bullet collection
                fs.add(fire1);
                //create bullets
                Fire fire2 = new Fire(hero.x+75,hero.y,2);
                //put the bullets into the bullet collection
                fs.add(fire2);
                //create bullets
                Fire fire3 = new Fire(hero.x+45,hero.y-10,1);
                //put the bullets into the bullet collection
                fs.add(fire3);
            }
            //put the counter to 0
            findex = 0;
        }
    }

    //Make the bullet move
    protected void fireMove(){
        //Iterate through the set of bullets
        for (int i = 0; i < fs.size(); i++) {
            //Get the position of each bullet
            Fire f = fs.get(i);
            //move each bullet in turn
            f.move();
        }
    }

    // determine whether the bullet hit the enemy aircraft
    protected void shootEp(){
        //Iterate through all bullets
        for (int i = 0; i < fs.size(); i++) {
            //Get each bullet
            Fire f = fs.get(i);
            // determine if a bullet hit an enemy aircraft
            bang(f);

        }
    }

    //judge whether a bullet has hit an enemy aircraft
    protected void bang(Fire f){
        for (int i = 0; i < eps.size(); i++) {
            // take out each enemy aircraft
            Ep e = eps.get(i);
            // determine if this bullet hit the enemy plane
            if(e.shootBy(f)&&e.type!=15){
                //judge whether the game machine machine hit the prop machine
                if(e.type==12){
                    //fire power increases
                    power++;
                    //If the firepower value is greater than three, increase the amount of blood
                    if(power>3){
                        //restore the amount of blood
                        if(hero.hp<3){
                            hero.hp++;
                        }
                        // make the console blood not exceed 3
                        power = 3;
                    }
                }
                //If the enemy machine is hit by a bullet
                //Enemy machine disappears
                eps.remove(e);
                //delete the bullets
                fs.remove(f);
                //Increase score
                score += 10;
            }
        }
    }

    //Detect if the enemy plane hit the host
    protected void hit() {
        for (int i = 0; i < eps.size(); i++) {
            //Get each enemy aircraft
            Ep e = eps.get(i);
            // call the method of the enemy plane to determine
            if(e.shootBy(hero)){
                //delete the enemy plane
                eps.remove(e);
                //host blood is reduced
                hero.hp--;
                //firepower restores initial value
                power = 1;
                //score increases
                score += 10;
                //game over when host blood is reduced to 0
                if(hero.hp==0){
                    gameover = true;
                }
            }

        }
    }

    //Constructor
    public GamePanel(GameFrame frame){
        //set the background
        bg = App.getImg("/img/bg2.jpg");

        //create mouse listener and mouse adapter


V.FlyObject.java

<ブロッククオート

フライオブジェクトのクラス、フライオブジェクトのプロパティの設定

package ui;

import java.awt.image;


public class FlyObject {
    //all use photo material
    BufferedImage img;
    //position of the horizontal coordinates
    int x;
    //the vertical coordinates of the location
    int y;
    //the width of the image element
    int w;
    //height of the image element
    int h;
}



VI.Hero.java

<ブロッククオート

プレイ中に操作する機体のプロパティを設定するホストクラス

package ui;

import java.awt.image;

//game machine
public class Hero extends FlyObject{
    // Set the amount of blood in the game machine
    int hp;

    //constructor
    public Hero(){
        //Get the game machine elements
        img = App.getImg("/img/hero.png");
        //confirm the initial position
        x = 200;
        y = 500;
        //Get the width and height of the console image element
        w = img.getWidth();
        h = img.getHeight();
        //set initial blood to 3
        hp = 3;
    }

    // according to the incoming parameters to move the corresponding position
    public void moveToMouse(int mx,int my){
        x = mx;
        y = my;
    }
}



VII.Ep.java

<ブロッククオート

エネミークラス

package ui;

import javax.swing.*;
import java.awt.image;
import java.util.ArrayList;
import java.util.List;
import java.util;

// Enemy class
public class Ep extends FlyObject{
    // set the speed of the enemy aircraft
    int sp;
    //Set the type of enemy aircraft, different types of enemy aircraft have different properties
    int type;

    // constructor
    public Ep(){
        //introduce a random number of random calls enemy aircraft
        Random random = new Random();
        //Call [1,15] range of enemy aircraft
        int index = random.nextInt(15) + 1;
        //Save the type of enemy aircraft
        type = index;
        //If the serial number is less than 10, then add the leading 0, the substance conforms to the image naming law
        String path = "/img/ep" + (index<10?"0":"")+index+".png";
        // call the method class function according to the path to get the image io stream
        img = App.getImg(path);
        // determine the location of the enemy aircraft
        //get the enemy aircraft photo element width parameter
        w = img.getWidth();
        //border length minus photo width to prevent photos from crossing the border
        x = random.nextInt(512-w);
        y = 0;
        //set the speed
        sp = 17-index;
    }

    // set the method of movement of enemy aircraft
    public void move() {
        //If the type of enemy aircraft is 5, then tilt to the left to move
        if(type==5){
            x -= 5;
            y += sp;
        }
        //If the enemy type is 5, then move tilted to the right
        else if(type==6){
            x += 5;
            y += sp;
        }
        //If other type, then move down normally
        else {
            y += sp;
        }
    }

    // determine whether the enemy aircraft is hit by a bullet
    public boolean shootBy(Fire f) {
        //get the image element attributes, determine the corresponding coordinate algorithm, determine whether the conditions are met, meet then be hit
        Boolean hit = x <= f.x+f.w &&x>f.x-w&&y<=f.y+f.h&&y>f.y-h;
        return hit;
    }

    // determine whether the enemy aircraft hit by the player aircraft
    public boolean shootBy(Hero f) {
        //get the image element properties, determine the corresponding coordinate algorithm, determine whether the conditions are met, meet the hit
        Boolean hit = x <= f.x+f.w &&x>f.x-w&&y<=f.y+f.h&&y>f.y-h;
        return hit;
    }
}



VIII.Fire.java

<ブロッククオート

弾丸クラス

package ui;

public class Fire extends FlyObject{
    // the current direction of movement of the bullet, 0 for the upper left corner of the fly, 1 vertical fly, 2 upper right corner of the fly
    int dir;

    / / constructor method, initialize the bullet
    public Fire(int hx,int hy,int dir){
        // get the picture of the bullet
        img = App.getImg("/img/fire.png");
        // Determine the size of the image, here the bullet size is reduced by a factor of 4
        w = img.getWidth()/4;
        h = img.getHeight()/4;
        // set the position of the bullet and the direction of the bullet according to the parameters passed in the constructor
        x = hx;
        y = hy;
        this.dir = dir;
    }

    // bullet movement method
    public void move() {
        // top left corner of the fly
        if(dir==0){
            x -= 1;
            y -= 10;
        }
        //Fly vertically up
        else if(dir == 1){
            y -= 10;
        }
        //Fly top right
        else if(dir == 2){
            x += 1;
            y -= 10;
        }
    }
}



IX.App.java

<ブロッククオート

メソッドクラス

package ui;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.image;
import java.io.IOException;
import java.io.InputStream;

// Tool class for processing images
// Here I have defined two methods to get the image, you can cross reference
public class App {
    //static can be common to all objects share the method, and can not depend on the object implementation
    public static BufferedImage getImg(String path){
        // catch exception with try method
        try {
            //io stream, the pipeline to transport data
            BufferedImage img = ImageIO.read(App.class.getResource(path));
            return img;
        }
        //Exception handling, print exception
        catch (IOException e) {
            e.printStackTrace();
        }
        //return null if not found
        return null;
    }

    // here and snake mini-game call method is the same
    public static ImageIcon getImg2(String path){
        InputStream is;
        //from the main class file is located in the path to find the corresponding path image
        is = App.class.getClassLoader().getResourceAsStream(path);
        // catch the exception with try method
        try {
            return new ImageIcon(ImageIO.read(is));
        }
        //Exception handling, print the exception
        catch (IOException e) {
            e.printStackTrace();
        }
        //return null if not found
        return null;
    }
}





X. エフェクトデモ