0

I'm trying to make a game but the movement is not working. It keeps registering the keypresses without the keys being pressed.

import turtle

player = turtle.Turtle()
root = turtle.Screen()

#variables
allowmovement = 1
#movement
def moveleft():
    player.setheading(180)
    player.forward(2)
    print("left")
def moveright():
    player.setheading(0)
    player.forward(2)
    print("right")
def jump():
    player.setheading(90)
    player.forward(2)
    print("jump")

root.listen()
#loop
while True:
    while allowmovement == 1:
        root.onkeypress(moveleft(), "a")
        root.onkeypress(moveright(), "d")
        root.onkeypress(jump(), " ")

output is:

up
left
right
up
left
right

This goes on forever.

I was expecting to be able to press "a" and the turtle moves left and when I press " " it moves up. Same with all of the other keys.

Instead, it kept running moveleft(), moveright(), and jump() repeatedly.

I am completely stumped and I don't even know where to start debugging this.

ggorlen
  • 44,755
  • 7
  • 76
  • 106
  • Remove the `()` after your funtions. You want to _pass the function object itself_ as the handler, not call it immediately and pass its return value of None as the handler. `root.onkeypress(moveleft, "a")`. Also, don't try to register the handlers in a `while` loop. Add them up front once. As far as being completely stumped, try [checking the docs](https://docs.python.org/3/library/turtle.html#turtle.onkeypress). They show exactly how to add a handler function as a callback. Googling your problem also led me to [this](https://stackoverflow.com/questions/48777798) dupe. – ggorlen Nov 05 '22 at 00:57
  • Does this answer your question? [Key event seems stuck using \`turtle.onkey(function(), "key")\`](https://stackoverflow.com/questions/48777798/key-event-seems-stuck-using-turtle-onkeyfunction-key) – ggorlen Nov 05 '22 at 01:00
  • no. it doesent. what im doing wont use mainloop because that only works for turtle things not other things. if i want it to be constantly running other code as well, mainloop is not going to work. also removing the () after the functions stopped it from triggering randomly but now the window is not responding. – DuckyPolice Nov 08 '22 at 20:33
  • The purpose of the linked answer is the parentheses, so it does help, because that portion of the problem is definitely wrong, and it's the exact same pattern as the link. As I mentioned already, you need to move your handlers outside of the `while` loop--your overall setup does not make sense for a realtime turtle app, so there are multiple issues beyond that you should consult any tutorial on event loops and key movement to resolve. I'm partial to [this setup](https://stackoverflow.com/questions/47879608/how-to-bind-several-key-presses-together-in-turtle-graphics/70979967#70979967). – ggorlen Nov 09 '22 at 01:03

0 Answers0