简体   繁体   中英

How to find where the snake tail is in a 2d array in the greedy snake game?

I am trying to code a greedy snake game in C++. I have a 2d array, and in this array there are some places set in some specific number, for example, grid[3][2] = 1; grid[3][3] = 2; grid[2][3] = 2; those places are stick together like a snake. And when the number is 1, it will show "@" in the grid as the head of the snake, when it is 2, it will show "*" as the body. So I am trying to keep the snake moving, for example, if I want the snake goes up until changes the direction. I just assign grid[2][2] as 1, and then assign grid[3][2] as 4, and the rest of places where are 2 become 3, too. And then reset those places where are 3 to 2; Like this:

void keep_moving_snake()
{
    //an example of going up
    for(int i = 0; i < 20; i++) {
        for(int j = 0; j < 20; j++) {
            if(grid[i][j] == 1) { //where the head is
                grid[i - 1][j] = 4;
                grid[i][j] = 3;
            }
            if(grid[i][j] == 2) {
                grid[i][j] = 3;
            }
        }
    }
    for(int i = 0; i < 20; i++) {
        for(int j = 0; j < 20; j++) {
            if(grid[i][j] == 4) { //set the new place as head
                grid[i][j] = 1;
            }
            if(grid[i][j] == 3) {
                grid[i][j] = 2;
            }
        }
    }
}

And I put some code like above into a loop, so the snake keep moving:

while(true) {
    keep_moving_snake();
    system("cls");
    show_grid();
    Sleep(500);
}

But I need to find where the snake tail is and set the number to 0. Or the snake will just get longer and longer. So how can I do to solve this? Thanks.

I recommend maintaining a Point variable for the head and tail. When you update the snake, update these variables. A lot faster than searching a matrix. The Point structure can be as simple as std::pair<int, int>

struct Point
{
  int row;
  int column;
};

Point snake_head;
Point snake_tail;

The snake's head can be accessed at board[snake_head.row][snake_head.column] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM