SoFunction
Updated on 2024-07-16

Java development to implement the aircraft wars

In this paper, we share the example of Java to achieve the specific code of the aircraft war, for your reference, the details are as follows

I. Airplane Wars

1 Parent class that encapsulates the public properties and functions of all flying objects

import 

/**
 * Parent class that encapsulates the public properties and functions of all flying objects
 */
public abstract class Flyer {
    protected int x; // Upper left corner of the flying object x-coordinate
    protected int y; //Flying object upper left corner y-coordinate
    protected int height; //Flying object altitude
    protected int width; //Width of flying objects
    protected BufferedImage image; //Pictures of flying objects

    /**
     * Requires that all flying objects must be able to move
     * but the way to move is implemented by the subclass itself
     */
    public abstract void step();

    /**
     * Methods to check for out-of-bounds
     * @return Whether or not it is out of bounds
     */
    public abstract boolean outOfBounds();

    /**
     * Tool method that specializes in detecting if two rectangular flying objects collide
     * It's not object-specific, so it's defined as a static method.
     * @param f1 flight object 1
     * @param f2 flight object 2
     * @return Whether or not they collide.
     */
    public static boolean boom(Flyer f1,Flyer f2){
        //step1: Find the centers of two rectangles.
        int f1x =  + /2;
        int f1y =  + /2;
        int f2x =  + /2;
        int f2y =  + /2;
        //step2: Lateral and Vertical Collision Detection
        boolean H = (f1x - f2x) < ( + )/2;
        boolean V = (f1y -f2y) < ( + )/2;
        //step3: must collide in both directions
        return H&V;
    }

}

2 Encapsulating Hero Machine Attributes and Function Classes

import ;

/**
 * Encapsulate the attributes and function classes of the hero machine
 */
public class Hero extends Flyer {

    private int doubleFire; //Double fire rounds
    private int life; //Life value
    private int score; //Score

    //Externally provide methods to read life values
    public int getLife(){
        return life;
    }

    //Externally available methods of obtaining scores
    public int getScore(){
        return score;
    }

    /**
     * Referenceless constructor for the hero machine object
     */
    public Hero(){
        image = ShootGame.hero0;
        height = ();
        width = ();
        x = 127;
        y = 388;
        doubleFire = 0;
        life = 3;
        score = 0;
    }

    /**
     * A way to animate the hero machine
     * Make the image of the hero machine switch between hero0 and hero1.
     */
    @Override
    public void step() {
        Random r = new Random();
        if((2) == 0){
            image = ShootGame.hero0;
        }else{
            image = ShootGame.hero1;
        }
    }

    @Override
    public boolean outOfBounds() {
        // TODO Auto-generated method stub
        return false;
    }

    /**
     * Method for the hero machine to move with the mouse
     * Requires the current mouse position to be passed in
     * @param x The x coordinate of the mouse position
     * @param y The y coordinate of the mouse position
     */
    public void move(int x,int y){
        // The incoming x and y are the mouse coordinates.
        The purpose of //move is to align the center of the hero machine with the mouse position
         = x - width / 2;
         = y - height / 2;
    }

    /**
     * Methods for the hero plane to get points or rewards
     * @param f is a flying object parent method that can point to an enemy or large airplane
     */
    public void getScore_Award(Flyer f){
        // Judge the type of the enemy object first
        if(f instanceof Airplane){ //If the enemy is an enemy aircraft
            //Get the score in the enemy aircraft object and add it to the current score.
            score += ((Airplane)f).getScore();
        }else{ // If the object is a large airplane
            // Continue to determine the type of rewards held in the large airplane object
            if(((BigPlane)f).getAwardType() == BigPlane.DOUBLE_FIRE){
                // If the save is double fire
                doubleFire += 20;
            }else{
                //If the save is a life bonus
                life += 1;
            }
        }

    }

