JavaDay3 - Snake game

Posted by worldcomingtoanend on Fri, 14 Jan 2022 02:24:31 +0100

According to the basic learning some time ago, I knocked out the code according to the greedy Snake game taught step by step according to the crazy God. Write a blog to record your learning experience.
The game interface looks like this:

1. First draw a JFrame window and set the properties of the window.

JFrame frame=new JFrame("Snake games");
        frame.setBounds(10,10,900,720);//Set the size of the interface
        frame.setResizable(false);//The window size cannot be changed
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);//Click x to close the game
        frame.setVisible(true);//Set window visible

2. Add a panel to use as a game area

frame.add(new GamePanel());

3. This game uses a lot of materials. Now you need to import the materials into the project
3.1 create a statistics package in the src directory to store our picture materials

3.2 reference materials and create a new Data class to store external Data
We first need a static path public static URL upurl = data class. getResource("/statics/up.png");
Secondly, we need to set this image as the icon public static ImageIcon up=new ImageIcon(upURL); (other picture materials are also written in this way)
4. Now we're going to start drawing a static game interface
First, we need a brush. We need to draw in JPanel. We need to inherit JPanel and implement a protected void paintComponent(Graphics g) {method, so that we can get the brush with the name of G. Set a background this in this method setBackground(Color.WHITE );// Set the background color; Draw a game area g. fillRect (25,75850600)// Draw the game area;
5. Step 4 has finished the background board of the game. In this step, we need to deal with snakes, food and game points.
Snake: snake is mainly composed of head and body. We set an int [] snake X and snake y to represent snake. Snake head is snake x [0], snake y [0]; Snake god starts with the array subscript 1. First, we draw a static snake to understand the movement of the snake, and use our material. Data.right.paintIcon(this,g,snakeX[0],snakeY[0]); This code means that if the snake head is to the right, the material specified by the right URL in the data class is placed as the snake head. Data.body.paintIcon(this,g,snakeX[1],snakeY[1]); The meaning of this code is to use the material specified by the URL of the body in the first section of the body position data class as the snake body. The snake position needs to be initialized:
length=3; snakeX[0]=100;snakeY[0]=100;// Head coordinate sneakex [1] = 75; snakeY[1]=100;// The first body coordinate sneakex [2] = 50; snakeY[2]=100;// Second body coordinates
There is also an initialization of snake head orientation: fx="R";
Food: the key to food is random appearance. Set food coordinates foodX and foodY. Randomly display food with a random class: Random food=new Random()// Random function; You need to initialize the food location: foodX = 25 + 25 * food nextInt(34); foodY=75+25*food. nextInt(24);
Draw food: data food. paintIcon(this,g,foodx,foody);
Draw integral: g.setColor(Color.BLACK); g.setFont(new Font("Microsoft YaHei", Font.BOLD,18)); g.drawString("length:" + length,350,35); g.drawString("integral:" + score,550,35);
6. Here we have finished a static snake, food and integral. Now we need to make a dynamic picture:
6.1 we need to control the start. We use the space bar to indicate the start and pause. First, we need to implement an interface: KeyListener implements the methods in it. For the three methods, we only need to use the keyPressed(KeyEvent e) {} method, which means to press the key but not release - to obtain which key is pressed on the keyboard. We need the space bar to judge, so the code is as follows:

	isStart=false;//Set to not started
 	int keyCode= e.getKeyCode();
    if(keyCode==e.VK_SPACE){//Determine whether to press space
        isStart= !isStart;//Change game status
        repaint();//Refresh interface

We have finished setting since the beginning of the game. Now we need to bind this event to our constructor:

 public GamePanel(){
        //Get the listening event of the keyboard
        this.setFocusable(true); //Get focus event
        this.addKeyListener(this); //Keyboard listening events

You need a hint to start the game:

//Game tip: start
        if (isStart==false){
            //Draw a text, String
            g.setFont(new Font("Microsoft YaHei ",Font.BOLD,40));
            g.drawString("Press the space to start the game",300,300);

Now we need to set a timer to make the snake move: timer Timer timer=new Timer(100, this)// timer
The event bound by this timer needs to implement the ActionListener interface and override the actionPerformed(ActionEvent e) {} method
We need to judge whether the game starts or not, because we initialize the snake's head to the right, so the snake moves to the right at the beginning

if (isStart){
            //Shift right
            for (int i = length - 1; i >0; i--) {

Now we need to control the snake through the up, down, left and right of the keyboard. First, we need to obtain the keyboard input:

        }else if(keyCode==KeyEvent.VK_LEFT){
        }else if(keyCode==KeyEvent.VK_UP){
        }else if(keyCode==KeyEvent.VK_DOWN){

Then move:

//Move the head by controlling the direction
            if(fx.equals("R")) {
                snakeX[0] = snakeX[0] + 25;

            }else if(fx.equals("L")) {
                snakeX[0] = snakeX[0] - 25;

            }else if(fx.equals("U")){

            }else if(fx.equals("D")){


We also need to make a boundary determination:

			if(fx.equals("R")) {
                snakeX[0] = snakeX[0] + 25;//Control Snake Movement
                if (snakeX[0] > 850) { snakeX[0] = 25;}//Boundary judgment
            }else if(fx.equals("L")) {
                snakeX[0] = snakeX[0] - 25;
                if (snakeX[0] < 25) { snakeX[0] = 850;}
            }else if(fx.equals("U")){
                if (snakeY[0]<75){ snakeY[0] = 650;}
            }else if(fx.equals("D")){
                if(snakeY[0]>650){ snakeY[0] = 75;}

At this point, the movement of our snake is basically over.
Now it is necessary to analyze the food eaten by the snake: if the coordinates of the snake head and the food coincide, we judge that the snake ate the food. Then the code is as follows:

			if (snakeX[0]==foodx &&snakeY[0]==foody){
                //Regenerate food

Then we need to let the timer start timer start(); (to be written in the constructor)
The score is linked to the length of the snake's body: after we judge that the snake has eaten food, we can increase the length + +; Integral + 10;

				//Length + 1
                score +=10;

Finally, don't forget to refresh the interface repaint();
So much is the process of playing the game. We also need to judge the end of the game. The game is over. We only write a snake head here. If you touch your body, the game is over:

			for (int i = 1; i < length; i++) {
                if (snakeX[i]==snakeX[0]&&snakeY[i]==snakeY[0]){

Then we should make corresponding changes at the beginning of the game. First, our isStart should be true; Isfail should also be true; ok, then we should rewrite the space to restart. We need to add that if the game fails, we can restart by pressing the space.

		if(keyCode==e.VK_SPACE){//Determine whether to press space
            if (isFail){//If the game fails, start all over again!
                isStart= !isStart;//Change game status
            repaint();//Refresh interface

Then we need to use g stroke to draw the failed interface

 //Game failure prompt
        if (isFail){
            //Draw a text, String
            g.setFont(new Font("Microsoft YaHei ",Font.BOLD,40));
            g.drawString("The game failed. Press the space to start again",200,300);

Of course, our isfail is initially false, which means that we have not failed

Topics: Java