简体   繁体   English

在贪婪的蛇游戏中,如何找到蛇尾在二维数组中的位置?

[英]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++. 我正在尝试用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; 我有一个2d数组,在这个数组中有一些以特定数字设置的位置,例如grid [3] [2] = 1; grid[3][3] = 2; grid [3] [3] = 2; grid[2][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. 当数字为1时,将在网格中显示“ @”作为蛇的头,当数字为2时,其将显示“ *”作为主体。 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. 我只是将grid [2] [2]分配为1,然后将grid [3] [2]分配为4,其余的2的地方也变为3。 And then reset those places where are 3 to 2; 然后重置那些3到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. 但是我需要找到蛇尾在哪里并将数字设置为0。否则蛇会变得越来越长。 So how can I do to solve this? 那么我该如何解决呢? Thanks. 谢谢。

I recommend maintaining a Point variable for the head and tail. 我建议为头部和尾部维护一个Point变量。 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> Point结构可以像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] . 可以通过board[snake_head.row][snake_head.column]访问蛇的头部。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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