In this section, we will discuss the following items.
- Techniques to change direction of the snake based on user input.
- Techniques to calculate the snake's next position.
- Techniques to check for snake collision with window and its body.
Snake direction and food
We are using the gotoxy(int x, int y) function to move the snake on the screen. The top left corner of the PC window starts at (0,0). The right side of the screen is positive x-axis, and the bottom of the screen is positive y-axis. However, we can represent the direction of snake in all four directions by positive and negative axes (-x, 0), (x, 0), (0, -y), and (0, y). For the left arrow key, set direction as negative x-axis (-x,0), for the right arrow key set direction as positive x-axis (x,0), for the up arrow key set direction as negative y-axis (-y,0), and for the down arrow key set direction as positive y-axis (y,0). When the direction is changed, the snake will move perpendicular to current position, so we don't have to use both x, and y coordinates values. The coordinates system of the PC window is shown in the image below.