“This is the 14th day of my participation in the First Challenge 2022.

❤️ Author’s home page: Xiao Xu Zhu

❤️ About the author: Hello everyone, I am Xiao Xu Zhu. Java field quality creator 🏆, CSDN blog expert 🏆, Huawei cloud enjoy expert 🏆, Nuggets of the year popular author 🏆, Ali Cloud expert blogger 🏆

❤️ technology live, the appreciation

❤️ like 👍 collect ⭐ look again, form a habit

preface

“Aircraft war -II” is a fusion of arcade, competitive and other elements of the classic shooting mobile tour. Gorgeous and exquisite game screen, super dazzle with a sense of skill special effects, super hot screen let you adrenaline burst, give you a full range of shock feeling, experience the infinite fun of flying combat.

The game is implemented in Java language, using Swing technology for interface processing, design ideas with object-oriented thought.

The main requirements

Players control a fighter to ensure that they are not destroyed by enemy planes. The more enemy planes destroyed, the energy can be collected to replenish the number of player fighters. If the player has zero fighters, the game ends.

The main design

1. Use Swing library to make visual interface, draw player fighter planes, different enemy planes, draw background pictures and draw bullets

2, mouse control fighter movement

3, with thread to achieve picture refresh.

4, random generation of enemy aircraft algorithm

5. Score calculation algorithm

6. Collision algorithm between bullets and flying objects

Screenshot function

The game start

The game pauses

Game over

Code implementation

Start the class


public class ShootGame extends JPanel {
    public static final int WIDTH = 400; / / panel width
    public static final int HEIGHT = 654; / / panel
    /** * START RUNNING PAUSE GAME_OVER */
    private int state;
    private static final int START = 0;
    private static final int RUNNING = 1;
    private static final int PAUSE = 2;
    private static final int GAME_OVER = 3;

    private int score = 0; / / score
    private Timer timer; / / timer
    private int intervel = 1000 / 100; // Time interval (milliseconds)

    public static BufferedImage background;
    public static BufferedImage start;
    public static BufferedImage airplane;
    public static BufferedImage bee;
    public static BufferedImage bullet;
    public static BufferedImage hero0;
    public static BufferedImage hero1;
    public static BufferedImage pause;
    public static BufferedImage gameover;

    private FlyingObject[] flyings = {}; // Array of enemy aircraft
    private Bullet[] bullets = {}; // Bullet array
    private Hero hero = new Hero(); / / hero machine

    static { // Static code block to initialize image resource
        try {
            background = ImageIO.read(ShootGame.class
                    .getResource("background.png"));
            start = ImageIO.read(ShootGame.class.getResource("start.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"));
        } catch(Exception e) { e.printStackTrace(); }}/ * * * * /
    @Override
    public void paint(Graphics g) {
        g.drawImage(background, 0.0.null); // Draw the background image
        paintHero(g); // Draw the hero machine
        paintBullets(g); / / draw the bullet
        paintFlyingObjects(g); // Draw a flying object
        paintScore(g); / / draw scores
        paintState(g); // Draw the game state
    }

    /** ** */
    public void paintHero(Graphics g) {
        g.drawImage(hero.getImage(), hero.getX(), hero.getY(), null);
    }

