You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现Mastermind游戏时正确位置数字统计异常问题

Python版Mastermind游戏位置计数错误修复方案

问题根因

  • 类型不匹配:four_digit_code_list存储的是整数类型的数字,用户输入的每个字符是字符串类型的数字,直接用==比较永远返回False,导致位置正确的计数无法正常统计。
  • 完全匹配判定错误:你用str(four_digit_code)生成的four_digit_code_string是类似"[1, 2, 3, 4]"的带符号字符串,和用户输入的4位纯数字字符串永远不匹配,就算全猜对也无法触发成功分支。
  • 变量意外修改:游戏循环第一行每次都会将初始为列表类型的four_digit_code转为字符串,属于冗余且不规范的写法,容易引发后续逻辑异常。

修复后完整代码

import random

def run_game():
    four_digit_code = []
    
    while len(four_digit_code) < 4:
        random_code = random.randint(1, 8)
        if random_code not in four_digit_code:
            four_digit_code.append(random_code)
    # 提前生成统一类型的正确码,避免后续类型不匹配问题
    correct_str = "".join(map(str, four_digit_code))
    correct_list = list(correct_str)
            
    number_of_turns = 12
    more_turns_left = True

    while more_turns_left:
        user_input = input("Input 4 digit code: ").strip()
        # 补充数字校验,避免用户输入非数字内容
        if len(user_input) != 4 or not user_input.isdigit():
            print("Please enter exactly four digits")
            continue

        if user_input == correct_str:
            print("Number of correct digits in correct place: {}".format(len(user_input)))
            print("Number of correct digits not in correct place: 0")
            print("Congratulations! You are a codebreaker!")
            print(f"The code was: {correct_str}")
            break

        digits_in_correct_place = 0
        digits_in_wrong_place = 0
        for index in range(4):
            if user_input[index] == correct_list[index]:
                digits_in_correct_place += 1
            elif user_input[index] in correct_str:
                digits_in_wrong_place += 1

        print(f"Number of correct digits in correct place: {digits_in_correct_place}")
        print(f"Number of correct digits not in correct place: {digits_in_wrong_place}")
        number_of_turns -= 1
        print(f"Turns left: {number_of_turns}")

        if number_of_turns == 0:
            print(f"The code was: {correct_str}")
            more_turns_left = False

if __name__ == "__main__":
    run_game()

内容的提问来源于stack exchange,提问作者LindaLee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 17:06:03