Mind mapping

Technology comes from sharing, so today I find time to use Java to do before the small game collation posted for your reference. Java isn’t really a good place to write desktop applications, so this is just a fun way to get people to understand oop oop programming. The code is very simple, it is very easy to understand, and the notes are very clear, there are problems, to make up lessons in private.

The complete code

The enemy plane

importjava.util.Random; Enemy plane: is a flying object, is also the enemypublic class Airplane extends FlyingObject implements Enemy {
    private int speed = 3;  // Move the step
 
    /** Initializes data */
    public Airplane(a){
        this.image = ShootGame.airplane;
        width = image.getWidth();
        height = image.getHeight();
        y = -height;         
        Random rand = new Random();
        x = rand.nextInt(ShootGame.WIDTH - width);
    }
 
    /** get the score */
    @Override
    public int getScore(a) { 
        return 5;
    }
 
    /** /** /
    @Override
    public     boolean outOfBounds(a) {  
        return y>ShootGame.HEIGHT;
    }
 
    Mobile / * * * /
    @Override
    public void step(a) { y += speed; }}Copy the code

scores

/** ** reward */ 
public interface Award { 
    int DOUBLE_FIRE = 0;  // Double your firepower
    int LIFE = 1;   / / 1 life
    /** Get the type of reward (0 or 1 above) */ 
    int getType(a); 
}
Copy the code

The bees

import java.util.Random; 
 
/ * * * / bees 
public class Bee extends FlyingObject implements Award{ 
    private int xSpeed = 1;   // x-coordinate moving speed
    private int ySpeed = 2;   // The moving speed of y coordinate
    private int awardType;    // Reward type
 
    /** Initializes data */ 
    public Bee(a){ 
        this.image = ShootGame.bee; 
        width = image.getWidth(); 
        height = image.getHeight(); 
        y = -height; 
        Random rand = new Random(); 
        x = rand.nextInt(ShootGame.WIDTH - width); 
        awardType = rand.nextInt(2);   // Give a reward at initialization
    } 
 
    /** Type of reward */ 
    public int getType(a){ 
        return awardType; 
    } 
 
    /** handle */ 
    @Override 
    public boolean outOfBounds(a) { 
        return y>ShootGame.HEIGHT; 
    } 
 
    /** move, can fly oblique */ 
    @Override 
    public void step(a) {       
        x += xSpeed; 
        y += ySpeed; 
        if(x > ShootGame.WIDTH-width){   
            xSpeed = - 1; 
        } 
        if(x < 0){ 
            xSpeed = 1; }}}Copy the code

Bullets: flying objects

/** * Bullets: Are flying objects */ 
public class Bullet extends FlyingObject { 
    private int speed = 3;  // The speed of movement
 
    /** Initializes data */ 
    public Bullet(int x,int y){ 
        this.x = x; 
        this.y = y; 
        this.image = ShootGame.bullet; 
    } 
 
    Mobile / * * * / 
    @Override 
    public void step(a){    
        y-=speed; 
    } 
 
    /** handle */ 
    @Override 
    public boolean outOfBounds(a) { 
        returny<-height; }}Copy the code

Enemy score

/** * enemies can have scores */ 
public interface Enemy { 
    /** Enemy score */ 
    int getScore(a); 
}
Copy the code

Flying objects (enemy planes, bees, bullets, heroes)

import java.awt.image.BufferedImage; 
 
/** * Flying objects (enemy planes, bees, bullets, heroes) */ 
public abstract class FlyingObject { 
    protected int x;    / / x coordinate
    protected int y;    / / y
    protected int width;    / / wide
    protected int height;   / / high
    protected BufferedImage image;   / / picture
 
    public int getX(a) { 
        return x; 
    } 
 
    public void setX(int x) { 
        this.x = x; 
    } 
 
    public int getY(a) { 
        return y; 
    } 
 
    public void setY(int y) { 
        this.y = y; 
    } 
 
    public int getWidth(a) { 
        return width; 
    } 
 
    public void setWidth(int width) { 
        this.width = width; 
    } 
 
    public int getHeight(a) { 
        return height; 
    } 
 
    public void setHeight(int height) { 
        this.height = height; 
    } 
 
    public BufferedImage getImage(a) { 
        return image; 
    } 
 
    public void setImage(BufferedImage image) { 
        this.image = image; 
    } 
 
    /** ** check if it is out * @return true If it is out */ 
    public abstract boolean outOfBounds(a); 
 
    /** * Flying object moves one step */ 
    public abstract void step(a); 
 
    /** * Checks if the current flying object is shot by a Bullet (x,y) * @param Bullet object * @return true indicates that it was shot */ 
    public boolean shootBy(Bullet bullet){ 
        int x = bullet.x;  // Bullet abscissa
        int y = bullet.y;  // Bullet ordinate
        return this.x<x && x<this.x+width && this.y<y && y<this.y+height; }}Copy the code

Hero machine

import java.awt.image.BufferedImage; 
 
/** * hero: is a flying object */ 
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

The game starts the main class

import java.awt.Font; 
import java.awt.Color; 
import java.awt.Graphics; 
import java.awt.event.MouseAdapter; 
import java.awt.event.MouseEvent; 
import java.util.Arrays; 
import java.util.Random; 
import java.util.Timer; 
import java.util.TimerTask; 
import java.awt.image.BufferedImage; 
 
import javax.imageio.ImageIO; 
import javax.swing.ImageIcon; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 
 
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
    } 
 
    /** draw hero machine */ 
    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() { 
                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
 
    / * / * * shot 
    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 a flying object ** @return flying 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