Home  >  Article  >  Java  >  How to implement the Snake War mini game in Java

How to implement the Snake War mini game in Java

WBOY
WBOYforward
2023-04-26 08:55:061632browse

1. Development environment and game display

The design and experiment process of Snake War needs to be carried out in the Window 10 system, and the development tool IntelliJ IDEA Community Edition 2020.3.2 (jdk- 15) Complete code writing, compilation, debugging, testing, etc. The components required by the program, such as the snake's head, body and background images, are all produced using the image software Adobe Photoshop 2020.

1.1 Game main interface

How to implement the Snake War mini game in Java

1.2 Mobile interface

How to implement the Snake War mini game in Java

##1.3 Reward interface

1. The game reaches 50 points:

How to implement the Snake War mini game in Java

2. The game reaches 100 points:

How to implement the Snake War mini game in Java

1.4 F acceleration function interface

When F is pressed, the speed increases to 100.

How to implement the Snake War mini game in Java

1.5 Death interface

How to implement the Snake War mini game in Java

2. Requirements analysis

The Snake game is a small Puzzle games can be used in people's daily leisure, entertainment and other scenarios. This game design involves knowledge of one-dimensional arrays, common components in Swing, event processing in GUI (event listeners, keyboard listeners), class encapsulation and inheritance, static variables, packaging classes, random numbers, etc.

The specific requirements are summarized as follows:

1. The initialization interface is 800×800 in size, and the game interface should be kept in the center of the screen, and the window should have the word "Snake";

2. The game interface should have necessary prompt text to prompt the game score and the current speed of the snake. The start interface should have operation prompt text (tap the space game to start/pause the game, hold down F to accelerate), and the text color should be beautiful;

3. Initialize the position of the snake in the program (near the left side of the panel ), the direction of the snake (default is to the right), the length of the snake (default is 3), and initializes the position of the food;

4. Implementation of the start and pause of the game: control the start and pause of the game through the space bar Pause;

5. Realization of the snake movement function: Use W, S, A, D or ↑, ↓, ←, → to control the movement direction of the snake as up, down, left, and right. Game;

6. When the snake head touches the periphery of the activity: When the snake head touches the rightmost (left) end of the interface, it will appear from the symmetrical left (right) end, and so on, when the snake head touches the uppermost (lower) end of the interface Then it appears from the lower (upper) end of the symmetry;

7. Realization of the snake's function of eating food: During the game, when the snake's head touches the food, it eats food. At this time, the length of the snake should be increased by 1, the speed should be increased by 10, the score should be increased by 10, and the position of the food is refreshed (random position);

8. Implementation of the snake acceleration function: when pressing and holding the "F" key , the snake accelerates and the speed value reaches 100; when the "F" key is released, the snake returns to the default speed of 10;

9. Snake's death determination: When the snake's head touches the snake's body, the snake dies. , the game is over, and the interface prompts near the center: "Your little snake has died, press space to start again!";

10. Implementation of the game's reward mechanism: When the score is 10, the game prompts "Good !"; when the score is 50, the game prompts "Good!!!"; when the score is 100, the game prompts "Perfect!!!"; when the score reaches 200, the game prompts "Unstoppable" !!!"; the above prompt words are all located on the snake head;

The basic operation table is as follows:

How to implement the Snake War mini game in Java

3. System design

3.1 Overall system functional design

This Snake program generally includes Snake’s movement function, Snake’s active acceleration function, game rule judgment function, and main interface control function. , the greedy snake eats food function. Among them, the movement function of the snake includes key control of the movement direction and the automatic movement of the snake; the game rule judgment function includes the snake's death judgment, game start and pause judgment, and out-of-bounds rules; the main interface control function includes the snake's initialization and Initialization of food; the functions of a greedy snake eating food include snake body growth, snake speed increase, points increase and food refresh position. The specific functional structure diagram is as follows:

How to implement the Snake War mini game in Java

3.2 Overall system process design

When entering the Snake program, first determine whether the space bar is pressed. If the space bar is pressed, the game starts. After the game starts, it is determined whether there is a key input. If there is a key input, the snake's moving direction is changed or accelerated according to the key settings; if there is no key operation, the snake continues to move in the original direction. During the snake's movement, it is judged whether the snake has eaten food. If it eats food, the game score will be increased by 10, and the snake's moving speed will also increase accordingly. Whether the snake has eaten food or not, it will be judged whether the snake dies. If it dies, the game ends; if If the snake is not dead, it will continue to judge whether there is a space input. If there is a space input, the game will be paused. Otherwise, it will continue to judge the keys, change the snake's motion state according to the keys, and continue the game until the snake dies and the game ends.

