Character Game – Snake!

Hits: 0

The last time I used construct2 to make a game similar to jerking off, this time I used C language to write a simple [command line] window game – Snake.

Compared with construct2 of [object-oriented] programming, it is naturally more difficult to write in procedural C language.

Consider the complexity of the program. I decided to first analyze the code required by the snake program in a top-down approach.

learning record

Complex programs should be broken down into small problems as much as possible

  1. Main program
    If the game is still running,
    print the map ,
    enter the control command
    to make the snake move and
    print the map
    , otherwise
    let the game end.

  2. Print the game interface
    We store the entire game map (including walls, open spaces, snakes and food) in a two-dimensional array. Then print it line by line. When the data in the array is constantly updated and we keep clearing the screen and printing out the map, it can make people’s eyes think it is a continuous animation picture.

Learning Difficulty Records:

When printing a map, it prints (Y,X) instead of the familiar (X,Y) coordinates.
The operation of clearing the screen.

  1. Control the movement of the snake
    We use “WSAD” on the keyboard to correspond to the “up, down, left and right” of the snake’s moving direction.

Then, before the snake walks, determine what the snake’s next step is. If it is a wall or its own body, let the snake die, and if it is food, let the snake grow a section.

  1. Place food
    We use a random function to generate the coordinates of the food. If there is an object on the new coordinates, it will be regenerated

Learning Difficulty Records

Control the growth of the snake and the random generation of food

smart snake

But such a snake can’t move by itself, so we have to use the kbhit function. This function checks for keyboard input but does not prevent the weile loop from continuing so the snake can move.

In addition, we can also write an intelligent algorithm that makes the snake run automatically.
Let the snake decide which of the four directions is feasible and the fastest to reach the food.

learning difficulties

Non-blocking input control
Snake ‘s intelligent judgment

Let’s put a moving picture to see the effect.

Leave a Reply

Your email address will not be published.