Snake Game - movement function

Hello,

Let's say I have a snake: char snake[3]. How do I move the snake on a board[10][10]?

My attempt is not bending the snake when changing direction:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{
	switch (key)
	{
	case('w'):
		headX--;
		break;
	case('s'):
		headX++;
		break;
	case('a'):
		headY--;
		break;
	case('d'):
		headY++;
		break;
	}

	for (int i = 0; i < snake.size(); i++)
	{
		 area[headX][headY+i] = snake[i];
	}
}
Are you keeping track of what direction the snake is currently going? In your loop, it looks like the area just gets updated with the snake moving up (if I understand your code correctly).

You could try doing your switch like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
  switch (direction)
  {
    case 'w':
      goUp();
      break;
    case 'a':
      goLeft();
      break;
    case 's':
      goDown();
      break;
    case 'd':
      goRight();
      break;
    default:
      std::cout << "Invalid input" << std::endl;
      break;
  }


You should also always have a default for your switch statements just in case you get some input that doesn't match any of your case statements. The default case would just get called if none of the other cases are satisfied. And good job on remembering the break in each case, I see people forget those sometimes.
So, how would one of the functions look like? For example goUp()?

I think I should use a temporary variable to store the head position and update the rest of the body accordingly.
Does your snake wrap around? Meaning, if the snake hits the edge, does it start showing up on the other side?

You could store all the body positions (you need to) in a vector. For every spot except the head, make that position equal to the body position in front of it (so they all get pushed forward by one spot). For the head, do that last and just make its position go up by 1.

Could look something like this:
1
2
3
4
5
6
7
8
9
10
11
12
13
void goUp()
{
  current_direction = UP;
  
  //Start at the end of the snake
  //Make each snake body piece be at the position of the one before it ("Scoot" them up)
  //Just don't update the head here, since there's nothing to "scoot" it to
  for (int i = snake_body.size() - 1; i > 0; i--)
  {
    snake_body[i] = snake_body[i - 1]; //"Scoot" all the positions up
  }
  snake_body[0].y += 1; //HEAD.y = HEAD.y + 1
}
Topic archived. No new replies allowed.