Python开发Hangman游戏如何仅在选中指定单词时激活对应代码段
Hangman猜单词游戏问题修复方案
核心错误原因
- 所有和
tree相关的判定逻辑没有加当前选中目标单词为tree的前置条件,不管随机抽到的是sun还是tree,只要输入tree都会触发正确判定 - 存在多处冗余重复的
letters == "tree"判断,布尔值拼写错误(Python中布尔值为True不是true)、赋值符号误用(把赋值用的=写成了比较用的==) - 错误输入判定逻辑写法错误,永远无法触发
- 初始的字母猜对提示逻辑写在用户输入循环外,不会生效
修复后完整代码
#hangman mini-project import random import string import time hangmanwords = ['tree','sun'] sunchoices = ['s _ _', '_ u _', '_ _ n'] treechoices = ['t _ _ _', '_ r _ _', ' _ _ e _', '_ _ _ e'] limbCount = 5 hangmanword = random.choice(hangmanwords) if hangmanword == "sun": print(random.choice(sunchoices)) else: print(random.choice(treechoices)) while True: letters = input("Please enter a letter to guess the word: ") print(f"The letter that you chose was {letters}") # 目标单词是tree时才执行tree相关逻辑 if hangmanword == "tree": # 直接猜中完整单词 if letters == "tree": input("Correct! The word was tree! Press enter to play again.") time.sleep(1) break # 猜中单个字母 if letters == "r": print("Nice! You guessed one letter from the word!\n t r _ _") elif letters == "e": print("Wow! You guessed two letters from the word!\n t _ e e") # 猜错字母 elif letters not in ['t','r','e']: print("Sorry, that's not a correct letter, feel free to try again.") limbCount -=1 # 目标单词是sun时才执行sun相关逻辑 elif hangmanword == "sun": # 直接猜中完整单词 if letters == "sun": input("Correct! The word was sun! Press enter to play again.") time.sleep(1) break # 猜中单个字母 if letters == "s": print("Nice! You guessed one letter from the word!\n s _ _") elif letters == "u": print("Nice! You guessed one letter from the word!\n _ u _") elif letters == "n": print("Nice! You guessed one letter from the word!\n _ _ n") # 猜错字母 elif letters not in ['s','u','n']: print("Sorry, that's not a correct letter, feel free to try again.") limbCount -=1 # 耗尽尝试次数 if limbCount == 0: print("Unfortunately, you are out of tries, better luck next time!") time.sleep(1) exit()
关键修改说明
- 给tree、sun对应的处理逻辑分别增加了目标单词匹配的前置判断,目标单词不对时对应逻辑完全不会执行,解决了输入tree在sun局也判定正确的问题
- 删掉了冗余重复的判断代码,修正了布尔值、赋值符号的写法错误
- 调整了错误提示的判定逻辑,现在可以正确识别猜错的字母
- 补充了sun局的猜词逻辑,游戏可以正常运行两个单词的猜词流程
内容的提问来源于stack exchange,提问作者Infui0ayaan
相关产品推荐
相关产品推荐

