Python Hangman代码修改:实现首次正确猜词提示与重复输入处理
刽子手(Hangman)游戏代码修改方案
需求说明
- 用户首次猜中正确字母时,在显示单词的下方输出提示:
Congrats, You have chosen the right letter! - 重复输入已猜过的字母时,仅输出:
You have already chosen this letter,不显示祝贺文本
修改后的完整代码
import random from replit import clear from hangman_art import logo, stages print(logo) print("\nWelcome to Lucid's Hangman!") from hangman_words import word_list choice = random.choice(word_list) # 测试用:可以注释掉下面这行,正式运行时隐藏答案 print(choice) lives = 6 running = True display = [] for letter in choice: display += "_" # 新增列表记录所有已猜过的字母 guessed_letters = [] while running: guess = input("Guess a letter: ").lower() clear() # 先判断是否重复猜过字母 if guess in guessed_letters: print("You have already chosen this letter") else: guessed_letters.append(guess) # 标记是否首次猜中正确字母 correct_guess = False for position in range(len(choice)): letter = choice[position] if letter == guess: display[position] = letter correct_guess = True print(display) if correct_guess: # 首次猜中时输出祝贺 print("Congrats, You have chosen the right letter!") else: # 猜错时扣减生命 lives -= 1 print("You have chosen a wrong letter. You lose a life") if lives == 0: running = False print("You lose!") # 检查是否获胜 if "_" not in display: running = False print("You have won!") print(stages[lives])
修改说明
- 新增
guessed_letters列表:专门记录所有已经输入过的字母,清晰区分重复猜字母的情况,避免和display列表的判断混淆 - 调整逻辑顺序:先判断是否重复猜字母,再处理猜中/猜错的业务逻辑,流程更清晰
- 首次猜中判断:用
correct_guess标记位,只有当字母是首次猜中且正确时,才输出祝贺文本 - 修正猜错判断逻辑:原代码中
guess not in display的判断会把重复猜正确字母误判为猜错,现在通过correct_guess标记位准确判断猜错场景
内容的提问来源于stack exchange,提问作者LucidKoder
相关产品推荐
相关产品推荐

