Code sharing of Snake Game realized by C language
This article mainly explains "C language to achieve gluttonous snake game code sharing", interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "C language to achieve gluttonous snake game code sharing" bar!
Gluttonous Snake is a very classic game, using C language to achieve is also a fun thing. After I finished writing this game, I put it in Zhihu, and the number of people who liked it was super large. I think you like it, on the one hand, because the writing is simple, everyone can understand it, and the scalability is still very strong.
I tried to talk about the three functions at the core of this code.
Menu ()
Setup ()
Draw ()
Menu is used to set up the menu, which we see as soon as we run it. Setup is used to set the parameters, we need to set the height and width, as well as the score, the location of the food. Draw means painting, that is, painting the whole picture.
There is also an enumerated type, which is used to set several states of the snake. I think this is also an idea of object-oriented programming, encapsulating the state of the snake into an enumerated type.
Typedef enum
{
STOP = 0
LEFT
RIGHT
UP
DOWN
} Direction
And
/ * judge the length of the gluttonous snake * /
Void logic ()
This function, this function should be the essence of the whole gluttonous snake, to understand how the code connects the snake. Used something ingenious.
Let's take a look at the key code here.
/ * write down the previous position * /
Int lastX = tailX [0]
Int lastY = tailY [0]
Int last2X, last2Y
/ * retrieve the current location * /
TailX [0] = x
TailY [0] = y
Int iTunes 0
/ * traverse the length of the whole snake to vacate the position of 0, and the position of the rest of the snake moves to the back space * /
For (iTunes 1; I