pythonpython-3.xfunctionturtle-graphicspython-turtle

Turtle is not reacting to onkeypress


I am new in python so I took some time and watched some videos about how to make a simple "snake" game, I was doing everything that dude was saying, but when it came to the keyboard binding something went wrong and I can't move my turtle.. code:https://pastebin.com/GLSRNKLR

import turtle
import time

delay = 0.1
# Screen
wn = turtle.Screen()
wn.title("Snake Game By AniPita")
wn.bgcolor('black')
wn.setup(600, 600)
wn.tracer(0)
# Snake Head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
head.penup()
head.goto(0, 0)
head.direction = "stop"


# Functions
def go_up():
    head.direction == "up"


def go_down():
    head.direction == "down"


def go_left():
    head.direction == "left"


def go_right():
    head.direction == "right"


def move():
    if head.direction == "up":
        y = head.ycor()
        head.sety(y + 10)
    if head.direction == "down":
        y = head.ycor()
        head.sety(y - 10)
    if head.direction == "left":
        x = head.xcor()
        head.setx(x - 10)
    if head.direction == "right":
        x = head.xcor()
        head.setx(x + 10)


# Keyboard Bindings
wn.onkeypress(go_up(), 'w')
wn.onkeypress(go_down(), 's')
wn.onkeypress(go_left(), 'a')
wn.onkeypress(go_right(), 'd')
wn.listen()
# Main Game
while True:
    wn.update()
    time.sleep(delay)
    move()

wn.mainloop()

Solution

  • You want to pass function references to the onkeypress function so it will call it on demand.

    Therefore, you need to drop the function calls e.g.:

    wn.onkeypress(go_up(), 'w')
    

    should be:

    wn.onkeypress(go_up, 'w')