写一个八路抢答器的程序
抢答器程序:
import threading
class Buzz:
def __init__(self, n):
self.n = n
self.count = 0
self.lock = threading.Lock()
self.cv = threading.Condition()
def buzz(self):
while True:
with self.cv:
self.cv.wait()
print("Buzz")
self.count += 1
if self.count >= self.n:
self.cv.notify_all()
return
class Player:
def __init__(self, name, buzz):
self.name = name
self.buzz = buzz
def run(self):
while True:
ans = input(f"{self.name} buzzer: ")
with self.buzz.lock:
if self.buzz.count >= self.buzz.n:
return
if ans == "buzz":
with self.buzz.cv:
self.buzz.cv.notify()
self.buzz.count += 1
if self.buzz.count >= self.buzz.n:
self.buzz.cv.notify_all()
return
if __name__ == "__main__":
n = 3
buzz = Buzz(n)
buzz_thread = threading.Thread(target=buzz.buzz)
buzz_thread.start()
players = [
Player("Alice", buzz),
Player("Bob", buzz),
Player("Charlie", buzz),
]
player_threads = [threading.Thread(target=p.run) for p in players]
for t in player_threads:
t.start()
for t in player_threads:
t.join()
buzz_thread.join()
print("Game over")
程序实现了一个八路抢答器游戏,其中 Buzz 类负责判断何时有人抢答成功,Player 类负责处理每个玩家的抢答,主程序启动 Buzz 和若干个 Player 线程并等待它们结束。程序运行时,玩家在终端上输入 buzz 按钮即可进行抢答。当有一个玩家抢答成功后,程序输出 Buzz 并结束游戏
原文地址: https://www.cveoy.top/t/topic/hh0F 著作权归作者所有。请勿转载和采集!