0
#imports
import turtle
import time

delay = 0.1

#design
window = turtle.Screen()
window.title("Snake Game by LZ")
window.bgcolor("#cce0ff")
window.setup(width=700, height=750)
window.tracer(0)

head = turtle.Turtle()
head.speed(0)
head.shape("circle")
head.color("black")
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 motion():
    if head.direction == "up":
        y = head.ycor()
        head.sety(y + 10)

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

#keyboard bindings
window.listen()
window.onkeypress(go_up, "Up")
window.onkeypress(go_down, "Down")
window.onkeypress(go_left, "Left")
window.onkeypress(go_right, "Right")

#main game loop
while True:
    window.update()

    motion()

    time.sleep(delay)

window.mainloop()

Here's my problem: I created a very simple Python program where if you press the → key, a black circle will move towards the right and if you press ↑ key, it will move upwards. Somehow, only the → is responding/functioning while the other three keys aren't.

My user-define functions (go_up, go_down, go_left, go_right) all seem alright, but I just don't understand why only go_right is working while the others aren't. Could anyone help me?

2
  • 1
    Your function motion() is defined 4 times. Commented Jan 22, 2021 at 13:35
  • Exactly, the namespace gets rewritten each time so only the last one actually holds that reference. Commented Jan 22, 2021 at 13:36

1 Answer 1

1

You redefine the motion() function every time you declare it. So when referring to it you only actually refer to the last one.

Try adding your conditions to 1 function as an if/else block

def motion():

    if head.direction == "up":
        y = head.ycor()
        head.sety(y + 10)

    elif head.direction == "down":
        y = head.ycor()
        head.sety(y - 10)
        
    elif head.direction == "left":
        x = head.xcor()
        head.setx(x - 10)
        
    elif head.direction == "right":
        x = head.xcor()
        head.setx(x + 10)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.