Kivy:做定时事件的更好方法(骰子滚动动画)
Kivy: better way to do timed events (dice rolling animation)
我正在编写一个 yahtzee 克隆来自学 Kivy(我对 Python 和一般编程还是很陌生),我在弄清楚如何最好地制作骰子动画时遇到了一些麻烦滚动。这段代码按预期工作,但我觉得我在概念上遗漏了一些东西。是否有更简单或更简洁的方式让时钟事件在设定的时间段内发生?
这是我目前拥有的:
父布局包含 5 个骰子作为子控件。用户单击一个按钮使用此方法将它们全部滚动:
def roll_all_dice(self):
for dice in self.children:
Clock.schedule_interval(dice.roll, .1)
Clock.schedule_once(dice.roll_animation_callback, .5)
如果我理解正确,它会每 .1 秒安排一次滚动,然后在 0.5 秒后调用 roll_animation_callback,这会停止事件。
以下是相关的骰子方法:
def roll(self, *args):
'''changes the number of the die and updates the image'''
if self.state != "down":
self.number = randint(1,6)
self.source = self.get_image()
def get_image(self):
'''returns image path for each of the die's sides'''
if self.state == "down":
return "images/down_state/dice" + str(self.number) + ".png"
else:
return "images/up_state/dice" + str(self.number) + ".png"
def roll_animation_callback(self, *args):
'''turns off the dice rolling animation event'''
Clock.unschedule(self.roll)
这看起来不错,像这样使用时钟是正常的。
我正在编写一个 yahtzee 克隆来自学 Kivy(我对 Python 和一般编程还是很陌生),我在弄清楚如何最好地制作骰子动画时遇到了一些麻烦滚动。这段代码按预期工作,但我觉得我在概念上遗漏了一些东西。是否有更简单或更简洁的方式让时钟事件在设定的时间段内发生?
这是我目前拥有的:
父布局包含 5 个骰子作为子控件。用户单击一个按钮使用此方法将它们全部滚动:
def roll_all_dice(self):
for dice in self.children:
Clock.schedule_interval(dice.roll, .1)
Clock.schedule_once(dice.roll_animation_callback, .5)
如果我理解正确,它会每 .1 秒安排一次滚动,然后在 0.5 秒后调用 roll_animation_callback,这会停止事件。
以下是相关的骰子方法:
def roll(self, *args):
'''changes the number of the die and updates the image'''
if self.state != "down":
self.number = randint(1,6)
self.source = self.get_image()
def get_image(self):
'''returns image path for each of the die's sides'''
if self.state == "down":
return "images/down_state/dice" + str(self.number) + ".png"
else:
return "images/up_state/dice" + str(self.number) + ".png"
def roll_animation_callback(self, *args):
'''turns off the dice rolling animation event'''
Clock.unschedule(self.roll)
这看起来不错,像这样使用时钟是正常的。