Just judge that the snake head coordinates coincide with the food coordinates, and then judge the direction of movement to determine where to add a section. The snake moves to the place where the food is covered, so the effect of eating the food need not be written. Use GetAsyncKeyState() function to read the keyboard input, and pay attention to the additional conditions to prevent the snake from turning around. The method is the same as the fourth step, just change "" into two spaces.īecause of the particularity of snake movement, only the head of snake needs to be treated. So before each movement, wipe off the snake. The reason is that although the attributes of the former node are assigned to the latter node, the node does not change. It's like the mouse cursor after the crash. When you write to the previous step, you will find that the snake is getting longer and longer. I used the method of moving the whole snake forward and dealing with the snake head separately, which is also convenient to control the direction in the future. It can be said that one goes to the tail of the snake and one goes to the head of the snake. I found that the snake's movement mode is not very complicated. I went to play snake eating game during the game. Then the initial generation of two or three sections is OK.Įstablish a for loop to traverse the whole snake, and copy the blank part as "" by using the strncpy() function. Define x and y variables as coordinate values, and use rand() function with remainder to get the desired range of coordinate values.
Generating random coordinates of snakesįirstly, random seed is planted and system time is used as seed. It should be noted that "" takes up two bytes, and many places need to be multiplied by two when writing coordinates.ģ. It might seem complicated at first but it is actually quite. Array stores snake's node number, XY coordinate, moving direction and other parameters. In order to do this, I decided to recreate the old Snake game from the Nokia phone using C++. The main disadvantages of arrays are limited capacity, the longest length needs to be defined first (as long as I set it long enough hhhh), and the address needs to be taken in many places (the "&" is knocked out N times). Print is to traverse the entire string with the for loop, and refresh with a certain frequency, you can achieve the effect of the game.Ĭonsidering that I haven't done anything with linked list and I'm not very skilled, I use array to do snake. Here I will not repeat the writing process, mainly talking about the logic of the most basic functions, and some functions that were less used before.ĭefine a two-dimensional string with "" and spaces to represent boundary, snake body, blank space, etc. The realization of the game is to modify and transform a two-dimensional array according to certain logic.