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

Wordle项目打印用户历史猜测列表时出现索引越界错误

Wordle项目打印历史猜测时索引越界问题修复

问题描述

我正在开发一个Wordle项目,其余功能正常,但在终端打印用户历史猜测列表时会触发索引越界错误。曾尝试向列表中添加初始元素(推测是索引0导致问题),但并未解决。

原代码(忽略ANSI转义码)

import random as random
play_again="Y"
while play_again=="Y":
  count=0
  list_words=[]
  my_file = open("usaWords.txt", "r")
  data = my_file.read()
  # replacing end splitting the text 
  # when newline ('\n') is seen.
  word_list = data.split("\n")
  my_file.close()
  #generating a random number
  random_word=(random.choice(word_list))
  #re-generating a random number if duplicates or if digits less than 3
  #converting number into set because they dont allow duplicates
  while len((random_word)) !=5:
      random_word=(random.choice(word_list))
  print('\u001b[47;1m' + '\033[31m'+'Welcome to Wordle! You have six chances to guess the five-letter word. A letter G means you got that letter correct and in the right position. A letter Y means you matched that letter, but it is in the wrong position.A letter B means that letter does not appear in the correct word')

  def user_input():
      
      user_guess=input('Please enter your guess: ')
      guess_bad=True # Repeating below until the user gives a good input
      while guess_bad:
        if len(user_guess) !=5: #this should make sure that all digits can be converted to integers!
            print('Must contain five letters or more.')
            user_guess = input('Please enter a 5-letter word:')
        # elif len(set(str(user_guess))) <5:
        #         print('No duplicates.')
        #         user_guess = input('Please enter a 5-letter word. No duplicates:')
        else:
          guess_bad=False
      return user_guess
  #Docstring required within each function:
      """
          Description of function: This function will convert the words into lists to compare and output the answer to user. It also takes in the number of tries and outputs the count.
          return: The number of tries.
      """

 
  def add_user_lists(colored_guesses)->int: 
    background='\u001b[47;1m'
    user_guess=user_input()
    random_word_list=[]
    past_guess=['none']
    past_guess.append(user_guess)
    user_input_list=[]
    for letter in str(random_word):
      random_word_list.append(letter)
    for letter in str(user_guess):
      user_input_list.append(letter)
  #   Just to check the answers:  
    print(random_word_list)
    print(user_input_list)
    #save the colors here
    colored_guess=['B','B','B','B','B']
    #For storing the old guesses
    
    #This does greens
    for i in range (0, len(random_word_list)):
      if random_word_list[i]==user_input_list[i]:
        colored_guess[i]='G'
        
      elif random_word_list[i] in user_input_list:
        colored_guess[i]='Y'
      else:
        colored_guess[i]='B'
    #now you do all of the yellows

    colored_guesses.append(colored_guess)

    for i in range(len(colored_guesses)):
    
      print(f"{background} Guess {i+1} is {past_guess[i+1]} colors are {''.join(colored_guesses[i])}")

    return colored_guesses

  
  colored_guesses=[]
  temp=[]
  while len(temp)<6 and ['G','G','G','G','G'] not in temp:
    temp=add_user_lists(colored_guesses)
  if len(temp) >=6:
    print("You lost.")
  elif ['G','G','G','G','G'] in temp:
    print(f'you won! it took {len(temp)} tries!')
  play_again=(input("Do you want to play again? Y if yes, N if no: "))

预期输出

What is your guess? truck
Guess 1: slice  BBBBY
Guess 2: truck  BYBBB
What is your guess? delay
Guess 1: slice  BBBBY
Guess 2: truck  BYBBB
Guess 3: delay  BYBYB
What is your guess? wheat
Guess 1: slice  BBBBY
Guess 2: truck  BYBBB
Guess 3: delay  BYBYB
Guess 4: wheat  BBYYB

问题根源

索引越界的核心问题是**past_guess列表每次调用add_user_lists时都会重新初始化**:

  • 每次调用函数,past_guess都会被重置为['none'],然后只追加当前的用户猜测,所以它的长度永远是2(初始元素+当前猜测)
  • 但colored_guesses是持续追加的,第二次调用时长度为2,第三次为3,以此类推
  • 循环for i in range(len(colored_guesses))中,当i等于1时,past_guess[i+1]即past_guess[2]会超出列表长度,触发索引越界错误

修复方案

把past_guess移到函数外部,和colored_guesses一起初始化,作为全局的历史猜测列表,每次调用add_user_lists时只追加新的猜测,而不是重新创建:

完整修复后代码

import random as random
play_again="Y"
while play_again=="Y":
    count=0
    list_words=[]
    my_file = open("usaWords.txt", "r")
    data = my_file.read()
    word_list = data.split("\n")
    my_file.close()
    
    random_word=random.choice(word_list)
    while len(random_word) !=5:
        random_word=random.choice(word_list)
    
    print('\u001b[47;1m' + '\033[31m'+'Welcome to Wordle! You have six chances to guess the five-letter word. A letter G means you got that letter correct and in the right position. A letter Y means you matched that letter, but it is in the wrong position.A letter B means that letter does not appear in the correct word')

    def user_input():
        user_guess=input('Please enter your guess: ')
        guess_bad=True
        while guess_bad:
            if len(user_guess) !=5:
                print('Must be a 5-letter word.')
                user_guess = input('Please enter a 5-letter word:')
            else:
                guess_bad=False
        return user_guess

    def add_user_lists(colored_guesses, past_guess): 
        background='\u001b[47;1m'
        user_guess=user_input()
        past_guess.append(user_guess)
        random_word_list=list(random_word)
        user_input_list=list(user_guess)
        
        colored_guess=['B','B','B','B','B']
        # 先处理绿色(位置正确)
        for i in range(len(random_word_list)):
            if random_word_list[i]==user_input_list[i]:
                colored_guess[i]='G'
                # 标记已匹配的字符,避免重复判断黄色
                random_word_list[i] = None
                user_input_list[i] = None
        
        # 再处理黄色(字符存在但位置错误)
        for i in range(len(random_word_list)):
            if user_input_list[i] is not None and user_input_list[i] in random_word_list:
                colored_guess[i]='Y'
                # 标记已匹配的字符
                random_word_list[random_word_list.index(user_input_list[i])] = None
        
        colored_guesses.append(colored_guess)
        
        for i in range(len(colored_guesses)):
            print(f"{background} Guess {i+1}: {past_guess[i]}  {''.join(colored_guesses[i])}")

        return colored_guesses

    colored_guesses=[]
    past_guess=[]
    temp=[]
    while len(temp)<6 and ['G','G','G','G','G'] not in temp:
        temp=add_user_lists(colored_guesses, past_guess)
    if len(temp) >=6:
        print("You lost.")
    elif ['G','G','G','G','G'] in temp:
        print(f'You won! It took {len(temp)} tries!')
    play_again=input("Do you want to play again? Y if yes, N if no: ").upper()

额外优化说明

  1. 修复了颜色判断逻辑的bug:原代码中重复字符会错误标记黄色,现在先处理绿色并标记已匹配字符,避免重复判断
  2. 简化了列表转换逻辑,用list()替代循环追加
  3. 调整了输入提示表述,更准确
  4. 对play_again输入做大写转换,避免大小写匹配问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:40:16