How to set & ldquo; if the function has been called this several times & rdquo; in Python?

advertisements

So I'm designing a hangman game using Python and Kivy and I want to add a win/lose option.

one of the functions I've defined is Button_pressed which hides the button if it's been pressed but I want the function man_is_hung() to have something that says "if the button has been pressed 6 times, show "game over"."

Would someone please help me?

 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)


Use a decorator:

Example:

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

Demo:

>>> for _ in range(4): func(0, 0)
>>> func.count
4
>>> func(0, 0)
0
>>> func.count
5

In py3.x you can use nonlocal to achieve the same thing using a function instead of a class:

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

Demo:

>>> for _ in range(6):func(1,1)
>>> func(1, 1)
    ...
    raise TypeError('Enough button pressing')
TypeError: Enough button pressing