Skip to content

Placing Snake in C

An answer to this question on Stack Overflow.

Question

i am trying to do a basic snake game . I have a board char board[N][N]={{'\0'}}; And i want to place my snake who has to be first line with the head at 0;0 and the body at 0;1 and 0;2. To track the tail and the body (for later for moving the snake) i create a 2D array for the coordinates of the snake .

int coord_percent[2][N*N] = { -1 };
coord_percent [0][0] = 0;
coord_percent [1][0] = 0;
coord_percent [0][1] = 0;
coord_percent [1][1] = 1;
coord_percent [0][2] = 0;
coord_percent [1][2] = 2;
int  size_percent = 3;

So now im calling a function to place the snake :

void place_snake (char board[N][N],int coord_snake[2][N*N],int size_snake) {
    
    int i;
    board[coord_snake[0][0]][coord_snake[1][0]] = '%'; // the head will always be the first in the array_coord
    
    for (i=1 ; i<size_snake ; i++) {
        board[coord_snake[0][i]][coord_snake[1][i]] = '*';
        
    }
    
}

I dont know where is my mistake ... Thank you for your time :)

Answer

Using a 2D array for the snake coordinates isn't a good idea, since you'll have to traverse the entire 2D array in order to figure out where the snake is.

It is better to use a deque or circular queue to implement the snake.

Then your snake's body segments are arranged conceptually as:

C D E F G H I

To move the snake forward you unpaint the part of its body on the right (I) and add a part of the body on the left (B), to get:

B C D E F G H

In your code you will replace the capital letters by the 2D coordinates of the snake's body segments.