乌龟对按键没有反应

时间:2018-10-19 21:10:57

标签: python python-3.x function turtle-graphics

我是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()

2 个答案:

答案 0 :(得分:2)

您想要将函数引用传递给onkeypress函数,以便它将按需调用。

因此,您需要删除函数调用,例如:

wn.onkeypress(go_up(), 'w')

应为:

wn.onkeypress(go_up, 'w')

答案 1 :(得分:0)

@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:可能会阻止一些您想从播放器接收的输入事件。