I write a snake game in c using a 2d array. I use for head the symbol 'o' and for tail the symbol '*'. How i change the tail position in 2d array if i have a tail bigger than one star *. Because with one star it's ok.
void Movement(char grid[gridsize][gridsize]){
char move;
int i, j ;
bool check = true, tail = false;
cout << "Make Your move w/s/a/d " << endl;
cin >> move ;
for(i = 0; i < gridsize; i )
{
for(j = 0; j < gridsize; j )
{
if(grid[i][j] == 'o')
{
goto Theend;
}
}
}
Theend:
int ii, jj;
for(ii = 0; ii < gridsize; ii )
{
for(jj = 0; jj < gridsize; jj )
{
if(grid[ii][jj] == '*')
{
tail = true;
goto Thefinalend;
}
}
}
Thefinalend:
switch (move)
{
case 'w':
grid[i-1][j] = 'o';
break;
case 'a':
grid[i][j-1] = 'o';
break;
case 's':
grid[i 1][j] = 'o';
break;
case 'd':
grid[i][j 1] = 'o';
break;
default:
cout << "Not correct input " << endl;
break;
}
grid[i][j] = ' ';
AppleEat(grid, i, j);
if(tail == true)
Swaptail(grid, i, j);
}
void AppleEat(char grid[gridsize][gridsize], int ibefore, int jbefore)
{
int i, j;
for(i = 0; i < gridsize; i )
{
for(j = 0; j < gridsize; j )
{
if(grid[i][j] == 'o')
{
goto Theend;
}
}
}
Theend:
if(iA == i && jA == j){
RandomPlaceApple(grid);
grid[ibefore][jbefore] = '*';
}
}
void Swaptail(char grid[gridsize][gridsize], int ibefore , int jbefore )
{
for(int ii = 0; ii < gridsize; ii ){
for(int jj = 0; jj < gridsize; jj ){
if(grid[ii][jj] == '*')
{
swap(grid[ii][jj], grid[ibefore][jbefore]);
}
}
}
}
I want to make the snake tail move. I try to search for the farthest position of the tail '*' but that was not good idea.
CodePudding user response:
You will need to keep track of the tail positions in a separate data structure, such as a queue or a linked list, I don't think there is a more optimal approach.
For example, you could create a struct (or class, preference) to represent each segment of the tail, which contains the x and y coordinates of the segment. Then, in your Movement function, you could use a queue to keep track of the tail segments. When the snake eats an apple, you would enqueue a new tail segment onto the queue, and when the snake moves, you would dequeue the oldest tail segment from the queue and update its position in the 2D array.
Something like:
#include <queue>
struct TailSegment {
int x;
int y;
};
std::queue<TailSegment> tail;
...
if(tail == true)
MoveTail(grid);
...
Theend:
if(iA == i && jA == j){
RandomPlaceApple(grid);
tail.push({ibefore, jbefore});
}
...
void MoveTail(char grid[gridsize][gridsize])
{
TailSegment last = tail.front();
grid[last.x][last.y] = '*';
}