2017-05-25 34 views
0

我正在嘗試爲文本遊戲編寫實時戰鬥系統。我希望玩家能夠採取行動,並且必須等待幾秒鐘才能夠再次採取行動,而NPC也同樣如此。在Python中重用線程

我寫了一個小例子:

import threading 
import time 

def playerattack(): 
    print("You attack!") 
    time.sleep(2) 


def npcattack(): 
    while hostile == True: 
     print("The enemy attacks!") 
     time.sleep(3) 

p = threading.Thread(target=playerattack) 
n = threading.Thread(target=npcattack) 

hostile = False 

while True: 
    if hostile == True: 
     n.start() 
    com = input("enter 'attack' to attack:") 
    if 'attack' in com: 
     hostile = True 
     p.start() 

的例子將正常工作的第一次進攻: 我進入「攻擊」,敵對的標誌被設置爲True,全國人大攻擊線程開始,但是當我再次嘗試攻擊時,我得到了'RuntimeError:線程只能啓動一次'。

有沒有辦法重用該線程,而不會引發錯誤?或者,我是否全力以赴?

+1

是的。你最好不用線程編寫這些東西。 – pvg

+1

你能解釋一個橡皮鴨爲什麼你需要這個例子的線程? – zwer

+0

你不能直接在python中殺死一個線程,但是你可以在多線程中處理線程。你可能正在使用線程來學習如何使用它們。 – thesonyman101

回答

0

問題是線程已經在運行,並且因爲while循環再次調用n.start()而無法再次啓動運行線程。

即使線程死了後,您仍需要重新初始化線程實例並重新啓動。您無法啓動舊實例。

在你的情況下,在while True循環它試圖多次啓動一個線程。你所做的是檢查線程是否正在運行,如果沒有運行,則啓動線程實例。

import threading 
import time 

def playerattack(): 
    print("You attack!") 
    time.sleep(2) 


def npcattack(): 
    while hostile: 
     print("The enemy attacks!") 
     time.sleep(3) 

p = threading.Thread(target=playerattack) 
n = threading.Thread(target=npcattack) 

hostile = False 

while True: 
    if hostile and not n.is_alive(): 
     try: 
      n.start() 
     except RuntimeError: #occurs if thread is dead 
      n = threading.Thread(target=npcattack) #create new instance if thread is dead 
      n.start() #start thread 

    com = input("enter 'attack' to attack:") 

    if 'attack' in com: 
     hostile = True 
     if not p.is_alive(): 
      try: 
       p.start() 
      except RuntimeError: #occurs if thread is dead 
       p = threading.Thread(target=playerattack) #create new instance if thread is dead 
       p.start() 
+0

這是完美的! 所以,我不會重複使用同一個確切的線程,我會產生一個運行相同函數的新線程。 非常感謝,我非常感謝! 編輯:此外,我試圖給你的答案投票,它說它記錄它,但因爲我有不到15聲望,它不會公開顯示它。抱歉! –

+0

是的,你不能一次又一次地重複使用同一個線程,你需要初始化一個新的線程實例,然後在需要的時候用不同的變量運行它,並且upvote這不是問題。 – Harwee

+0

'如果敵意==真'是多餘的。只要使用'如果敵對'。 – zondo