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

MasterMind游戏出现Index out of range错误,求排查修复方案

MasterMind游戏索引越界错误排查与解决

嘿,我来帮你搞定这个MasterMind游戏的索引越界问题!这个Index out of range错误主要是输入处理不严谨导致的,咱们一步步拆解:

错误根源

  1. 输入分割逻辑有问题:你用了guess.split(),但这个方法默认按空格分割字符串。如果用户输入连续数字(比如12345),split后得到的列表只有1个元素,而密码是5个元素的元组,循环到i=1时访问guess[1]自然就越界了。
  2. 缺少输入验证:没有检查用户输入的长度是否为5,也没验证每个字符是不是1-5的数字,万一用户输入少于/多于5个字符,或者乱输字母,都会触发索引错误。

修复方案

我调整了代码,主要做了这几件事:

  • 处理输入时先去掉空格,再按字符拆分,不管用户是连续输入还是用空格分隔都能兼容
  • 添加输入验证,确保用户输入的是5个1-5的数字,不符合要求就提示重新输入
  • 优化循环和计数逻辑,避免不必要的错误

修正后的完整代码

def MasterMind():
    import random
    tries = 10
    # 生成5个1-5的随机数作为密码
    password = (random.randint(1,5), random.randint(1,5), 
                random.randint(1,5), random.randint(1,5), random.randint(1,5))
    
    while tries > 0:
        guess = input("To access the treasure you have to guess the password!!! Guess the 5 digit password between numbers 1-5: ")
        # 去掉输入中的空格,然后按字符拆分
        guess = guess.replace(" ", "")
        # 输入验证:必须是5个字符,且每个字符都是1-5的数字
        if len(guess) != 5 or not all(c in "12345" for c in guess):
            print("Invalid input! Please enter exactly 5 digits between 1 and 5 (you can use spaces or not).")
            continue
        
        numbers_correct = 0
        tries -= 1
        # 遍历比较每个位置的数字
        for i in range(5):
            if str(password[i]) == guess[i]:
                numbers_correct += 1
        
        if numbers_correct == 5:
            print(f"Congratulations! You guessed the password in {10 - tries} tries!")
            return
        else:
            print(f"Wrong guess! You have {numbers_correct} correct digits in the right position. {tries} tries left.")
    
    print(f"Game over! The correct password was {''.join(str(num) for num in password)}.")

# 启动游戏
MasterMind()

额外说明

  • 现在用户不管输入12345还是1 2 3 4 5,代码都能正确处理
  • 输入验证会过滤非法内容,避免程序崩溃
  • 游戏结束后会显示正确密码,提升用户体验

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:23:23