The snake is controlled with the four arrow keys. Key events are captured by the turtle screen listener and routed to one of four direction functions.
Key bindings
| Key | Function called | Effect |
|---|
↑ Up | arriba() | Sets direction to 'up' |
↓ Down | abajo() | Sets direction to 'down' |
→ Right | derecha() | Sets direction to 'right' |
← Left | izquierda() | Sets direction to 'left' |
Registering handlers
screen.listen() tells the turtle window to start capturing keyboard events. Each handler is then bound to a key with screen.onkeypress():
screen.listen()
screen.onkeypress(arriba, "Up")
screen.onkeypress(abajo, "Down")
screen.onkeypress(derecha, "Right")
screen.onkeypress(izquierda, "Left")
Direction state
The current direction is stored directly on the serpiente turtle object as a string attribute:
serpiente.direction = 'stop'
Possible values are 'up', 'down', 'left', 'right', and 'stop'. The snake starts with direction = 'stop' and does not move until the player presses a key.
Direction functions
Each function guards against reversing direction. A snake moving upward cannot immediately go downward — doing so would cause the head to collide with its own body in the next tick. Each function checks the opposite direction before updating state:
def arriba():
if serpiente.direction != 'down':
serpiente.direction = 'up'
def abajo():
if serpiente.direction != 'up':
serpiente.direction = 'down'
def derecha():
if serpiente.direction != 'left':
serpiente.direction = 'right'
def izquierda():
if serpiente.direction != 'right':
serpiente.direction = 'left'
The 'stop' direction is never blocked by any guard, so any arrow key press from the initial state will start the snake moving.
Movement execution
The direction functions only update the direction attribute — they do not move the snake themselves. Actual movement happens in movimiento(), which is called once per game loop iteration:
def movimiento():
if serpiente.direction == 'up':
y = serpiente.ycor()
serpiente.sety(y + 20)
if serpiente.direction == 'down':
y = serpiente.ycor()
serpiente.sety(y - 20)
if serpiente.direction == 'right':
x = serpiente.xcor()
serpiente.setx(x + 20)
if serpiente.direction == 'left':
x = serpiente.xcor()
serpiente.setx(x - 20)
The snake moves in 20-pixel steps, which matches the size of each body segment square, keeping the grid-aligned movement clean.