2017-05-25 31 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