    /** * draw bullets */
    public void paintBullets(Graphics g) {
        for (int i = 0; i < bullets.length; i++) {
            Bullet b = bullets[i];
            g.drawImage(b.getImage(), b.getX() - b.getWidth() / 2, b.getY(),
                    null); }}/** * draw a flying object */
    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); }}/** * draw fractions */
    public void paintScore(Graphics g) {
        int x = 10; / / x coordinate
        int y = 25; / / y
        Font font = new Font(Font.SANS_SERIF, Font.BOLD, 22); / / font
        g.setColor(new Color(0xFF0000));
        g.setFont(font); // Set the font
        g.drawString("SCORE:" + score, x, y); / / draw scores
        y = y + 20; // Increase y by 20
        g.drawString("LIFE:" + hero.getLife(), x, y); / / draw life
    }

    /** * draw the game state */
    public void paintState(Graphics g) {
        switch (state) {
            case START: // Start status
                g.drawImage(start, 0.0.null);
                break;
            case PAUSE: // Pause state
                g.drawImage(pause, 0.0.null);
                break;
            case GAME_OVER: // The game is terminated
                g.drawImage(gameover, 0.0.null);
                break; }}public static void main(String[] args) {
        JFrame frame = new JFrame("Fly");
        ShootGame game = new ShootGame(); // Panel object
        frame.add(game); // Add the panel to the JFrame
        frame.setSize(WIDTH, HEIGHT); // Set the size
        frame.setAlwaysOnTop(true); // Set it always at the top
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // The operation is closed by default
        frame.setIconImage(new ImageIcon("images/icon.jpg").getImage()); // Sets the icon for the form
        frame.setLocationRelativeTo(null); // Sets the initial position of the form
        frame.setVisible(true); Call paint as soon as possible

        game.action(); // Start execution
    }

    /** * start executing code */
    public void action(a) {
        // Mouse listening events
        MouseAdapter l = new MouseAdapter() {
            @Override
            public void mouseMoved(MouseEvent e) { // Mouse movement
                if (state == RUNNING) { // Move the hero in running state with mouse position
                    int x = e.getX();
                    inty = e.getY(); hero.moveTo(x, y); }}@Override
            public void mouseEntered(MouseEvent e) { // Mouse entry
                if (state == PAUSE) { // Run in pause statestate = RUNNING; }}@Override
            public void mouseExited(MouseEvent e) { // Mouse exit
                if (state == RUNNING) { // If the game is not over, set it to pausestate = PAUSE; }}@Override
            public void mouseClicked(MouseEvent e) { // Mouse click
                switch (state) {
                    case START:
                        state = RUNNING; // Run in startup state
                        break;
                    case GAME_OVER: // Game over, clean up the scene
                        flyings = new FlyingObject[0]; // Empty the flying object
                        bullets = new Bullet[0]; // Empty the bullets
                        hero = new Hero(); // recreate the hero machine
                        score = 0; // Clear the score
                        state = START; // State is set to start
                        break; }}};this.addMouseListener(l); // Handle mouse clicks
        this.addMouseMotionListener(l); // Handle mouse sliding

        timer = new Timer(); // Master process control
        timer.schedule(new TimerTask() {
            @Override
            public void run(a) {
                if (state == RUNNING) { // Running status
                    enterAction(); // Fly in
                    stepAction(); / / step
                    shootAction(); // Hero machine shooting
                    bangAction(); // The bullet hit the flying object
                    outOfBoundsAction(); // Remove flyers and bullets
                    checkGameOverAction(); // Check game over
                }
                repaint(); // Redraw, call paint()
            }

        }, intervel, intervel);
    }

    int flyEnteredIndex = 0; // Count of flights

    /** * Fly in */
    public void enterAction(a) {
        flyEnteredIndex++;
        if (flyEnteredIndex % 40= =0) { // Generate a flying object in 400 milliseconds --10*40
            FlyingObject obj = nextOne(); // Generate a random flying object
            flyings = Arrays.copyOf(flyings, flyings.length + 1);
            flyings[flyings.length - 1] = obj; }}/** ** take a step */
    public void stepAction(a) {
        for (int i = 0; i < flyings.length; i++) { // The flying object takes a step
            FlyingObject f = flyings[i];
            f.step();
        }

        for (int i = 0; i < bullets.length; i++) { // The bullet takes a step
            Bullet b = bullets[i];
            b.step();
        }
        hero.step(); // The hero takes a step
    }

    /** * Flying object take a step */
    public void flyingStepAction(a) {
        for (int i = 0; i < flyings.length; i++) { FlyingObject f = flyings[i]; f.step(); }}int shootIndex = 0; // Count shots

    /** * shooting */
    public void shootAction(a) {
        shootIndex++;
        if (shootIndex % 30= =0) { // One shot in 300 milliseconds
            Bullet[] bs = hero.shoot(); // The hero shoots
            bullets = Arrays.copyOf(bullets, bullets.length + bs.length); / / capacity
            System.arraycopy(bs, 0, bullets, bullets.length - bs.length,
                    bs.length); // Append an array}}/** * Bullet collision detection with flying object */
    public void bangAction(a) {
        for (int i = 0; i < bullets.length; i++) { // Iterate over all bullets
            Bullet b = bullets[i];
            bang(b); // Collision check between bullet and flying object}}/** * Remove flying objects and bullets */
    public void outOfBoundsAction(a) {
        int index = 0; / / index
        FlyingObject[] flyingLives = new FlyingObject[flyings.length]; // Live flying object
        for (int i = 0; i < flyings.length; i++) {
            FlyingObject f = flyings[i];
            if(! f.outOfBounds()) { flyingLives[index++] = f;// Don't cross the line
            }
        }
        flyings = Arrays.copyOf(flyingLives, index); // Keep all flying objects that do not cross the boundary

        index = 0; // The index is reset to 0
        Bullet[] 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);// Save bullets that do not cross the line
    }

    /** * Check game over */
    public void checkGameOverAction(a) {
        if (isGameOver() == true) {
            state = GAME_OVER; // Change the state}}/** * Check if the game is over */
    public boolean isGameOver(a) {

        for (int i = 0; i < flyings.length; i++) {
            int index = -1;
            FlyingObject obj = flyings[i];
            if (hero.hit(obj)) { // Check whether hero collides with flying object
                hero.subtractLife(); / / life
                hero.setDoubleFire(0); // Double down
                index = i; // Record the index of the flying objects encountered
            }
            if(index ! = -1) {
                FlyingObject t = flyings[index];
                flyings[index] = flyings[flyings.length - 1];
                flyings[flyings.length - 1] = t; // Swap with the last flying object encountered

                flyings = Arrays.copyOf(flyings, flyings.length - 1); // Delete the flying objects encountered}}return hero.getLife() <= 0;
    }

    /** * Collision check between bullets and flying objects */
    public void bang(Bullet bullet) {
        int index = -1; // Index of flying objects hit
        for (int i = 0; i < flyings.length; i++) {
            FlyingObject obj = flyings[i];
            if (obj.shootBy(bullet)) { // Determine if it hit
                index = i; // Index of hit flying objects
                break; }}if(index ! = -1) { // There is a hit flying object
            FlyingObject one = flyings[index]; // Record the flying object that was hit

            FlyingObject temp = flyings[index]; // The hit flying object swaps with the last flying object
            flyings[index] = flyings[flyings.length - 1];
            flyings[flyings.length - 1] = temp;

            flyings = Arrays.copyOf(flyings, flyings.length - 1); // Remove the last flying object that was hit

            // Check the type of one (bonus points for enemies, bonus gain)
            if (one instanceof Enemy) { // Check the type, is the enemy, plus points
                Enemy e = (Enemy) one; // Cast
                score += e.getScore(); / / points
            } else { // If it is a reward, set a reward
                Award a = (Award) one;
                int type = a.getType(); // Get the reward type
                switch (type) {
                    case Award.DOUBLE_FIRE:
                        hero.addDoubleFire(); // Double the firepower
                        break;
                    case Award.LIFE:
                        hero.addLife(); // Set bonus life
                        break; }}}}/** * Randomly generates flying objects **@returnFlying object */
    public static FlyingObject nextOne(a) {
        Random random = new Random();
        int type = random.nextInt(20); / / [0, 20)
        if (type < 4) {
            return new Bee();
        } else {
            return newAirplane(); }}}Copy the code

Player-controlled aircraft


public class Hero extends FlyingObject{
	
	private BufferedImage[] images = {};  // The hero image
	private int index = 0;                // Switch index
	
	private int doubleFire;   // Double your firepower
	private int life;   / / life
	
	/** Initializes data */
	public Hero(a){
		life = 3;   // Initial 3 lives
		doubleFire = 0;   // Initial firepower is 0
		images = new BufferedImage[]{ShootGame.hero0, ShootGame.hero1}; // Array of hero images
		image = ShootGame.hero0;   // The initial hero0 image
		width = image.getWidth();
		height = image.getHeight();
		x = 150;
		y = 400;
	}
	
	/** Get double firepower */
	public int isDoubleFire(a) {
		return doubleFire;
	}

	/** Set double firepower */
	public void setDoubleFire(int doubleFire) {
		this.doubleFire = doubleFire;
	}
	
	/** Increase firepower */
	public void addDoubleFire(a){
		doubleFire = 40;
	}
	
	/ * * * / life
	public void addLife(a){  / / gain life
		life++;
	}
	
	/** 减命 */
	public void subtractLife(a){   / / life
		life--;
	}
	
	/** Get life */
	public int getLife(a){
		return life;
	}
	
	/** The current object moved a bit, relative distance, x,y mouse position */
	public void moveTo(int x,int y){   
		this.x = x - width/2;
		this.y = y - height/2;
	}

	/** handle */
	@Override
	public boolean outOfBounds(a) {
		return false;  
	}

	/** Fires bullets */
	public Bullet[] shoot(){   
		int xStep = width/4;      / / 4 and a half
		int yStep = 20;  / / step
		if(doubleFire>0) {// Double your firepower
			Bullet[] bullets = new Bullet[2];
			bullets[0] = new Bullet(x+xStep,y-yStep);  // Y-ystep (position of bullet from aircraft)
			bullets[1] = new Bullet(x+3*xStep,y-yStep);
			return bullets;
		}else{      // Single power
			Bullet[] bullets = new Bullet[1];
			bullets[0] = new Bullet(x+2*xStep,y-yStep);  
			returnbullets; }}Mobile / * * * /
	@Override
	public void step(a) {
		if(images.length>0){
			image = images[index++/10%images.length];  // Switch images hero0, hero1}}/** Collision algorithm */
	public boolean hit(FlyingObject other){
		
		int x1 = other.x - this.width/2;                 // The minimum distance of the x coordinate
		int x2 = other.x + this.width/2 + other.width;   // Maximum distance of x coordinate
		int y1 = other.y - this.height/2;                // The minimum distance of y coordinates
		int y2 = other.y + this.height/2 + other.height; // The maximum distance of y coordinates
	
		int herox = this.x + this.width/2;               // The distance to the center of the hero x coordinate
		int heroy = this.y + this.height/2;              // The distance to the center of the hero y coordinate
		
		return herox>x1 && herox<x2 && heroy>y1 && heroy<y2;   // A collision occurs within the interval}}Copy the code

conclusion

Through the aircraft War -II game implementation, LET me have a further understanding of swing related knowledge, the Language of Java has a deeper understanding than before.

Basic Java syntax, such as data types, operators, program flow control, and arrays, is better understood. Java is the core of the core object oriented thought, for this concept, finally realized some.

The source code for

After clicking “like” and following the blogger, the private blogger will get it for free