所以我正在使用Python和Kivy设计一个刽子手游戏,我想添加一个赢/输选项.
我定义的其中一个函数是Button_pressed,如果它被按下则会隐藏按钮,但是我希望函数man_is_hung()能够显示"如果按钮被按下了6次,则显示"游戏结束"."
有人请帮帮我吗?
def button_pressed(button):
for (letter, label) in CurrentWord:
if (letter.upper() == button.text): label.text=letter
button.text=" " # hide the letter to indicate it's been tried
def man_is_hung():
if button_pressed(button)
Run Code Online (Sandbox Code Playgroud)
使用装饰者:
例:
class count_calls(object):
def __init__(self, func):
self.count = 0
self.func = func
def __call__(self, *args, **kwargs):
# if self.count == 6 : do something
self.count += 1
return self.func(*args, **kwargs)
@count_calls
def func(x, y):
return x + y
Run Code Online (Sandbox Code Playgroud)
演示:
>>> for _ in range(4): func(0, 0)
>>> func.count
4
>>> func(0, 0)
0
>>> func.count
5
Run Code Online (Sandbox Code Playgroud)
在py3.x中,您可以使用nonlocal
函数而不是类来实现相同的功能:
def count_calls(func):
count = 0
def wrapper(*args, **kwargs):
nonlocal count
if count == 6:
raise TypeError('Enough button pressing')
count += 1
return func(*args, **kwargs)
return wrapper
@count_calls
def func(x, y):
return x + y
Run Code Online (Sandbox Code Playgroud)
演示:
>>> for _ in range(6):func(1,1)
>>> func(1, 1)
...
raise TypeError('Enough button pressing')
TypeError: Enough button pressing
Run Code Online (Sandbox Code Playgroud)