Python开发Mastermind猜色游戏颜色计数逻辑错误如何修复
Mastermind猜色游戏计数异常修复方案
问题根因
- 颜色匹配计数未考虑重复色的出现频次:原有逻辑只要玩家猜的颜色在答案中存在就算有效,不会匹配答案中该颜色的实际数量,是答案有3红、玩家猜4红被统计为4个颜色正确的核心原因。
- 玩家猜测列表未重置:每轮猜测后
player_colors没有清空,下一轮会继续追加内容,列表长度会超过4,引发逻辑混乱。 - 尝试次数统计错误:
attempts变量定义在compare函数内部,每次调用都会重置为10,无法实现剩余次数递减的效果。 - 函数返回值异常:如果玩家未猜对,
compare函数没有返回值,打印时会输出多余的None。
修复后完整代码
import random from collections import Counter def compare(player_colors, computer_colors, attempts_left): both_correct = 0 # 先统计位置和颜色都正确的数量 for p, c in zip(player_colors, computer_colors): if p == c: both_correct += 1 # 统计所有颜色匹配的总数量(含位置正确的,按最小频次计算) player_counter = Counter(player_colors) computer_counter = Counter(computer_colors) total_color_match = 0 for color, count in player_counter.items(): total_color_match += min(count, computer_counter.get(color, 0)) # 仅颜色正确、位置错误的数量 = 总颜色匹配数 - 位置颜色都正确的数量 correct_color_only = total_color_match - both_correct if both_correct == 4: return f"恭喜!你猜对了正确答案:{player_colors}", True else: print(f"仅颜色正确的数量:{correct_color_only}") print(f"颜色和位置都正确的数量:{both_correct}") print(f"你还剩 {attempts_left - 1} 次尝试机会") return "", False colors = ["red", "blue", "yellow", "pink", "white", "orange"] computer_colors = [] max_attempts = 10 # 生成答案 for _ in range(4): computer_color = random.choice(colors) computer_colors.append(computer_color[0]) print("欢迎来到Mastermind猜色游戏") game_is_on = True current_attempts = 0 while game_is_on and current_attempts < max_attempts: player_colors = [] print(f"可选颜色:{colors}") # 调试用,正式玩可以注释掉下面一行 print(f"答案(调试用):{computer_colors}") print("请从上面的颜色中选4个,输入颜色首字母即可:") player_answer1 = input("第一个颜色:").lower() player_colors.append(player_answer1) player_answer2 = input("第二个颜色:").lower() player_colors.append(player_answer2) player_answer3 = input("第三个颜色:").lower() player_colors.append(player_answer3) player_answer4 = input("第四个颜色:").lower() player_colors.append(player_answer4) res, is_win = compare(player_colors, computer_colors, max_attempts - current_attempts) if is_win: print(res) game_is_on = False current_attempts += 1 if current_attempts >= max_attempts: print(f"很遗憾,你已经用完了所有尝试机会,正确答案是{computer_colors}")
关键修改说明
- 用
Counter统计双方颜色的出现频次,对每个颜色取玩家和答案中频次的最小值求和,得到总颜色匹配数,彻底解决重复颜色计数超标的问题。 - 每轮猜测开始前重新初始化
player_colors,避免历史数据干扰当前轮次。 - 将尝试次数统计移到全局循环中,每轮猜测后主动递减,达到最大次数后自动结束游戏。
- 优化函数返回值逻辑,避免打印多余的
None,同时补充了次数耗尽的结束提示。
内容的提问来源于stack exchange,提问作者Anscom
相关产品推荐
相关产品推荐

