我是Python新手,所以我花了一些时间观看了一些关于如何制作简单的“贪吃蛇”游戏的视频,我正在做那家伙所说的一切,但是当涉及到键盘绑定时出现了问题,我不能'别动我的乌龟..
code:
https://pastebin.com/GLSRNKLR
import turtle
import time
delay = 0.1
# Screen
wn = turtle.Screen()
wn.title("Snake Game By AniPita")
wn.bgcolor('black')
wn.setup(600, 600)
wn.tracer(0)
# Snake Head
head = turtle.Turtle()
head.speed(0)
head.shape("square")
head.color("white")
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 move():
if head.direction == "up":
y = head.ycor()
head.sety(y + 10)
if head.direction == "down":
y = head.ycor()
head.sety(y - 10)
if head.direction == "left":
x = head.xcor()
head.setx(x - 10)
if head.direction == "right":
x = head.xcor()
head.setx(x + 10)
# Keyboard Bindings
wn.onkeypress(go_up(), 'w')
wn.onkeypress(go_down(), 's')
wn.onkeypress(go_left(), 'a')
wn.onkeypress(go_right(), 'd')
wn.listen()
# Main Game
while True:
wn.update()
time.sleep(delay)
move()
wn.mainloop()
您希望将函数引用传递给 onkeypress 函数,以便它可以根据需要调用它。
因此,您需要删除函数调用,例如:
wn.onkeypress(go_up(), 'w')
应该是:
wn.onkeypress(go_up, 'w')
@JBernardo 关于函数引用与函数调用的说法绝对正确(+1)。
但是,我想解决代码中的另一个问题:使用
while True:
以及较小程度的 wn.update()
和 time.sleep(delay)
。在像海龟这样的事件驱动世界中,永远不应该有 while True:
,因为控制权应该通过代码永远不会到达的 wn.mainloop()
调用移交给事件处理程序。为了获得您想要的时间延迟动画,我们可以通过 wn.ontimer()
使用计时器事件。
下面是重写的代码,以使用计时器事件并简化您的转动逻辑:
from turtle import Screen, Turtle
DELAY = 100 # milliseconds
# Screen
wn = Screen()
wn.title("Snake Game By AniPita")
wn.bgcolor('black')
wn.setup(600, 600)
# Snake Head
head = Turtle('square')
head.speed('fastest')
head.color('white')
head.setheading(1) # magic token for no motion
head.penup()
# Functions
def go_up():
head.setheading(90)
def go_down():
head.setheading(270)
def go_left():
head.setheading(180)
def go_right():
head.setheading(0)
def move():
if head.heading() % 90 == 0:
head.forward(10)
wn.ontimer(move, DELAY)
# Keyboard Bindings
wn.onkeypress(go_up, 'w')
wn.onkeypress(go_down, 's')
wn.onkeypress(go_left, 'a')
wn.onkeypress(go_right, 'd')
wn.listen()
# Main Game
move()
wn.mainloop()
使用
while True:
可能会阻止您想要从播放器接收的一些输入事件。