如何在for循环中跳过已匹配项?解决Wordle类游戏重复字母判定问题
5字母猜词游戏(类Wordle)重复字母反馈问题求助
项目背景
我正在开发一款类似Wordle的简易5字母猜词游戏,核心逻辑:
- 程序随机获取一个5字母单词
- 用户输入猜测单词后,反馈字母是否存在于目标单词中,以及是否处于正确位置

问题描述
当目标单词包含重复字母时,代码会错误地向用户反馈过多该字母。核心原因是当前代码会用用户输入的每个字母遍历整个目标单词,导致匹配过程重复执行——比如示例中会向反馈列表添加4个O。

我需要找到一种在循环中跳过已匹配字母的方法。尝试过一个临时解决方案,但它无法处理包含三个相同字母的单词:
if len(userInput) < len(letter): deleted = [] for i in range(len(letter)): l = i + 1 if letter[i] == letter[l]: deleted.append(letter[i]) del letter[i] if len(userInput) > len(letter): for i in range(len(deleted)): l = i + 1 if deleted[i] == deleted[l]: del letter[i] letter.append(deleted)
这个方案只是临时删除部分重复项,无法彻底解决问题。
完整代码
from random_word import Wordnik wordnik_service = Wordnik() truth = True #grabs a random word randWord = wordnik_service.get_random_word(minLength=5, maxLength=5) #starts the while loop until the word has been solved while truth == True: #creates an input in the terminal for the user to submit there word userInput = input("Guess a 5-letter word: ") #defining variables and lists letter = [] trueLett = [] same = False #create for loops to cycle through the user inputed word and the random word to find letters that match for i in range(len(userInput)): for l in range(len(randWord)): #checks if the letters are the same value if randWord[l] == userInput[i]: #checks if the letter are both in the same position if l == i: same = True trueLett.append(randWord[l]) #checks if the letter isn't in the same position elif l != i: letter.append(randWord[l]) l+=1 i+=1 #we don't talk about this italian dish that was cooked by a toddler if len(userInput) < len(letter): deleted = [] for i in range(len(letter)): l = i + 1 if letter[i] == letter[l]: deleted.append(letter[i]) del letter[i] if len(userInput) > len(letter): for i in range(len(deleted)): l = i + 1 if deleted[i] == deleted[l]: del letter[i] letter.append(deleted) if userInput == randWord: print("Correct") truth = False elif userInput == 'Lose': print(randWord) elif len(userInput) > 5 or len(userInput) < 5: print('The word is 5-letters. Please try again') else: print("Incorrect. Try again") if same == True: print("These letter/s: " + str(trueLett) + " are in the correct place") if len(letter) != 0: print("These letter/s: " + str(letter) + " are in the word")
希望能得到可行的解决方案,感谢帮助。
内容的提问来源于stack exchange,提问作者Noah Robb
相关产品推荐
相关产品推荐