    /**
     * The hero machine's method of firing bullets
     * @return The name of the newly created bullet pair.
     * It could be one or two bullets, saved in an array.
     */
    public Bullet[] shoot(){
        Bullet[] bullets = null;
        //When to turn on double fire:
        if(doubleFire != 0){ //Creating double fire
            bullets = new Bullet[2];
            Bullet b1 = new Bullet(x + width/4 - ()/2,y + ());
            Bullet b2 = new Bullet(x + width*3/4 - ()/2,y + ());
            bullets[0] = b1;
            bullets[1] = b2;
            // doubleFire -1 for each doubleFire created
            doubleFire -= 1;
        }else{
            //single fire:
            //Bullet x-coordinate: x + hero machine width/2 - bullet width/2
            // Bullet y-coordinate: y-bullet height
            bullets = new Bullet[1];
            bullets[0] = new Bullet(x + width/2 - ()/2,y - ());
        }
        return bullets;
    }

    /**
     * Hero machine's own collision detection method with enemies
     * @param f Enemies that may collide
     * It could be an enemy plane or a large airplane.
     * @return Whether or not there is a collision.
     */
    public boolean hit(Flyer f){
        // Call the collision detection method to detect whether there is a collision or not
        boolean r = (this, f);
        if(r){ //If collision
            life--;
            doubleFire = 0;
        }
        return r;
    }

}

3 Classes encapsulating enemy aircraft properties and functions

import ;

/**
 * Classes encapsulating the properties and functions of the enemy aircraft
 */
public class Airplane extends Flyer {

    private int speed = 2; // Enemy aircraft fall 2 units at a time.
    private int score = 5; // Bonus points contained in enemy aircraft

    // Externally available method of reading bonus scores for enemy aircraft
    public int getScore(){
        return score;
    }

    /**
     * Referenceless constructor for the adversary class
     */
    public Airplane(){
        image = ;
        width = ();
        height = ();
        y = -height;
        Random r = new Random();
        x = ( - width);
    }

    @Override
    public void step() {
        //Enemy planes move down one speed length at a time.
        y += speed;
    }

    @Override
    public boolean outOfBounds() {
        //Enemy aircraft y-coordinates> game interface, out-of-bounds
        return y > ;
    }

}

4 Classes that encapsulate the attributes and functions of a large airplane

import ;

/**
 * Classes encapsulating the attributes and functions of a large airplane
 */
public class BigPlane extends Flyer {

    /* Define alternative constants for reward types */
    public static final int DOUBLE_FIRE = 0; //Reward type is 0, indicating that double firepower is rewarded
    public static final int FILE = 1; //Reward type is 1, stating that one life is rewarded

    /* Private member of the large aircraft class */
    private int xspeed = 1; // Horizontal movement with a speed of 1
    private int yspeed = 2; //Vertical movement at a speed of 2
    private int awardType; //Current type of reward saved for large planes

    // Externally available methods for reading large airplane award types
    public int getAwardType(){
        return awardType;
    }

    /**
     * :: Parameterless construction method for large airplanes
     */
    public BigPlane(){
        //step1: Get the static variable for the bigplane image from the main program - bigplane
        image = ;
        //step2: Setting the object's width with the image's width
        width = ();
        height= ();
        //step3: set the altitude at which the big plane will start falling.
        y = -height;
        //step4: the x-coordinate at which the big plane object starts to fall is randomized before 0~(width of the interface - width of the big plane image).
        Random r = new Random();
        x = ( - width);
        //Randomly select a reward type between 0 and 1 first
        awardType = (2);
    }

    @Override
    public void step() {
        // Move x one xspeed and y one yspeed at a time.
        x += xspeed;
        y += yspeed;
        //Large planes can't be lifted out of the boundary, if they are out of the boundary then xspeed*(-1), which is equivalent to moving in reverse.
        if(x < 0 || x >  - width){
            xspeed *= -1;
        }
    }

    @Override
    public boolean outOfBounds() {
        // y-coordinate of the big airplane > game interface, out of bounds
        return y > ;
    }
}

5 Bullets

public class Bullet extends Flyer{

    private int speed = 5; //Bullets rise at a rate of 3

    /**
     * The bullet class' constructor with parameters
     * Because the position of the bullet object creation is determined by the position of the hero machine
     * So the x and y of the bullet pair names have to be passed in from the outside world.
     * @param x The x-coordinate of the hero machine's specified bullet creation position.
     * @param y The y coordinate of the hero machine's specified bullet creation position.
     */
    public Bullet(int x,int y){
        image = ;
        width = ();
        height = ();
         = x;
         = y;
    }

