Lilia Georgieva
Lilia Georgieva

Reputation: 1

Python turtle moves up and right but not left and down

I am coding a snake game in Python.

I have from turtle import Screen, Turtle and I have the starting positions

STARTING_POSITIONS = [(0, 0), (-20, 0), (-40, 0)]
MOVE_DISTANCE = 20
UP = 90
DOWN = 270
LEFT = 180
RIGHT = 0

and then

screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")
screen.listen()

Up and right behave as expected but not left and down.

The snake does not respond to

for example, snake.speed(3), when I try to slow it down either.

Upvotes: 0

Views: 493

Answers (1)

Lecdi
Lecdi

Reputation: 2241

turtle.Turtle.up(), .left(), .right() and .down() don't do what you think they do. .up() and .down() put the pen up and down and don't affect direction and .left() and .right() don't immediately snap the turtle to a certain direction, they turn it by a specific angle which must be specified.

Instead of doing this you should use turtle.Turtle.setheading() to your constants, which would look like the following:

screen.onkey(lambda: snake.setheading(UP), "Up")
screen.onkey(lambda: snake.setheading(DOWN), "Down")
screen.onkey(lambda: snake.setheading(LEFT), "Left")
screen.onkey(lambda: snake.setheading(RIGHT), "Right")
screen.listen()

Note that this sets which way they are facing but does not move them in that direction. If you want to do that , create your own function for each direction and use that, so for left that would look like:

def move_left():
    snake.setheading(LEFT)
    snake.forward(5)

screen.onkey(move_left, "Left")
screen.listen()

Upvotes: 1

Related Questions