Python双人掷骰子游戏:如何判定玩家连续三次掷出同一点数
掷骰子游戏胜负判定解决方案
核心判定逻辑
要检测玩家是否连续三次掷出同一点数,只需要每次掷骰后,检查该玩家最近3次的掷骰结果是否完全一致即可。你提供的现有代码存在以下可优化点:
- 仅对玩家1做了胜负判定,完全遗漏了玩家2的逻辑
- 写死了三轮掷骰的判断流程,硬编码逻辑扩展性差
- 玩家2的掷骰结果虽然存入了列表,但未参与任何判定,属于无效数据
通用判定函数实现
可以单独封装判定逻辑,和主流程解耦,后续修改规则也不需要调整主代码:
def check_consecutive_win(roll_history, required_times=3): # 掷骰次数不足时直接返回未获胜 if len(roll_history) < required_times: return False # 取最近N次结果判断是否全部相等 latest_rolls = roll_history[-required_times:] return all(roll == latest_rolls[0] for roll in latest_rolls)
如果需要判定的是连续三次掷出指定固定点数(例如提前指定要连续三次掷出6才算赢),可以给函数新增目标点数参数:
def check_target_win(roll_history, target_num, required_times=3): if len(roll_history) < required_times: return False latest_rolls = roll_history[-required_times:] return all(roll == target_num for roll in latest_rolls)
修正后的完整可运行代码
import random def check_consecutive_win(roll_history, required_times=3): if len(roll_history) < required_times: return False latest_rolls = roll_history[-required_times:] return all(roll == latest_rolls[0] for roll in latest_rolls) # 初始化变量 player1_history = [] player2_history = [] current_round = 1 while True: # 每轮两位玩家各掷一次骰子 p1_roll = random.randint(1, 6) p2_roll = random.randint(1, 6) print(f"第 {current_round} 轮:\t玩家1掷出:{p1_roll};玩家2掷出:{p2_roll}") # 记录双方掷骰结果 player1_history.append(p1_roll) player2_history.append(p2_roll) # 判定胜负 p1_win = check_consecutive_win(player1_history) p2_win = check_consecutive_win(player2_history) if p1_win and p2_win: print(f"双方同时满足获胜条件,平局!") break elif p1_win: print(f"玩家1获胜!连续三次掷出点数 {player1_history[-1]}") break elif p2_win: print(f"玩家2获胜!连续三次掷出点数 {player2_history[-1]}") break current_round += 1
内容的提问来源于stack exchange,提问作者Martin Müller
相关产品推荐
相关产品推荐

