JAVA implementation of "simple maze" game | CSDN creation punch in

Posted by ThYGrEaTCoDeR201 on Sat, 05 Feb 2022 08:41:37 +0100

preface

Human beings have built mazes for 5000 years. During the development of different cultures in the world, these strange buildings always attract people to walk hard along winding and difficult paths to find the truth. Maze games came into being. In the game, the maze is represented as a dangerous area with all kinds of wonders and puzzles or treasures in the adventure stage. Types include caves, artificial buildings, monster nests, dense forests or mountain roads. There are villains or fierce creatures (real or imaginary objects) wandering in the maze, including traps, unknown facilities, relics, etc.

"Simple maze" game is implemented in java language, using swing technology for interface processing, and the design idea is object-oriented.

Main demand

Key control movement, the role out of the maze, the game victory.

Main design

1. Build game map panel

2. Set the maze map, including walkable passages, non walkable walls, and exit locations

3. Press the up, down, left and right keys of the keyboard to control the movement of the character

4. The algorithm of character movement, the channel can go, but not when encountering the wall

5. At the end, there is a prompt for successful customs clearance.

Function screenshot

Game start page

Mobile interface

Customs clearance interface

code implementation

Window layout

public class MainApp extends JFrame {
    public MainApp(){
        // Set form name
        setTitle("Simple maze game");
        // Gets the instance object of the custom game map panel
        MapPanel panel=new MapPanel();
        Container contentPane = getContentPane();
        contentPane.add(panel);
        // Execute and build form settings
        pack();
    }

    public static void main(String[] args) {
        MainApp app=new MainApp();
        // Allow form close operation
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // Display Form 
        app.setVisible(true);
    }
}

Core algorithm

public class MapPanel extends JPanel implements KeyListener {
    // Width and height of the form
    private static final int WIDTH = 450;
    private static final int HEIGHT = 450;
    // Set the default number of rows and columns for the background grid
    private static final int ROW = 15;
    private static final int COLUMN = 15;
    // Set a single image of the form, using 30x30 size graphics, and set 15 in one line, that is, 450 pixels, that is, the default size of the form
    private static final int SIZE = 30;

