0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

マルチスレッドのイベント制御

Posted at

デスマッチ(KeyboardInterruptまで戦う)

import threading
import time
import sys

event = threading.Event()

def minamikawa(name):
    '''
    flag=True: 防御状態
    flag=False: 攻撃状態
    '''
    count = 0
    event.set()  # 初期値は青信号
    while True:
        if 5 < count <= 10:
            event.clear()  # 体力回復 攻撃状態へ
            print("\33[41;1m[{}]ラッシュ...\033[0m".format(name))
        elif count > 10:
            event.set()  # 体力切れ 防御状態へ
            count = 0
            print("\33[41;1m[{}]体力切れ...\033[0m".format(name))
        else:
            print("\33[41;1m[{}]防御...\033[0m".format(name))

        time.sleep(1)
        count += 1

def shibata(name):
    while True:
        if event.is_set():  # 相手が体力切れかどうか
            print("\33[42;1m[{}] 攻撃...\033[0m".format(name))
            time.sleep(1)
        else:
            print("\33[42;1m[{}] 防御...\033[0m".format(name))
            event.wait()
            # flag=Trueになるまでここでブロッキングする
            print("\33[42;1m[{}] 反撃開始...\033[0m".format(name))


systema = threading.Thread(target=minamikawa, args=("MINAMIKAWA",))
#mainが終了したらスレッドが終了するようにデーモン化
systema.setDaemon(True)
systema.start()

prowrestling = threading.Thread(target=shibata, args=("SHIBATA",))
#mainが終了したらスレッドが終了するようにデーモン化
prowrestling.setDaemon(True)
prowrestling.start()

try:
    while True:
        time.sleep(1)
        print('Fight!!\n')
except KeyboardInterrupt:
    print('!!FINISH!!')
    sys.exit()
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?