How to implement the Snake War mini game in Java

4. Functional design

4.1 Snake movement and acceleration function design

Snake’s movement function mainly depends on selection Statements and keyboard monitors are used to implement the game. Use W, S, A, D or ↑, ↓, ←, → to control the movement direction of the snake to up, down, left, and right to play the game. When the F key is pressed, the snake accelerates.

How to implement the Snake War mini game in Java

4.2 The design of greedy snake’s food-eating acceleration and death determination functions

In the process of greedy snake’s food-eating and death determination, the following are used Parameter:

  • A parameter of the Timer class: time of type int. The timer.setDelay(time) method is called in the program to change the parameters of the timer (the smaller the time, the faster the snake moves) ;

  • Parameters to record whether the snake is dead or not: isDied of boolean type (true means the snake dies, false means the snake lives), the default is false;

  • The length of the snake: length of type int (initially 3);

  • Integral parameter: score of type int (initially 0), each time it is eaten is controlled through a loop in the program Food adds 10 points;

  • Coordinates of the snake head: snakeX[0] and snakeY[0] of type int, which store the horizontal and vertical coordinates of the snake head respectively;

  • Coordinates of the snake body: snakeX[i] and snakeY[i] of type int[], which store the horizontal and vertical coordinates (i≠0) of each section of the snake body respectively;

  • Food coordinates: int type foodX, foodY, store the horizontal and vertical coordinates of food respectively. foodX and foodY are random numbers generated using the nextInt() method in the Random class, so the coordinates of the food are random.

I won’t go into details when using the above parameters below.

4.2.1 The design of the greedy snake’s food-eating acceleration function

When the coordinates of the snake head snakeX[0] and snakeY[0] are equal to the coordinates of foodX and foodY respectively, the score is Add 10, the length of the snake body is increased by 1, and the Timer parameter time is decreased by 10, thereby completing the extra points after the snake eats food, lengthening the snake body, and accelerating the function. The process design diagram of this function is as follows:

How to implement the Snake War mini game in Java

4.2.2 Design of Snake Death Determination Function

When a greedy snake eats itself, the snake Death, that is, when the snake head coordinates snakeX[0] and snakeY[0] are equal to the snake body coordinates snakeX[i] and snakeY[i] respectively, the snake dies. At this time isDied=! isDied.

How to implement the Snake War mini game in Java

4.3 Design of Snake’s active acceleration function

The active acceleration function of Snake is to hold down the F key during the game, and the snake will move The speed increases. If you press and release it, the snake's speed will return to the default value. This is mainly achieved through the keyboard listener in the GUI. Two methods of the keyboard listener are implemented, keyPressed() and keyReleased() respectively monitor the operation of pressing the F key and releasing the F key. Secondly, the parameter time is used. The value of time is changed in the program by calling the timer.setDelay(time) method (timer is an object of the Timer class) to change the frequency of the timer, thereby achieving the effect of speeding up the snake.

How to implement the Snake War mini game in Java

4.4 Design of the Snake Reward Mechanism Function

The Snake Reward Mechanism function mainly uses the selection structure and the paintComponent(Graphics g) method The brush tool is used to achieve this. When the game reaches a certain score, the program will call the g.drawString("XXX", snakeX[0], snakeY[0]) method in the brush tool to draw prompt text at the snake head position.

How to implement the Snake War mini game in Java

5. Project structure and project implementation

5.1 Project structure and relationship between classes

How to implement the Snake War mini game in Java

How to implement the Snake War mini game in Java

5.2 Complete project source code

5.2.1 Images class

This class is a static class, which mainly stores the picture objects of the Snake component.

package snakegame;

import javax.swing.*;
import java.net.URL;

