2014-07-07 23 views
0

所以我正在製作一個基於文本的冒險遊戲。我現在正在引擎上工作,在長時間尋找解決此問題的解決方案後,我陷入困境。定時線程函數作爲一個類中的屬性

我有一個叫做use_action的類。該類的一個參數是函數的名稱。我希望能夠創建這個動作,並有一個可能的自定義函數來處理調用這個use_action的項目做特定的事情。

我現在正在使用的自定義函數是玩家受傷的地方,每隔幾秒鐘就會失去5點HP。

這應該從他使用某個特定物品開始,然後在他使用連接到停止功能的藥物時停止。我遇到的問題是該函數被立即調用。即使我試圖在一個很長的else語句結束時調用它。然後當我到達我想要調用的位置時,它不會調用。

我沒有發佈整個班級,因爲它的功能大約是150行代碼。

class use_action(object): 
    def __init__(self, function = None): 
     self.function = function 


pizza_act = use_action(function = mechanics.tmr.start()) 

#This is located at the end of an if else statement after the player types use . . . 
if self.function != None: 
    self.function 
else: 
    pass 

從力學:

thread_list = [] 

class TimerClass(threading.Thread): 
    def __init__(self, function, time): 
     threading.Thread.__init__(self) 
     self.event = threading.Event() 
     self.function = function 
     self.time = time 
     thread_list.append(self) 

    def run(self): 
     while not self.event.is_set(): 
      self.event.wait(self.time) 
      self.function() 

    def stop(self): 
     self.event.set() 

def blank_current_readline(): 
    # Next line said to be reasonably portable for various Unixes 
    (rows,cols) = struct.unpack('hh', fcntl.ioctl(sys.stdout, termios.TIOCGWINSZ,'1234')) 

    text_len = len(readline.get_line_buffer())+2 

    # ANSI escape sequences (All VT100 except ESC[0G) 
    sys.stdout.write('\x1b[2K')       # Clear current line 
    sys.stdout.write('\x1b[1A\x1b[2K'*(text_len/cols)) # Move cursor up and clear line 
    sys.stdout.write('\x1b[0G')       # Move to start of line 



def pizza_poisoned_action(): 
    # threading.Timer(10, pizza_poisoned_action).start() 
    blank_current_readline() 
    print "You lost 5 hp." 
    initialization.gamer.hp -= 5 
    sys.stdout.write('> ' + readline.get_line_buffer()) 
    sys.stdout.flush()   # Needed or text doesn't show until a key is pressed 

tmr = TimerClass(pizza_poisoned_action, 5) 

很抱歉的長度,我試圖只發布相關的東西這一點。如果您認爲我應該發佈一些可能相關的其他代碼,請告訴我!

+0

提示:類應該使用CamelCase。只是爲了將它與功能分開。 – aIKid

+0

謝謝!這就說得通了。我會更新我的代碼。 :) – Pljeskavica

回答

1

如果你想傳遞一個函數,不要來調用它。否則,你會傳遞返回值。

pizza_act = use_action(function = mechanics.test()) #Wrong! 
pizza_act = use_action(function = mechanics.test) #Right 
+0

謝謝你的幫助!現在看起來很明顯。但我對編程完全陌生,從Hello,World開始! 3個星期前,有時候最小的東西也是最難找到的答案:) – Pljeskavica

+0

哈哈哈,好吧,這是一切的開始。別客氣!保持學習! – aIKid

相關問題