    @Override
    public void step() {
        //Bullets move up one speed length at a time.
        y -= speed;
    }

    @Override
    public boolean outOfBounds() {
        //y-coordinate of the bullet + height of the bullet <0, out of bounds
        return (y + height) < 0;
    }
}

6 Master Methods for Plane Wars Shooting

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;

public class ShootGame extends JPanel {

    private static final long serialVersionUID = 1L;

    //Background image size 320*568
    public static final int WIDTH = 320;
    public static final int HEIGHT = 568;
    //Game interface fixed size 336*607
    public static final int FRAME_WIDTH = 336;
    public static final int FRAME_HEIGHT = 607;

    /*
     * The first thing the game does when it starts is load all the images it needs from the hard disk into memory.
     * And only loaded once at startup - static blocks
     * All the images cached in the program are used repeatedly and only one copy is saved - static variables.
     * Below, load a static variable for each image, and then load each image in a static block
     */
    public static BufferedImage background; //Background image
    public static BufferedImage start; //Start picture
    public static BufferedImage airplane; //Pictures of enemy aircraft
    public static BufferedImage bigplane; //Large aircraft
    public static BufferedImage hero0; //Hero machine status 0
    public static BufferedImage hero1; // Hero machine status 1
    public static BufferedImage bullet; // Bullets
    public static BufferedImage pause; // Pause the picture
    public static BufferedImage gameover; // Game Over

    // Static blocks, executed once when the class is loaded into the method area, specialize in loading static resources
    static{
        /*
         * java load image from hard disk into memory:
         * method: a static method dedicated to loading images from hard disk
         * No need to instantiate, call it directly
         * :Get the path to the loader of the current class
         * ("filename"); load the specified file from the path where the current class is located into the program
         */
        try {
            background = ((""));
            airplane = ((""));
            bigplane = ((""));
            bullet = ((""));
            start = ((""));
            pause = ((""));
            hero0 = ((""));
            hero1 = ((""));
            gameover = ((""));
        } catch (IOException e) {
            // TODO Auto-generated catch block
            ();
        }
    }

    /*
     * Define data structures for the characters in the game, including:
     * 1 object for the hero plane
     * 1 object array storing all enemies (enemy and big planes)
     * 1 object array storing all bullets
     */
    public Hero hero = new Hero();
    public Flyer[] flyers = {}; // Array storing all enemy objects
    public Bullet[] bullets = {}; // Array storing all bullet objects

    // Define game state: current state variable: default is start state
    private int state = START;
    // Define the option constants for the game 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;


    public static void main(String[] args) {

        /*
         * Drawing forms in java: JFrame object - window frame
         * To draw content in a form, you also need to embed a background panel - JPanel
         */
        JFrame frame = new JFrame("ShootGame");
        (FRAME_WIDTH,FRAME_HEIGHT);//(336, 607);
        (true); //Set the form top
        //Set the form to close and exit the program at the same time.
        (JFrame.EXIT_ON_CLOSE);
        (null); //Set the position of the form, null means center.

        /* Embed background panel object in form - JPanel */
        ShootGame game = new ShootGame(); // Create a background panel object
        (game); //Embed the background panel object into the form object.
        /* Forms are not visible by default! The setVisible method must be called to display the form */
        (true); // Automatically call the form's paint method.
        ();
    }

