Python骰子游戏while循环问题:如何实现两名玩家轮流回合
问题解决思路
- 原代码中
while循环内的break导致循环仅执行一次就终止,后续的continue不在任何循环块内,因此触发报错。 - 缺少两名玩家的独立得分记录,无法区分双方进度。
- 回合切换逻辑不清晰,没有明确的玩家交替机制。
修正后的代码
import random # 输入玩家信息 players = [input("Player one name: "), input("Player two name: ")] print("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") print(f"{players[0]} vs {players[1]}") input("Press enter key to continue...") # 初始化游戏数据 scores = [0, 0] # 分别记录两名玩家的得分 current_player = 0 # 当前回合玩家索引(0为玩家1,1为玩家2) round_num = 1 max_rounds = 6 win_score = 10000 while round_num <= max_rounds and all(score < win_score for score in scores): print(f"\nRound: {round_num} | Current Player: {players[current_player]}") print(f"Your current score: {scores[current_player]}") busted = False turn_score = 0 while not busted: # 掷5个骰子 dice = [random.randint(1,6) for _ in range(5)] print(f"\nDice result: {dice}") # 计算本轮掷骰得分 temp_score = 0 # 检查顺子 sorted_dice = sorted(dice) if sorted_dice == [1,2,3,4,5] or sorted_dice == [2,3,4,5,6]: temp_score += 1250 else: # 计算1和5的得分 temp_score += dice.count(1)*100 temp_score += dice.count(5)*50 # 如果本轮无得分则爆掉 if temp_score == 0: busted = True print("Busted! No score added this turn.") break turn_score += temp_score print(f"Turn score so far: {turn_score}") # 选择保存或继续掷骰 choice = input("[S]ave score or [R]oll again? ").strip().lower() if choice == 's': scores[current_player] += turn_score print(f"Score saved! Total score: {scores[current_player]}") break # 切换玩家 current_player = 1 - current_player # 检查是否有人获胜 if any(score >= win_score for score in scores): winner = players[scores.index(max(scores))] print(f"\n{winner} wins with {max(scores)} points!") break # 进入下一轮 if current_player == 0: round_num += 1 # 游戏结束 if round_num > max_rounds: print("\nGame over! Max rounds reached.") winner = players[scores.index(max(scores))] print(f"{winner} wins with {max(scores)} points!")
关键修改说明
- 用
scores列表分别存储两名玩家的得分,current_player变量控制当前回合的玩家。 - 嵌套
while循环:外层控制全局回合和获胜条件,内层处理单个玩家的掷骰回合,确保循环逻辑合规。 - 修复了顺子判断逻辑:原代码仅判断骰子顺序为1-5或2-6,现在先排序再判断,适配骰子的任意排列顺序。
- 增加了爆掉(busted)逻辑:当掷出的骰子没有1或5也不是顺子时,本轮无得分,回合结束。
- 明确了玩家切换和回合推进的逻辑,确保两名玩家交替进行回合。
内容的提问来源于stack exchange,提问作者lui
相关产品推荐
相关产品推荐

