Search code examples
pythonturtle-graphics

My program crashes after i hold the w key to move the turtle for too long in the turtle library


The code is as follows:

import turtle

width = 400
length = 300

wn = turtle.Screen()
wn.bgcolor("black")
wn.title("x")

drawer = turtle.Turtle()
drawer.speed(3)
drawer.begin_fill()
drawer.color("blue", "yellow")

def drawern():
    drawer.seth(90)
    drawer.fd(1)

def drawerw():
    drawer.seth(180)
    drawer.fd(1)

def drawers():
    drawer.seth(270)
    drawer.fd(1)

def drawere():
    drawer.seth(0)
    drawer.fd(1)

wn.onkeypress(drawern, "w")
wn.onkeypress(drawerw, "a")
wn.onkeypress(drawers, "s")
wn.onkeypress(drawere, "d")

wn.listen()

wn.mainloop()

It gives a stack overflow error. Does anyone know why this issue persists? It doesn't happen when i let go of it once in a while.


Solution

  • I believe the stack overflow error is due to repeated assigning of angle to the stack. To prevent this, you can introduce a debounce. We will name our debounce as move. A debounce, in simple terms, is fail-safe to prevent an event for triggering again and again while keeping the rest of the code running.

    Define the variable in global space:

    move = False
    

    As for the function:

    def drawern():
        global move #To let the function know the variable is from global scope
    
        if not move: #The key is pressed first time
            drawer.seth(90)
            move = True #Sets our debounce to True, it will not activate until the key is released
            
        drawer.fd(1)
    
    wn.onkeypress(drawern, "w")
    

    We need to have another function with an event to reset our debounce:

    def reset_db():
        global move
        move = False #Resets the debounce, referencing the key has been released
    
    wn.onkeyrelease(reset_db, "w") #Connects the event
    

    I have demonstrated for w key here only. You can duplicate it for the rest of the keys too.