    /**
     * What to do when the game starts
     */
    public void action(){

        /* To define the mouse events to listen to when the game starts */
        //step1: Create the MouseAdapter anonymous inner class - the event response program.
        MouseAdapter l = new MouseAdapter(){
            //step2: Rewrite the desired mouse event, mouseover.
            @Override
            public void mouseMoved(MouseEvent e) {
                //Hero machine follows the mouse only in RUNNING state
                if(state == RUNNING){
                    //step3: get new mouse position
                    int x = ();
                    int y = ();
                    //step4: The move method that passes the mouse position to the hero machine.
                    (x, y);
                }
            }

            @Override
            public void mouseClicked(MouseEvent e) {
                if(state == START || state == PAUSE){ //START or PAUSE state, click to change to RUNNING state.
                    state = RUNNING;
                }else if(state == RUNNING){ // Game click to pause
                    state = PAUSE;
                }else if(state == GAME_OVER){ //Click after the end of the game to initialize the game
                    state = START;
                    // From GAME_OVER to START, re-initialize the game data.
                    flyers = new Flyer[0];
                    bullets = new Bullet[0];
                    hero = new Hero();
                }
            }


            @Override
            public void mouseExited(MouseEvent e) {
                if(state == RUNNING){
                    //Pause mouseover only when in RUNNING state.
                    state = PAUSE;
                }
            }

            @Override
            public void mouseEntered(MouseEvent e) {
                if(state == PAUSE){
                    state = RUNNING;
                }
            }

        }; //Anonymous inner classes should end with a semicolon.
        /*step5: To respond to mouse events, you must add the mouse event to the program's listener*/.
        (l); //Supports mouse movement events, does not support mouse click events.
        (l);; //Support mouse click events

        //step1: Creating a timer
        Timer timer = new Timer();
        //step2: call the schedule method of the timer object to make a schedule
        // First argument: an anonymous inner class of type TimerTask.
        // Must override run method - core - what to do
        (new TimerTask(){
            // First define a timer variable index to record the number of times the run method runs
            private int runTimes = 0;

            @Override
            public void run() {
                //Except for the REPAINT method, the rest of the functions are only executed in the RUNNING state
                if(state == RUNNING){
                    // Every time the run method is executed, runTimes is +1.
                    runTimes++;

                    //Spawns enemies every 500 milliseconds.
                    if(runTimes % 50 == 0){
                        nextOne(); //Automatic random creation of enemy objects
                    }
                    // Iterate through each object, calling the object's STEP method, moving the object's position once
                    for(int i = 0;i < ;i++){
                        flyers[i].step();
                    }

                    // Generate bullets every 300 milliseconds.
                    if(runTimes % 30 == 0){
                        shoot(); //Creating a bullet once
                    }
                    // Iterate through each object in the bullet array, moving the position
                    for(int i = 0;i < ;i++){
                        bullets[i].step();
                    }

                    // Hero motorized painting effect
                    ();

                    // Add collision detection for bullets and enemies
                    boom();

                    // Hero Machine Collision Detection
                    hit();

                    //Add cross-border detection
                    outOfBounds();
                }
                /* Emphasize: whenever the interface changes, the repaint method must be called to repaint the interface */
                repaint();
            }

        }, 10,10); //Interface changes every 10 milliseconds.

    }


    @Override
    public void paint(Graphics g) {
        //step1: Draw the background image
        (background, 0, 0, null);
        //step2: Drawing the Hero Machine
        paintHero(g);
        //step3: Batch Draw Enemy Array
        paintFlyers(g);
        //step4: Batch Draw Bullet Array
        paintBullets(g);
        //Mapping of scores and life values
        paintScore_Life(g);

        // Draw different pictures according to the game state
        if(state == START){
            (start, 0, 0, null);
        }else if(state == PAUSE){
            (pause, 0, 0, null);
        }else if(state == GAME_OVER){
            (gameover, 0, 0, null);
        }

    }

    /**
     * Method for drawing the hero machine object
     * @param g brush
     */
    public void paintHero(Graphics g){
        (, , , null);
    }

    /**
     * Iterate over the array of enemies and batch draw all of them
     * @param g
     */
    public void paintFlyers(Graphics g){
        for(int i = 0;i < ;i++){
            (flyers[i].image, flyers[i].x, flyers[i].y, null);
        }
    }

    /**
     * Iterate over the array of bullets and batch draw all the bullets
     * @param g
     */
    public void paintBullets(Graphics g){
        for(int i = 0;i < ;i++){
            (bullets[i].image, bullets[i].x, bullets[i].y, null);
        }
    }

