如何在python中停止线程变量

时间:2018-09-19 02:35:21

标签: python

如标题所示,我正在学校编程一项任务,并且我有一个变量来检查玩家遭受的伤口,但是伤口等于死亡数量,并不能像计划的那样停止游戏,并连续打印“ You Died” '而不是一次。任何提示将非常有帮助
import sys
import threading
import multiprocessing

wounds = 2

def die():
    print("You Died")
    sys.exit()
    return

def woundCount():
    global wounds
    if wounds >= 3:
        die()
        return

def checkdeath():
    threading.Timer(0.5, checkdeath).start()
    woundCount()
    return

####This should print the wounds and then kill your character.
print(wounds)
wounds = wounds + 1
print(wounds)

1 个答案:

答案 0 :(得分:0)

之所以这样做,是因为方法checkdeath()在触发另一个wounds之前不会检查checkdeath()(或者如果您已经死了)。您可以通过以下方法解决它:

>>> import sys
>>> import threading
>>> import multiprocessing
>>> wounds = 2
>>> is_dead = False
>>> def die():
        global is_dead
        is_dead = True
        print("You Died")
        sys.exit()
        return

>>> def woundCount():
        global wounds
        if wounds >= 3:
            die()


>>> def checkdeath():
        if is_dead:
            return
        threading.Timer(0.5, checkdeath).start()
        woundCount()
        return

>>> checkdeath()
>>> wounds += 1
>>> You Died

因此,每当您死后,is_dead就会变成True。而且,当您在启动另一个线程之前检查是否已经死亡时,该死亡通知仅打印一次。