所以我一直在尝试遵循本指南,了解如何使用Turtle图形和Python创建贪吃蛇游戏:https://www.youtube.com/watch?v=rrOqlfMujqQ&ab_channel=ChristianThompson基本上,我无法让"蛇"真正移动。我看到一个灰色的屏幕,有蛇,它被卡住了。(点击"w/s/d/a"时应该移动(。
我收到的错误:
raise Terminator
turtle.Terminator
我写的程序是:
import turtle
import time
delay = 0.1
# Set up Screen
wn = turtle.Screen()
wn.title("Snake Game By Aviv Sabati")
wn.bgcolor("gray")
wn.setup(width=600, height=600)
wn.tracer(0)
# Snake Head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("green")
head.penup()
head.goto(0,0)
head.direction = "stop"
# functions
def go_up():
head.directin = "up"
def go_down():
head.directin = "down"
def go_right():
head.directin = "left"
def go_left():
head.directin = "right"
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 == "left":
x = head.xcor()
head.setx(x - 20)
if head.direction == "right":
x = head.xcor()
head.setx(x + 20)
#Keybord binding
wn.listen()
wn.onkeypress(go_up, "w")
wn.onkeypress(go_down, "s")
wn.onkeypress(go_left, "a")
wn.onkeypress(go_right, "d")
#Main Game Loop
while True:
wn.update()
move()
time.sleep(delay)
wn.mainloop()
您在以下函数"go_up","go_down","go_right"和"go_left"中将"direction"错误拼写为"directin"。我还注意到您的"go_left"将方向设置为右,"go_right"将其设置为左。
代码的"前进方向"部分应如下所示:
def go_up():
head.direction = "up"
def go_down():
head.direction = "down"
def go_right():
head.direction = "right"
def go_left():
head.direction = "left"