如何根据用户响应实现Python命令行Wordle程序重启
Wordle命令行游戏重开功能实现方案
问题说明
需要为命令行版本Wordle猜词游戏增加对局结束后询问玩家是否继续的功能,玩家确认后自动开启新局。此前尝试调整缩进、封装函数、添加while循环的方式均出现运行无输出的问题,原有代码如下:
import random from colorama import Fore, Back, Style print("Guess My Word - Based on TextBasedWordle by DrVictor") print("") def processGuess(theAnswer, theGuess): position = 0 clue = "" for letter in theGuess: if letter == theAnswer[position]: clue += u"\u2714 " elif letter in theAnswer: clue += Fore.YELLOW + u"\uFF0D " + Style.RESET_ALL else: clue += Fore.RED + u"\u274C " + Style.RESET_ALL position += 1 print(clue) print("") return clue == u"\u2714 "u"\u2714 "u"\u2714 "u"\u2714 "u"\u2714 " # true if correct, false otherwise # load words and store them into a list word_list = [] word_file = open("target_words.txt") for word in word_file: word_list.append(word.strip()) # pick a word answer = random.choice(word_list) num_of_guesses = 0 guessed_correctly = False while num_of_guesses < 6 and not guessed_correctly: # get guess from user guess = input("Input a 5-letter word and press enter: ") print("You have guessed", guess) num_of_guesses += 1 print(6 - num_of_guesses, "guesses remaining") # process guess guessed_correctly = processGuess(answer, guess) # display end of game message if guessed_correctly: print("Congratulations, you guessed the word correctly with", num_of_guesses, "guesses.") else: print("You have used up all your guesses. The correct word was", answer)
故障原因
此前实现失败的核心问题是没有拆分全局逻辑和单局逻辑:随机选答案、初始化猜词计数、猜词循环这些单局专属逻辑直接写在全局作用域,只会在程序启动时执行一次;外层新增循环时如果没有把这些单局初始化逻辑放进循环体,就会出现要么不循环、要么循环时变量状态异常导致无输出的问题。
修复后代码
核心改动点:
- 把单局完整流程封装为
run_single_game()函数,每调用一次就开启全新对局 - 最外层增加主循环,对局结束后询问玩家意愿,输入
y则重开,输入n则退出 - 补充输入合法性校验,避免异常输入打断程序
- 优化文件读取写法,避免文件句柄泄漏
- 简化猜对判断逻辑,避免硬编码拼接符号容易出错的问题
import random from colorama import Fore, Style # 欢迎信息仅在程序启动时打印一次 print("Guess My Word - Based on TextBasedWordle by DrVictor") print("") def processGuess(theAnswer, theGuess): position = 0 clue = "" for letter in theGuess: if letter == theAnswer[position]: clue += u"\u2714 " elif letter in theAnswer: clue += Fore.YELLOW + u"\uFF0D " + Style.RESET_ALL else: clue += Fore.RED + u"\u274C " + Style.RESET_ALL position += 1 print(clue) print("") # 清除颜色转义字符后判断是否全对,避免硬编码拼接出错 plain_clue = clue.replace(Fore.YELLOW, "").replace(Fore.RED, "").replace(Style.RESET_ALL, "").strip() return plain_clue == u"\u2714 \u2714 \u2714 \u2714 \u2714" def run_single_game(word_list): # 每局重新随机选答案、重置猜词计数 answer = random.choice(word_list) num_of_guesses = 0 guessed_correctly = False while num_of_guesses < 6 and not guessed_correctly: guess = input("Input a 5-letter word and press enter: ").strip() # 输入长度校验,不符合要求直接重输,不扣猜词次数 while len(guess) != 5: guess = input("Invalid input, please enter a 5-letter word: ").strip() print(f"You have guessed {guess}") num_of_guesses += 1 print(f"{6 - num_of_guesses} guesses remaining") guessed_correctly = processGuess(answer, guess) # 单局结算 if guessed_correctly: print(f"Congratulations, you guessed the word correctly with {num_of_guesses} guesses.") else: print(f"You have used up all your guesses. The correct word was {answer}") if __name__ == "__main__": # 词表仅在程序启动时加载一次,无需每局重复读文件 word_list = [] # 用上下文管理自动关闭文件 with open("target_words.txt", "r", encoding="utf-8") as f: for word in f: stripped_word = word.strip() if len(stripped_word) == 5: # 过滤词表中不符合长度的异常行 word_list.append(stripped_word) # 主循环控制重开逻辑 while True: run_single_game(word_list) # 校验重开输入 while True: play_again = input("Start a new game? (y/n): ").strip().lower() if play_again in ["y", "n"]: break print("Invalid input, please enter y or n") if play_again == "n": print("Game over, thanks for playing!") break
内容的提问来源于stack exchange,提问作者shuaXII
相关产品推荐
相关产品推荐