//Images类用于封装图片路径以及获取图片(使用静态对象便于用类名直接访问)
public class Images {
    //将图片的路径封装成一个对象
    public static URL bodyURL=Images.class.getResource("/snake_images/body.jpg");
    public static URL backURL=Images.class.getResource("/snake_images/back.jpg");
    public static URL snakeDownURL=Images.class.getResource("/snake_images/snakeDown.jpg");
    public static URL snakeLeftURL=Images.class.getResource("/snake_images/snakeLeft.jpg");
    public static URL snakeRightURL=Images.class.getResource("/snake_images/snakeRight.jpg");
    public static URL snakeUpURL=Images.class.getResource("/snake_images/snakeUp.png");
    public static URL foodURL=Images.class.getResource("/snake_images/food.jpg");
    //将图片封装为程序中的对象
    public static ImageIcon bodyImg=new ImageIcon(bodyURL);
    public static ImageIcon backImg=new ImageIcon(backURL);
    public static ImageIcon snakeDownImg=new ImageIcon(snakeDownURL);
    public static ImageIcon snakeUpImg=new ImageIcon(snakeUpURL);
    public static ImageIcon snakeRightImg=new ImageIcon(snakeRightURL);
    public static ImageIcon snakeLeftImg=new ImageIcon(snakeLeftURL);
    public static ImageIcon foodImg=new ImageIcon(foodURL);
}

5.2.2 HighestScore

This class implements the highest score function in history.

package snakegame;

import org.w3c.dom.Text;

import java.io.*;

//该类用于给游戏添加历史最高分功能
public class HighestScore {
    static int score = 0;//最高分的存储

    public void highest() throws IOException {
        //得分为最高分时存储
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(String.valueOf(Text.class.getResourceAsStream("贪吃蛇大作战/score.txt"))));
        if (GamePanel.score > score) {
            score = GamePanel.score;
            String s1 = String.valueOf(score);
            bos.write(s1.getBytes());
        }
        bos.close();
    }

    //用于游戏开始时从文件读取最高分的值
    public void readHighest() throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(String.valueOf(Text.class.getResourceAsStream("贪吃蛇大作战/score.txt"))));
        byte[] bys = new byte[1024];
        int len;
        while ((len = bis.read(bys)) != -1) {
            System.out.print(new String(bys, 0, len));//测试用
            String s2 = new String(bys, 0, len);
            score = Integer.valueOf(s2);
        }
        bis.close();
    }
}

5.2.3 GamePanel class

This class is used to draw the Snake game panel and implement specific logic functions of the game.

package snakegame;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.IOException;
import java.util.Random;

//贪吃蛇游戏面板的绘制
public class GamePanel extends JPanel {
    Timer timer;
    int time=100;
    static int score;//记录游戏分数
    //蛇属性部分
    boolean isDied;
    int length;//设置蛇长
    String direction;//蛇头朝向
    //分别储存蛇身的X,Y坐标
    int[] snakeX=new int[300];
    int[] snakeY=new int[300];
    //判断游戏是否开始
    boolean isStart=false;
    int foodX,foodY;//食物的X,Y坐标
    //贪吃蛇初始化方法
    public void init(){
        length=3;
        snakeX[0]=175;
        snakeY[0]=275;
        snakeX[1]=150;
        snakeY[1]=275;
        snakeX[2]=125;
        snakeY[2]=275;
        foodX=300;
        foodY=400;
        score=0;
        isDied=false;//蛇默认状态为活着
        direction="R";//U,D,L,R分别表示蛇头朝向上,下,左,右
    }

