Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Directions | Building a Classic Snake Game
Building a Classic Snake Game
course content

Contenido del Curso

Building a Classic Snake Game

book
Directions

To manage and organize the various directions our snake can take, we utilize a constants in our code. Each direction is represented as a tuple containing the changes in the x and y coordinates:

Direction
Movement
Explanation
RIGHT
(1, 0)
Moves the snake one unit to the right.
LEFT
(-1, 0)
Moves the snake one unit to the left.
UP
(0, -1)
Moves the snake one unit upward.
DOWN
(0, 1)
Moves the snake one unit downward.

Changing Directions

We need to create separate functions and implement them to manage these directional changes. It's crucial to divide them into distinct functions for clearer and more understandable code.

  • change_direction_left(snake): this method changes the snake's direction to the left, but only if the previous direction was not right.

  • change_direction_right(snake): similarly, this method changes the direction to the right, barring the previous direction being left.

  • change_direction_up(snake): moves the snake upwards, preventing a sudden reversal if the previous direction was downward.

  • change_direction_down(snake): moves the snake downwards, ensuring it doesn't collide with its own body by immediately turning back

Note

The direction change methods ensure that the snake doesn't abruptly reverse its course, which could lead to collision and subsequently end the game. By restricting the direction changes based on the previous direction, we maintain smooth and logical movement.

Tarea
test

Swipe to show code editor

  • Implement four methods: change_direction_left(), change_direction_right(), change_direction_up(), and change_direction_down(). Each method will update the snake's current direction based on its previous direction to prevent the snake from reversing onto itself.

Mark tasks as Completed
Switch to desktopCambia al escritorio para practicar en el mundo realContinúe desde donde se encuentra utilizando una de las siguientes opciones
¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 1. Capítulo 6
AVAILABLE TO ULTIMATE ONLY
We're sorry to hear that something went wrong. What happened?
some-alt