Hello. I'm in the process of writing a console version of the classic Snake game and I need a little help.
Currently, I have a board (represented as a 2-D array), a snake head (represented by a '^', 'v' '<' or '>' depending on the direction the snake is traveling), and food (represented by 'X'). The user inputs 'f' to move the snake forward, 'l' to rotate the head of the snake to the left, and 'r' to rotate the head to the right. Each movement costs a unit of energy. Eating the food restores energy by 20 units. Once the energy runs out, the program ends.
When the head of the snake is pointing to the right ('>') or pointing down ('v') and the user tries to move forward ('f'), the program bugs out in a very strange way. However, when the head is pointing to the left ('<') and up ('^'), the snake moves perfectly.
Is it too vague a hint to say that the fact that it works with up or left means something?
When you move the snake right or down, you find it again later in the loop ( and again and again and again ).
I put break; at line 221 and this solved it. The rotation functions are buggy, maybe has to do with the same thing.
I would say your snake class is too bulky. Think about having a board class and a food class. Then the you can have something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// code is missing, I think the names of the functions are clear enough though
Board::Draw_Board(const Snake& snake)
int snake_x = snake.get_x();
int snake_y = snake.get_y();
for ( /* nested loop to draw the board */ )
if ( i == snake_x && j == snake_y )
snake.draw(); // writes a character depending upon it's own direction
cout << ' ';
As a side. Whenever I see myself writing a whole bunch of if statements, I think something is wrong with my approach.
For example, a rotate could be something like this:
The bug from moving right or down comes from how you look for the head of the snake, you go across and down the array, when you update it's movement you move it (for this example to the right), and the next place you look after updating it's position because you don't stop looking for the snake is to the right which it finds again and will perform the move right command again all the way till it's out of the screen and cause your issue. You can fix it by returning from the function after you find and update the head.