0

This code draws a line, but when you press (and hold) the space bar, it speeds up, when you release, it goes back to the original speed (kind of like slither.io).

import turtle 
speed = 1
def speed_up():
    global speed
    speed += 8
    return speed
def slow_down():
    global speed
    speed -= 8
    return speed
wn = turtle.Screen()


wn.listen()
wn.onkeypress(speed_up, "space")
wn.onkeyrelease(slow_down, "space")

RADIUS = 500
drone = turtle.Turtle()
for _ in range(1000):
    for __ in range(RADIUS // 10): 
        drone.speed(speed)
        print(speed)
        drone.forward(10)

turtle.mainloop()

However, the speed is really inconsistent, so in my terminal (when i run python app.py) the print statements look something like

9
9
9
9
9
1
9
9
9
1
1
9
9
9
1
9
9
9
1
9
9

Even though I'm pressing and holding the entire time.

wel
  • 234
  • 2
  • 11
  • What sort of application are you trying to make here? If you're trying to make a real-time game, the approach here is likely suboptimal, so this might be an [xy problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/233676#233676). You probably want to turn off `tracer()` and run your own update loop, like the technique shown in [How to bind several key presses together in turtle graphics?](https://stackoverflow.com/questions/47879608/how-to-bind-several-key-presses-together-in-turtle-graphics/70979967#70979967). – ggorlen Jan 14 '23 at 19:18
  • @ggorlen I just want to make an application where the turtle is going straight ahead and when i press the space bar, it speeds up, but when i release it, it goes back to the normal speed. Kinda like slither.io – wel Jan 15 '23 at 05:20

0 Answers0