2013-09-24 13 views
0

所以我正在設計一個使用Python和Kivy的hang子手遊戲,我想添加一個雙贏選項。如何在Python中放置「如果函數已被多次調用」?

我定義的一個函數是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) 
+4

您需要在對象成員或'全局'中保存狀態。 –

回答

0

ummmm

num_presses = 0 
def button_pressed(button): 
    global num_presses 
    num_presses += 1 
    if num_presses > X: 
     print "YOU LOSE SUCKA!!!" 
    for (letter, label) in CurrentWord: 
     if (letter.upper() == button.text): label.text=letter 
    button.text=" " # hide the letter to indicate it's been tried 

會做的一種方式...林種驚訝,你已經走到這一步,不知道如何保存簡單的狀態。

5

使用decorator

例子:

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 

演示:

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

在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 

演示:

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

這是一個非常新穎的想法。我不知道這是不是一個好的。 – Marcin

+0

這可能是我使用裝飾器(功能簿記)的頭號事情。它使您的代碼方式更清晰,並且非常容易移除/更改。 – reem

1

這裏有一個方法有靜態變量的函數,不涉及全局或類:

def foobar(): 
    foobar.counter = getattr(foobar, 'counter', 0) 
    foobar.counter += 1 
    return foobar.counter 

for i in range(5): 
    print foobar() 
1

你可以保存按鈕作爲一類像這樣:

class button_pressed(Object): 
    def __init__(self): 
     self.num_calls = 0 

    def __call__(self, button): 
     self.num_calls += 1 
     if self.num_calls > 6: 
      print "Game over." 
      return None 
     else: 
      # Your regular function stuff goes here. 

這基本上是一個手動裝飾器,雖然它可能有點複雜,你要做什麼這是一個簡單的方法來做一個函數簿記。

真的,做這種事情的正確方法是使用一個裝飾器,該裝飾器需要一個參數來調用函數能夠被調用的次數,然後自動應用上述模式。

編輯:啊! hcwhsa擊敗了我。他的解決方案是我在上面討論的更一般的解決方案。

相關問題