I am participating in the nuggets Community game creative submission Contest. For details, please see: Game Creative Submission Contest.

Design idea:

1. Create the JFrame form, set the page size, and create the body panel.

2. Draw a static snake, identifying its head and initial body

3. Add keyboard monitoring to control the movement direction of the snake head

4. Set the boundary of the main panel, set the size of the game interface box, and judge the end of the game

5. Determine whether to end the game. End the game when the snake head touches his body, and end the game when the snake head touches the edge of the drawing board

6. Calculate the score, each time the late food, random coordinates to generate a new food, at the same time the score plus one, after the end of the game score cleared zero

Overall development idea

Create and size the JFrame form and introduce the Canvas theme class

public static void main(String[] args) { JFrame jframe = new JFrame(); Jframe. setTitle(" Snake little game "); jframe.setBounds(300, 50, 650, 470); jframe.setResizable(false); jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); jframe.add(new GamePanel()); jframe.setVisible(true); }Copy the code

Create the image class ReadyImages to read the prepared static image information stored in the images package.

Create the main panel, and add the keyboard monitor class, control the steering of the snake head through the up and down keys, create the direction control, code is as follows:

public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_SPACE) { isstart = ! isstart; } else if (keyCode == KeyEvent.VK_LEFT) { action = "L"; } else if (keyCode == KeyEvent.VK_RIGHT) { action = "R"; } else if (keyCode == KeyEvent.VK_UP) { action = "U"; } else if (keyCode == KeyEvent.VK_DOWN) { action = "D"; }Copy the code

Initialize the gameplay in the palette body, create a snake object, randomly generate food locations, and add keyboard events to the canvas

    public void initGame() {
​
       
        snake = new Snake();
        keyListener = new GameKeyListener(snake.action,start);
​
​
        foodX = 25 + 25 * random.nextInt(24);  
        foodY = 75 + 25 * random.nextInt(14);
​
        this.setFocusable(true); 
        this.addKeyListener(keyListener);   
​
    }
Copy the code

Create the snake object, initialize the position, and control the position of the snake through the thread. Record the coordinate point position of the snake’s head and body through two arrays, add the head position to the array, and delete the element at the end, so that the snake moves, moves once per second.

public class Snake implements Runnable { public int snakeLength; public int[] snakeX = new int[600]; public int[] snakeY = new int[500]; public String action = "R"; public ImageIcon headimages = ReadyImages.headrightIcon; public Snake() { snakeLength = 3; snakeX[0] = 100; snakeY[0] = 100; snakeX[1] = 75; snakeY[1] = 100; snakeX[2] = 50; snakeY[2] = 100; } @Override public void run() { for (int i = snakeLength - 1; i > 0; i--) { snakeX[i] = snakeX[i - 1]; snakeY[i] = snakeY[i - 1]; } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); }}}Copy the code

Control the snake through the keyboard. When action= ‘U’ or action= ‘D’, change the coordinate of the snake head Y and change the picture even if the snake head goes up or down. When action= ‘L’ or action= ‘R’, change the coordinate of the snake head X and change the picture even if the snake head goes left or right. When the coordinates are greater than the length of the boundary, the game ends. Return true. Similarly, the game ends when the head of the snake touches its body when the x and y coordinates are already in the array

 public boolean border() {
​
        if (action == "L") {
​
            snakeX[0] = snakeX[0] - 25;
            if (snakeX[0] < 25) {
                return true;
            }
​
            headimages = ReadyImages.headleftIcon;
​
        } else if (action == "R") {
​
            snakeX[0] = snakeX[0] + 25;
            if (snakeX[0] > 600) {
                return true;
            }
​
            headimages = ReadyImages.headrightIcon;
​
        } else if (action == "U") {
​
            snakeY[0] = snakeY[0] - 25;
            if (snakeY[0] < 75) {
                return true;
            }
            headimages = ReadyImages.headupIcon;
​
        } else if (action == "D") {
​
            snakeY[0] = snakeY[0] + 25;
            if (snakeY[0] > 400) {
                return true;
            }
            headimages = ReadyImages.headdownIcon;
        }
        return false;
    }
Copy the code

Increased the movement of eating food. When the snake’s head overlaps with the food, the body length increases by 1.

public boolean eatfood(int foodx, int foody) {
​
    if (foodx == snakeX[0] && foody == snakeY[0]) {
​
        snakeLength++; 
        return true;
    }
​
    return false;
}
Copy the code

When the game starts, start the thread, and determine whether the snake touches the boundary, and the direction of the snake head, if the snake head touches the food, call the method of eating the transaction, and random position to generate the transaction. Return true, end the game, prompt, and clear the score.

if(start == true && dead == false) { snake.run(); dead = snake.border(); if (dead) { g.setColor(Color.BLACK); G. setfont (new Font(" Microsoft yahei ", Font.BOLD, 30)); G. rawString(" Game over, press spacebar to start ", 180, 250); grade = 0; } boolean eatting = snake.eatfood(foodX, foodY); if(eatting) { foodX = 25 + 25 * random.nextInt(24); foodY = 75 + 25 * random.nextInt(14); grade++; }}Copy the code

conclusion

Simple write down, is a simple application of JFrame and thread, excerpted part of the code, well, this article to introduce you here, feel helpful, leave a like or comment again go! Thanks ~ 💐