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

Python猜词游戏Bug:仅错猜应扣血,却每次猜测都扣生命值

猜词游戏生命值扣除逻辑问题排查

问题描述

编写的Python猜词游戏预期仅在用户猜错字母时扣除1点生命值,但实际无论猜对猜错,生命值都会减少1点。

原代码

import random
# Make a list of different animal or anything.
word_list = ["ardvark", "baboon", "camel"]


# Use the random module to randomly pick an animal in the list.
random_word = random.choice(word_list)


# print the choosen word.
print(random_word)


display = ["_" for _ in random_word]

lives = 6

# empty guess.
guess = ''
# empty guess list.

# while loop in display.
while "_" in display:
    # ask the user to guess a letter from the chosen word.
    guess = input("Guess a letter: ").lower()
    # get the range and the len of the chosen word.
    for i in range(len(random_word)):
        # if the letter(guess) is equal to one of the letter in the chosen word.
        if random_word[i] == guess:
            display[i] = random_word[i]
    if random_word != guess:
        lives -= 1
        print(lives)
    # print the display with the right letter.
    print(" ".join(display))

运行结果

RESULTS:
baboon
Guess a letter: b
5
b _ b _ _ _
Guess a letter: r
4
b _ b _ _ _
Guess a letter:

问题分析与修复

错误原因

核心问题在于生命值扣除的判断条件:

if random_word != guess:
    lives -= 1

这里是将整个随机单词和用户输入的单个字母做比较,显然除了单词长度为1的极端情况外,这个条件永远为True,导致每次循环都会扣除生命值,和用户是否猜对无关。

修复方案

将判断条件改为检查用户猜测的字母不在随机单词中时,才扣除生命值:

if guess not in random_word:
    lives -= 1
    print(lives)

修复后的完整代码

import random
# Make a list of different animal or anything.
word_list = ["ardvark", "baboon", "camel"]


# Use the random module to randomly pick an animal in the list.
random_word = random.choice(word_list)


# print the choosen word.
print(random_word)


display = ["_" for _ in random_word]

lives = 6

# empty guess.
guess = ''
# empty guess list.

# while loop in display.
while "_" in display:
    # ask the user to guess a letter from the chosen word.
    guess = input("Guess a letter: ").lower()
    # get the range and the len of the chosen word.
    for i in range(len(random_word)):
        # if the letter(guess) is equal to one of the letter in the chosen word.
        if random_word[i] == guess:
            display[i] = random_word[i]
    # 修改判断条件:仅当猜测的字母不在单词中时扣生命值
    if guess not in random_word:
        lives -= 1
        print(lives)
    # print the display with the right letter.
    print(" ".join(display))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 02:17:04