    // Set maze map
    private static final byte FLOOR = 0;// 0 indicates channel floor
    private static final byte WALL = 1;// 1 means wall
    private static final byte END = 2;// 2 indicates the end point
    private byte[][] map = {
            {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
            {1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1},
            {1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1},
            {1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1},
            {1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1},
            {1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 1},
            {1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1},
            {1, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1},
            {1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1},
            {1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1},
            {1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1},
            {1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 0, 0, 1, 1},
            {1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1},
            {1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1},
            {1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 2, 1}
    };

    // Sets the displayed image object
    private Image floorImage;
    private Image wallImage;
    private Image heroImage;
    private Image endImage;

    // Character coordinates
    private int x, y;

    // Distinguish the movement of up, down, left and right buttons
    private static final byte LEFT = 0;
    private static final byte RIGHT = 1;
    private static final byte UP = 2;
    private static final byte DOWN = 3;

    public MapPanel() {
        // Set panel size
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        // Load picture
        loadImage();
        // Initialize role coordinates
        this.x = 1;
        this.y = 1;
        // Set the focus on this form and listen for keyboard events
        setFocusable(true);
        addKeyListener(this);
    }

    /**
     * Draw maps and characters
     *
     * @param g paint brush
     */
    public void paintComponent(Graphics g) {
        drawMap(g);
        drawRole(g);
    }

    /**
     * Draw characters (Heroes)
     *
     * @param g paint brush
     */
    private void drawRole(Graphics g) {
        g.drawImage(heroImage, x * SIZE, y * SIZE, SIZE, SIZE, this);
    }

    private void loadImage() {
        // Get the floor image under the image folder corresponding to the current class
        ImageIcon icon = new ImageIcon(getClass().getResource("images/floor.png"));
        // Assign a floor image instance to the floorImage variable
        floorImage = icon.getImage();
        // Get wall image
        icon = new ImageIcon(getClass().getResource("images/wall.gif"));
        wallImage = icon.getImage();
        // Get hero image
        icon = new ImageIcon(getClass().getResource("images/hero.png"));
        heroImage = icon.getImage();
        // Get destination image
        icon = new ImageIcon(getClass().getResource("images/end.png"));
        endImage = icon.getImage();
    }

    /**
     * Draw the map according to the map information recorded in map[i][j]
     * Mark 0 as the floor and mark 1 as the wall
     *
     * @param g
     */
    private void drawMap(Graphics g) {
        for (int i = 0; i < ROW; i++) {
            for (int j = 0; j < COLUMN; j++) {
                switch (map[i][j]) {
                    case 0:
                        // When the mark is 0, draw the floor and load the image at the specified position
                        g.drawImage(floorImage, j * SIZE, i * SIZE, this);
                        break;
                    case 1:
                        // Mark 1 to draw the city wall
                        g.drawImage(wallImage, j * SIZE, i * SIZE, this);
                        break;
                    case 2:
                        // Mark 2 to draw the end point
                        g.drawImage(endImage, j * SIZE, i * SIZE, SIZE, SIZE, this);
                    default:
                        break;
                }
            }
        }
    }

    @Override
    public void keyTyped(KeyEvent e) {

    }

    @Override
    public void keyPressed(KeyEvent e) {
        // Move according to the key
        int keyCode = e.getKeyCode();// Get key code
        switch (keyCode) {
            // The left direction key or 'A' key can move left
            case KeyEvent.VK_LEFT:
                move(LEFT);
                break;
            case KeyEvent.VK_A:
                move(LEFT);
                break;
            // Right direction key or'D 'key can move to the right
            case KeyEvent.VK_RIGHT:
                move(RIGHT);
                break;
            case KeyEvent.VK_D:
                move(RIGHT);
                break;
            // The up arrow key or 'W' key can move up
            case KeyEvent.VK_UP:
                move(UP);
                break;
            case KeyEvent.VK_W:
                move(UP);
                break;
            // The down direction key or'S' key can move down
            case KeyEvent.VK_DOWN:
                move(DOWN);
                break;
            case KeyEvent.VK_S:
                move(DOWN);
                break;
            default:
                break;
        }
        // Redraw form image
        repaint();
        if (isFinish(x, y)) {
            // Move to exit
            JOptionPane.showMessageDialog(this, "Congratulations on customs clearance!");
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {

    }

    /**
     * Judge whether moving is allowed. If the incoming coordinate is not a wall, it can be moved
     *
     * @param x
     * @param y
     * @return If movement is allowed, return true; otherwise, return false
     */
    private boolean isAllowMove(int x, int y) {
        // Judge whether (x,y) is WALL or FLOOR as the basis for whether it can be moved
        // 1 indicates the wall and cannot be moved; 0 represents the floor and can be moved
        if (x < COLUMN && y < ROW) {// Parameter verification cannot exceed the length of the array
            return map[y][x] != 1;
        }
        return false;
    }

    /**
     * Mobile personas
     *
     * @param event The incoming movement direction can be LEFT, RIGHT, UP and DOWN respectively
     */
    private void move(int event) {
        switch (event) {
            case LEFT:// Shift left
                if (isAllowMove(x - 1, y)) {// Judge whether the position is allowed to move after moving one step to the left (it can be moved if it is not a wall)
                    x--;
                }
                break;
            case RIGHT:// Shift right
                if (isAllowMove(x + 1, y)) {
                    x++;
                }
                break;
            case UP:// Move up
                if (isAllowMove(x, y - 1)) {
                    y--;
                }
                break;
            case DOWN:// Move down
                if (isAllowMove(x, y + 1)) {
                    y++;
                }
            default:
                break;
        }
    }

    /**
     * Pass in the coordinates of the character to judge whether it reaches the end point
     *
     * @param x
     * @param y
     * @return
     */
    private boolean isFinish(int x, int y) {
        // 2 represents the end image
        // Note: the X coordinate represents the column and the Y coordinate represents the row, so it is map[y][x] instead of map[x][y]
        return map[y][x] == END;
    }
}


summary

Through the implementation of this simple maze game, I have a further understanding of the relevant knowledge of swing and a deeper understanding of the language java than before.

Some basic syntax of java, such as data types, operators, program flow control and arrays, are better understood. The core of java is the idea of object-oriented. I finally realized something about this concept.

Source code acquisition

Download address of source code: portal ---- >

After following the blogger, you can chat with the blogger for free

Today is the 5th / 100th day of continuous writing.
You can follow me, praise me, comment on me and collect me.

Topics: Java Game Development