“This is the 8th day of my participation in the First Challenge 2022. For details: 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

Humans have been building mazes for 5,000 years. At different times in the world’s cultural development, these strange structures have always drawn people to trudge along winding and difficult paths in search of the truth. The labyrinth type small game arises at the historic moment. In the game, mazes are represented as dangerous areas in the adventure stage that contain all kinds of wonders and puzzles or treasures. There are caves, artificial buildings, monster lair, forest or mountain road, etc. The maze has villains or ferocious creatures (real or imagined) wandering around, and there may be traps, unknown installations, relics, etc.

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

The main requirements

Direction key control movement, the role out of the maze, the game victory.

The main design

1. Build the game map board

2. Set up a maze map, including walkable passages, unwalkable walls, and exit positions

3, the keyboard up and down around the key, to control the movement of the role

4, the role of the movement of the algorithm, the channel can go, encounter the wall can not go

5, go to the end, there is a successful clearance tips.

Screenshot function

Game start page

Moving boundary

Clearance interface

Code implementation

Window layout


public class MainApp extends JFrame {
    public MainApp(a){
        // Sets the form name
        setTitle("Easy Maze Game.");
        // Get the instance object of the custom game map panel
        MapPanel panel=new MapPanel();
        Container contentPane = getContentPane();
        contentPane.add(panel);
        // Executes and builds the form Settings
        pack();
    }

    public static void main(String[] args) {
        MainApp app=new MainApp();
        // Allows the form to close
        app.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // Displays the form
        app.setVisible(true); }}Copy the code

The 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 graphics, 15 in a row, i.e. 450 pixels, the default size of the form
    private static final int SIZE = 30;

    // Set the maze map
    private static final byte FLOOR = 0;// 0 indicates the aisle floor
    private static final byte WALL = 1;// 1 indicates the 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}};// Set the image object to display
    private Image floorImage;
    private Image wallImage;
    private Image heroImage;
    private Image endImage;

    // Role coordinates
    private int x, y;

    // Separate up, down, left, and right button movements
    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(a) {
        // Set panel size
        setPreferredSize(new Dimension(WIDTH, HEIGHT));
        // Load the image
        loadImage();
        // Initialize the role coordinates
        this.x = 1;
        this.y = 1;
        // Set focus on the form and listen for keyboard events
        setFocusable(true);
        addKeyListener(this);
    }

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

    /** * draw the character (hero) **@paramG * / brush
    private void drawRole(Graphics g) {
        g.drawImage(heroImage, x * SIZE, y * SIZE, SIZE, SIZE, this);
    }

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

    /** * Draw a map based on the map information recorded in map[I][j] ** mark 0 for floor, mark 1 for 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:
                        // Mark 0 to draw the floor and load the image at the specified position
                        g.drawImage(floorImage, j * SIZE, i * SIZE, this);
                        break;
                    case 1:
                        // Draw the wall when marked 1
                        g.drawImage(wallImage, j * SIZE, i * SIZE, this);
                        break;
                    case 2:
                        // Mark 2 to draw the endpoint
                        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 the key code
        switch (keyCode) {
            // The left arrow key or the 'A' key can be moved left
            case KeyEvent.VK_LEFT:
                move(LEFT);
                break;
            case KeyEvent.VK_A:
                move(LEFT);
                break;
            // The right arrow key or the 'D' key can be moved right
            case KeyEvent.VK_RIGHT:
                move(RIGHT);
                break;
            case KeyEvent.VK_D:
                move(RIGHT);
                break;
            // Up arrow key or 'W' key, can be moved up
            case KeyEvent.VK_UP:
                move(UP);
                break;
            case KeyEvent.VK_W:
                move(UP);
                break;
            // Down arrow key or 'S' key, can be moved down
            case KeyEvent.VK_DOWN:
                move(DOWN);
                break;
            case KeyEvent.VK_S:
                move(DOWN);
                break;
            default:
                break;
        }
        // Redraw the form image
        repaint();
        if (isFinish(x, y)) {
            // Move to the exit
            JOptionPane.showMessageDialog(this."Congratulations on getting through!); }}@Override
    public void keyReleased(KeyEvent e) {}/** * Determines whether movement is allowed, if the coordinates passed in are not walls@param x
     * @param y
     * @returnReturns true if movement is allowed, false */ otherwise
    private boolean isAllowMove(int x, int y) {
        // Determine whether (x,y) is WALL or FLOOR
        // 1 indicates the wall, which cannot be moved; 0 indicates the floor, which can be moved
        if (x < COLUMN && y < ROW) {// The length of the array cannot be exceeded
            returnmap[y][x] ! =1;
        }
        return false;
    }

    /** * Move character **@paramEvent Is passed in the direction of movement, which can be LEFT, RIGHT, UP, or DOWN */
    private void move(int event) {
        switch (event) {
            case LEFT:/ / shift to the left
                if (isAllowMove(x - 1, y)) {// Determine if the left position is allowed to move (not the wall can move)
                    x--;
                }
                break;
            case RIGHT:/ / moves to the right
                if (isAllowMove(x + 1, y)) {
                    x++;
                }
                break;
            case UP:/ / 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 determine whether the destination is reached **@param x
     * @param y
     * @return* /
    private boolean isFinish(int x, int y) {
        // 2 represents the endpoint image
        Map [y][x] map[x][y]
        returnmap[y][x] == END; }}Copy the code

conclusion

Through the “Simple Maze” game implementation, let me have a further understanding of swing related knowledge, the Language of Java has a more profound 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

Can pay attention to the blogger, private chat blogger access