蛇头不动

Snake Head Isn't Moving

我在 Python 的 turtle 模块中编写了一个基本的蛇游戏,当我测试它时,我发现蛇头没有动。

代码如下:

导入模块:

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)

我测试了它,它起作用了,所以我移到了蛇头上:

# snake head

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

移动蛇头:

# 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
while True:
    win.update()
    move()
    time.sleep(delay)

和键盘绑定:

# keyboard binding

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

此外,我在 win.listen() 行中有一个错误,说“此代码无法访问”,如果有人知道我做错了什么,请告诉我。

它说代码无法访问的原因是因为键绑定内容(包括 window.listen)位于 while True: 循环之后。因为你没有办法退出循环,后面的代码永远不会 运行。如果没有任何键绑定,蛇将永远不会从 "stop" 方向改变。

您应该将主游戏循环移到代码的最后,这样其他所有内容都有机会 运行。