我想写一个文本游戏的实时战斗系统。我希望玩家能够表演,并且在他们能够再次表演之前必须等待一定的秒数,而NPC也在这样做。在
我写了一个小例子:
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()
对于第一次攻击,该示例效果良好: 我输入'attack',敌方标志设置为True,npc攻击线程启动,但是当我再次尝试攻击时,我得到一个“RuntimeError:线程只能启动一次”。在
有没有一种方法可以在不引发错误的情况下重用该线程?还是我做错了?在
我们用},而不是{}和{}来重用相同的线程。在
start()
方法启动线程。 之后我们使用run()
方法,即p.run()
和{问题是线程已经在运行,并且由于while循环再次调用
n.start()
,因此无法再次启动正在运行的线程。在即使在线程死后,也需要重新初始化线程实例并重新启动。不能启动旧实例。在
在
while True
循环中,它试图多次启动一个线程。你要做的是检查线程是否正在运行,如果没有运行,启动线程实例。在相关问题 更多 >
编程相关推荐