You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Hangman游戏重复输入字母扣除2次生命值问题求助

Hangman游戏重复输入扣两次生命的修复方案

问题根源

你当前的代码逻辑存在顺序问题:重复输入字母时,if guess in duplicate会先扣一次生命,之后if guess not in chosen_word的判断依然会执行——如果是错误字母的重复输入,就会触发两次扣生命的逻辑;哪怕是正确字母重复输入,后续的流程也会产生不必要的判断。核心解决思路是把重复输入的判断优先级拉到最高,一旦检测到重复,直接跳过后续的正确/错误猜测判定。

修复后的完整代码

import time
import random

# 初始化游戏
print("Welcome to HANGMAN")
user = input("\nWhat's Your Name : ")
print(f"\nHello {user}! Best Of Luck")
x = input("\nReady to play??? : ")

# 简化开始游戏的判断逻辑
if x.lower() in ["yes", "y"]:
    print("\nGame Loading in \n3..2..1")
else:
    print("\nOk Sadly ending the game!! BYE BYE")
    exit()

print("\nGame Start!!")
print("\nRules as follows :-")
print("1. Guess the right word letter by letter.")
print("2. You only got 6 lives.")
print("3. Do not repeat the same alphabet entry it will reduce your life.")
print("4. Enjoy the game.")

# 游戏核心变量初始化
word_list = ["TIGER", "ELEPHANT", "LION", "CAT", "DOG", "HORSE"]
chosen_word = random.choice(word_list)
length = len(chosen_word)
display = ["_"] * length
in_game = True
lives = 6
duplicate = []

# 游戏主循环
while in_game:
    guess = input("\nCome On Guess a word letter by letter : ").upper()

    # 1. 优先判断是否重复输入
    if guess in duplicate:
        lives -= 1
        print(f"\n{user} Do not repeat same alphabet entry. A LIFE LOST due to repeated entry.")
        if lives == 0:
            in_game = False
            print(f"\n{user} You lost all your life, YOU LOSE.")
    else:
        # 2. 未重复输入时,才处理猜测逻辑并记录字母
        duplicate.append(guess)
        
        correct_guess = False
        # 遍历单词检查是否猜中
        for position in range(length):
            letter = chosen_word[position]
            if letter == guess:
                correct_guess = True
                display[position] = letter
                print(f"\nYou guessed {guess} which is the right alphabet!!")
        
        print(" ".join(display))

        # 处理错误猜测
        if not correct_guess:
            print(f"\nYou guessed {guess} which is not the alphabet, life lost.")
            lives -= 1
            if lives == 0:
                in_game = False
                print(f"\nTry next time {user}, You lost all your life, YOU LOSE.")
        
        # 检查是否获胜
        if "_" not in display:
            in_game = False
            print(f"\nCongrats {user} You WIN.")
    
    # 打印当前生命对应的阶段图
    from hangman_art import stages
    print(stages[lives])

关键修改点

  • 逻辑顺序调整:将重复输入的判断放在最前端,避免后续逻辑重复扣生命
  • 重复输入处理优化:仅在输入未重复时,才将字母加入duplicate列表,避免提前加入导致的误判
  • 新增correct_guess标记:用布尔变量统一记录是否猜中正确字母,减少冗余的单词遍历判断
  • 简化输入判断:用x.lower() in ["yes", "y"]替代多个or判断,代码更简洁易读
  • 输出格式统一:规整print语句的换行与内容格式,让游戏输出更清晰

内容的提问来源于stack exchange,提问作者Numan147

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 15:45:57