Hangman项目问题:仅猜错字母时增加生命值并打印吊图
修正Hangman游戏的猜错判断逻辑
你的代码核心问题在于判断用户猜错的条件错误——你用了循环最后一个字母letter和用户猜测比较,这完全不靠谱,因为循环结束后letter只是单词的最后一个字符,和用户猜测的匹配与否不能代表整个单词是否包含该字母。
下面是修正后的完整代码,关键修改点我会标注出来:
import random import gamename import hangmanpics import wordslist print(gamename.hangman_log) word_choice = random.choice(wordslist.random_words) # 调试用的打印可以注释掉,正式玩的时候别显示答案 # print(word_choice) word_length = len(word_choice) display = [] lives = 0 for letter in word_choice: display += "_" print(''.join(display)) end_game = False while not end_game: user_guess = input("Guess a letter in word: ") correct_guess = False # 新增:标记是否猜对字母 for position in range(word_length): letter = word_choice[position] if user_guess == letter: display[position] = letter correct_guess = True # 猜对了就把标记设为True # 修改:只有没猜对的时候才增加生命值、打印吊图 if not correct_guess: lives += 1 print(hangmanpics.HANGMANPICS[lives]) if lives == 6: end_game = True print("You lost") print(f"The word was: {word_choice}") # 修正:用原始单词变量避免未定义问题 if "_" not in display: end_game = True print('You won') current_display = ''.join(display) print(f"The word is: {current_display}")
关键修改说明:
- 新增
correct_guess布尔变量:用来记录本次猜测是否命中单词里的字母,循环遍历单词时只要找到匹配项就把它设为True - 替换猜错判断条件:从错误的
if user_guess != letter改成if not correct_guess,确保只有当用户猜的字母完全不在单词里时,才执行增加生命值、打印吊图的逻辑 - 修正失败提示的单词变量:原代码里
print(f"the word is{word}")中的word是在后面才赋值的,直接用原始的word_choice更准确 - 可选优化:注释掉调试用的
print(word_choice),正式游戏时不要提前显示答案
这样就能实现你要的逻辑:猜对字母时不改变生命值、不打印吊图;猜错时才增加生命值并显示对应吊图,直到6次错误后游戏结束。
内容的提问来源于stack exchange,提问作者Felonzo
相关产品推荐
相关产品推荐