    //构造方法
    public GamePanel() throws IOException {
        init();

        if(GamePanel.score>HighestScore.score){
            new HighestScore().highest();
        }
        //焦点定位到当前面板
        this.setFocusable(true);
        //监听器的实现部分
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                super.keyPressed(e);
                int keyCode = e.getKeyCode();
                //按下空格以开始游戏,以及方向键的控制
                if (keyCode == KeyEvent.VK_SPACE) {
                    if(isDied){
                        init();
                    }else {
                        isStart = !isStart;
                        repaint();//重绘
                    }
                } else if (keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_W) {
                    direction = "U";
                } else if (keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_S) {
                    direction = "D";
                } else if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_A) {
                    direction = "L";
                } else if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_D) {
                    direction = "R";
                }
            }
        });
        //贪吃蛇加速功能的实现
        this.addKeyListener(new KeyAdapter() {
            @Override
            public void keyPressed(KeyEvent e) {
                int keyCode=e.getKeyCode();
                if(keyCode==KeyEvent.VK_F){
                    time=10;
                    timer.setDelay(time);//按下F时加速
                }
            }

            @Override
            public void keyReleased(KeyEvent e) {
                int keyCode=e.getKeyCode();
                if(keyCode==KeyEvent.VK_F){
                    time=100;
                    timer.setDelay(time);//松开F键减速恢复默认速度
                }
            }
        });
        //对定时器进行初始化,并实现监听器
            timer = new Timer(time, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    //当游戏处于开始状态且蛇活着时蛇活动,且后一节身子到前一节身子的位置上(每一节身子为25乘25像素)
                    if (isStart && isDied == false) {
                        //蛇身运动部分
                        for (int i = length - 1; i > 0; i--) {
                            snakeX[i] = snakeX[i - 1];
                            snakeY[i] = snakeY[i - 1];
                        }
                        //蛇头运动部分
                        if ("D".equals(direction)) {
                            snakeY[0] += 25;
                        }
                        if ("U".equals(direction)) {
                            snakeY[0] -= 25;
                        }
                        if ("L".equals(direction)) {
                            snakeX[0] -= 25;
                        }
                        if ("R".equals(direction)) {
                            snakeX[0] += 25;
                        }
                        //防止超出边界
                        if (snakeX[0] > 750) {
                            snakeX[0] = 25;
                        }
                        if (snakeX[0] < 25) {
                            snakeX[0] = 750;
                        }
                        if (snakeY[0] < 100) {
                            snakeY[0] = 725;
                        }
                        if (snakeY[0] > 725) {
                            snakeY[0] = 100;
                        }
                        //吃食物的动作,吃食物加10分且蛇身变长,蛇的速度提升10
                        if ((snakeX[0] == foodX && snakeY[0] == foodY)) {
                            length++;//蛇身长度加1
                            foodX = (new Random().nextInt(30) + 1) * 25;//随机生成X坐标[25,750]
                            foodY = (new Random().nextInt(26) + 4) * 25;//随机生成Y坐标[100,725]
                            score += 10;//吃一次食物积分加10
                            try {
                                new HighestScore().highest();
                            } catch (IOException ioException) {
                                ioException.printStackTrace();
                            }
                            if(time>10)
                                timer.setDelay(time-=10);//吃一次食物速度增加10
                        }
                        //蛇的死亡机制判定
                        for (int i = 1; i < length; i++) {
                            if (snakeX[0] == snakeX[i] && snakeY[0] == snakeY[i]) {
                                isDied = !isDied;
                            }
                        }
                        repaint();
                    }
                }
            });
            timer.start();//定时器启动
    }

    //绘制面板部分
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        //填充背景颜色
        this.setBackground(new Color(164, 219, 246));
        //绘制初始蛇头的图片(默认右方朝向)
        Images.backImg.paintIcon(this,g,10,10);
        //调整画笔的颜色并绘制一个矩形面板
        g.setColor(new Color(219,226,219));
        g.fillRect(10,70,770,685);
        //蛇头的绘制;上下左右不同情况
        if("L".equals(direction)){
            Images.snakeLeftImg.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        if("R".equals(direction)){
            Images.snakeRightImg.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        if("U".equals(direction)){
            Images.snakeUpImg.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        if("D".equals(direction)){
            Images.snakeDownImg.paintIcon(this,g,snakeX[0],snakeY[0]);
        }
        //蛇身的绘制
        for(int i=1;i

5.2.4 Start class

The overall layout of the page and the entrance of the program.

package snakegame;

import javax.swing.*;
import java.awt.*;
import java.io.IOException;

//贪吃蛇总体界面布局以及程序的主方法
public class Start {
    public static void main(String[] args) throws IOException {
        JFrame jf=new JFrame("贪吃蛇");
        //获取屏幕的大小,并使用数据使窗口位置居中
        int width= Toolkit.getDefaultToolkit().getScreenSize().width;
        int height= Toolkit.getDefaultToolkit().getScreenSize().height;
        jf.setBounds((width-800)/2,(height-800)/2,800,800);
        jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        jf.setResizable(false);//设置窗口大小不能更改
        //添加GamePanel面板
        GamePanel panel=new GamePanel();
        jf.add(panel);
        jf.setVisible(true);
    }
}

The above is the detailed content of How to implement the Snake War mini game in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact [email protected] delete