提问人:Demeridianth 提问时间:10/28/2023 最后编辑:Demeridianth 更新时间:10/28/2023 访问量:58
需要使用线程将倒数计时器添加到游戏中
Need to Add Countdown Timer to Game using threads
问:
我在python上写了一个简单的骰子游戏,我想为它实现一个倒数计时器!这是一个无休止的循环!也许是某种线程生成器?我是线程模块的新手。
如果我尝试为每个玩家向游戏添加两个线程:我会收到“RuntimeError: threads can only be started once”错误
import random
import os
import time
from threading import Thread
class Player:
def __init__(self, name) -> None:
self.name = name
self.score = 0
def add_points(self, points):
self.score += points
def roll_dice():
min_val = 1
max_val = 6
dice_value = random.randint(min_val, max_val)
return dice_value
这是我的倒计时时间
def countdown(user_time):
while user_time >= 0 and not done:
mins, secs = divmod(user_time, 60)
timer = '{:02d}:{:02d}'.format(mins, secs)
print(timer, end='\r')
time.sleep(1)
user_time -= 1
关键是:如果玩家不停止倒计时,他就输了
player1_name = input('enter name: ')
player2_name = input('enter name: ')
player1 = Player(player1_name)
player2 = Player(player2_name)
roll_again = 'y'
if __name__ == '__main__':
while roll_again.lower() == 'yes' or roll_again.lower() == 'y':
os.system('cls' if os.name == 'nt' else 'clear')
""" Player 1 """
print(f'Hurry up {player1_name}')
# new thread generated here
input('press enter to stop\n')
如果玩家没有用输入打断倒计时 - 游戏结束
done = True
# thread join
player1_roll = roll_dice()
player1.add_points(player1_roll)
print(f'{player1.name} has {player1.score}')
""" Player 2 """
print(f'Hurry up {player2_name}')
# new thread generated here
input('press enter to stop\n')
done = True
#thread join
player2_roll = roll_dice()
player2.add_points(player2_roll)
print(f'{player2.name} has {player2.score}')
if player1.score >= 30:
print(f'game over: {player1_name} has won')
break
elif player2.score >= 30:
print(f'game over: {player2_name} has won')
break
roll_again = input('Roll Again? ')
答: 暂无答案
上一个:循环内循环 [重复]
评论
Thread
input