    /**
     * Randomly generate 1 enemy object
     * Each time a new enemy is generated, the array of flyers is expanded by one.
     * Then put the new enemy into the last element of the array.
     */
    public void nextOne(){
        Random r = new Random();
        Flyer f = null;
        if((20) == 0){ // Create a large airplane only if the random number takes 0.
            f = new BigPlane();
        }else{ // All the rest generate enemy aircraft
            f = new Airplane();
        }
        // Expansion of the flyers array1
        flyers = (flyers,  + 1);
        // Put the new enemy at the end of the array.
        flyers[ - 1] = f;
    }

    /**
     * Get the bullet object fired by the hero machine object
     * Save the new bullet object into the bullet array to unify management
     */
    public void shoot(){
        Bullet[] newBullets = (); // Get the array of new bullets returned by the hero machine
        // Expand the array of bullets according to the number of new bullets returned.
        bullets = (bullets,  + );
        // Copy all elements from the newBullets array to the end of the bullets array.
        (newBullets, 0, bullets,  - , );

    }

    /**
     * Iterate over the bullet and enemy arrays to perform collision detection
     * Once a collision occurs, both bullets and enemies are reduced by one
     */
    public void boom(){
        for(int i = 0;i < ;i++){
            for(int j = 0;j < ;j++){
                if((bullets[i], flyers[j])){
                    //Get points and rewards for hero machines
                    hero.getScore_Award(flyers[j]);
                    // Remove hit enemy planes from the enemy array.
                    //step1: Replace the hit enemy plane with the last element of the enemy array.
                    flyers[j] = flyers[ - 1];
                    //step2: compressing arrays
                    flyers = (flyers,  - 1);
                    // Remove bullets that hit enemy aircraft from the bullet array.
                    bullets[i] = bullets[ - 1];
                    bullets = (bullets,  -1);
                    i--; // The first time a collision is detected, the bullet has to retreat one element to re-detect its current position.
                    break; // Exit the loop for the current enemy array as soon as a collision is detected
                }
            }
        }
    }

    /**
     * Methods for plotting scores and life values
     * @param g
     */
    public void paintScore_Life(Graphics g){
        int x = 10; //The x-coordinate of the text in the upper left corner
        int y = 15; // y-coordinate of the text in the upper left corner
        Font font = new Font(Font.SANS_SERIF,,14);
        (font); //Set the brush object for the font
        // Plotting the first row: fraction
        ("SCORE: " + (), x, y);
        // Plot second row: life value, y-coordinate shifted down 20 units
        y += 20;
        ("LIFE: " + (), x, y);
    }

    /**
     * :: Checking all flying objects for overruns
     */
    public void outOfBounds(){
        //Checks that all enemies have not crossed the border
        Flyer[] Flives = new Flyer[];
        // Iterate through the enemy array and store the surviving enemy objects in a new array.
        // Set the counter index of the Flives array: 1. Marks the position of the next surviving object.
        // 2. Count how many elements are in the Flives.
        int index = 0;
        for(int i = 0;i < ;i++){
            if(!flyers[i].outOfBounds()){ // No out-of-bounds objects
                Flives[index] = flyers[i];
                index++;
            } // After the traversal is finished:
            //index is the number of surviving objects.
            The //Flives array is the number of living objects, indexed.
            //Compress the Flives array to index size
            // The new compressed array should replace the flyers array.
        }
        flyers = (Flives, index);

        //Detect all bullets for overruns
        Bullet[] Blives = new Bullet[];
        index = 0;
        for(int i = 0;i < ;i++){
            if(!bullets[i].outOfBounds()){
                Blives[index] = bullets[i];
                index++;
            }
        }
        bullets = (Blives, index);
    }

    /**
     * Iterate through the enemy array and determine if the hero machine and each enemy collide
     */
    public void hit(){
        Flyer[] lives = new Flyer[];
        //Record of surviving enemies
        int index = 0;
        for(int i = 0;i < ;i++){
            if(!(flyers[i])){
                lives[index] = flyers[i];
                index++;
            }
        }
        if(() <= 0){ //If the hero machine's life value is less than or equal to 0, the game ends.
            state = GAME_OVER;
        }
        // Compress the array of enemies and replace the array
        flyers = (lives, index);

    }
}

II. Test results

This is the entire content of this article.