Snake Head Isn't Moving

Viewed 115

I was coding a basic snake game in the turtle module in Python and when I tested it, I saw that the snake head wasn't moving.

here is the code:

import modules:

import turtle
import random
import time
delay=0.1

# Background

win = turtle.Screen()
win.title("snake")
win.bgcolor("black")
win.setup(width=800, height=800)
win.tracer(0)

I tested it and it worked so I moved onto the snake head:

# snake head

head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
head.penup()
head.goto(0, 50)
head.direction = "stop"

moving the snake head:

# snake movement

def move():

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

    if head.direction == "down":
        y = head.ycor()
        head.sety(y - 20)

    if head.direction == "right":
        x = head.xcor()
        head.setx(x + 20)

    if head.direction == "left":
        x = head.xcor()
        head.setx(x - 20)

# keyboard setting


def go_up():

    if head.direction != "down":
        head.direction = "up"


def go_down():

    if head.direction != "up":
        head.direction = "down"


def go_right():

    if head.direction != "left":
        head.direction = "right"


def go_left():
    if head.direction != "right":
        head.direction = "left"

Main game loop:

# main game loop
while True:
    win.update()
    move()
    time.sleep(delay)

And keyboard binding:

# keyboard binding

win.listen()
win.onkey(go_up, "w")
win.onkey(go_down, "s")
win.onkey(go_right, "d")
win.onkey(go_left, "a")

Also i have an error in the line win.listen() saying "This code is unreachable" if anybody knows what I did wrong please let me know.

1 Answers

The reason it says the code is unreachable is because the key binding stuff, including window.listen, comes after the while True: loop. Since you don’t have any way to exit the loop, the code after will never run. If there are not any key bindings, the snake will never change from the "stop" direction.

You should move the main game loop to the very end of your code, so everything else gets a chance to run.

Related