Python龟图:键盘绑定功能第一次后无法正常工作

时间:2017-04-19 21:43:33

标签: python turtle-graphics

我是一个没有经验的python 3程序员。我使用海龟模块在youtube上的教程后创建了这个游戏,我遇到了一个问题。以下是我认为问题所在的代码的一部分:

def missile_status(self):
    i = 0
    if self.status == "firing":
        while i <= 5:
            i += 1
            turtle.time.sleep(1)
    if i >= 5:
        self.status = "ready"

def shoot(self):
    if self.status == "ready":
        self.goto(player_traits.xcor(), player_traits.ycor())
        self.setheading(player_traits.heading())
        self.status = "firing"
        self.st()

所以我把这个功能绑定了&#39;拍摄&#39;用空格键。如果我第一次按空格键它会执行该功能并正常工作。但之后如果我试着按空格键并拍摄(五秒钟后),该功能无法正常工作(它不会拍摄)。 这可能是一个可怕的描述,但我希望你能够使用它。对不起,谢谢你的时间!

1 个答案:

答案 0 :(得分:0)

您可能没有提供足够的代码来调试,但是在诸如Turtle之类的事件驱动环境中,任何包含time.sleep()的教程都是可疑的。下面是一个完整的,可运行的,简化的示例,说明了如何解决此问题。为使示例简单起见,播放器仅在一个维度上移动,但基本思想也应在两个维度上起作用:

from turtle import Screen, Turtle
from functools import partial

class Missle(Turtle):
    def __init__(self):
        super().__init__("circle")

        self.hideturtle()
        self.shapesize(0.5)
        self.setheading(90)
        self.penup()

        screen.onkey(self.shoot, "space")  # enable shooting

    def track_missle(self, milliseconds=5000):
        if milliseconds > 0:
            self.forward(10)
            milliseconds -= 100

            # can't use partial() due to object has no attribute '__name__'
            screen.ontimer(lambda: self.track_missle(milliseconds), 100)
        else:
            self.hideturtle()  # this shot is finished
            screen.onkey(self.shoot, "space")  # reenable shooting

    def shoot(self):
        screen.onkey(None, "space")  # disable further shots for now

        self.goto(player.position())  # shots originate from player's position
        self.showturtle()

        screen.ontimer(self.track_missle, 100)  # move for 5 secs, update every 0.1 sec

class Player(Turtle):
    def __init__(self):
        super().__init__("triangle")

        self.settiltangle(90)  # move side to side but face upward
        self.penup()
        self.sety(-screen.window_height() / 4)

        screen.onkey(partial(self.forward, 10), "Right")
        screen.onkey(partial(self.backward, 10), "Left")

screen = Screen()
player = Player()
missle = Missle()

screen.listen()
screen.mainloop()