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

Hangman游戏Spaces变量显示异常及自动重玩问题排查

解决Hangman游戏的两个问题:Spaces显示异常与回车自动触发重玩

问题描述

我的Hangman游戏几乎能正常运行,但存在两个问题:

  • Spaces变量无法正确显示已猜对的字母
  • 按下回车键后游戏会自动询问是否重玩

错误分析与修复方案

1. Spaces显示异常的修复

  • 变量传递错误:getRandomWord返回的是[单词, 类别]列表,全局代码里原本传了整个列表给displayBoard,导致长度计算错误,应该只传入单词部分
  • 未定义变量误用:displayBoard里替换下划线时误用了未定义的blanks变量,应该用spaces本身拼接字符串

2. 回车自动触发重玩的修复

  • 输入验证逻辑缺失:GetdaGuess里没有跳过无效输入,空输入直接被返回,需要在每个错误判断后添加continue,仅当输入有效时才返回
  • 重复调用输入函数:Play1MoreTime里两次调用input(),第一次输入被丢弃,改为只调用一次并直接判断
  • 游戏结束逻辑错误:主循环里每次猜完都直接标记游戏结束,应该只在猜对所有字母或用完次数时才触发结束
  • 遗漏猜错字母的处理:之前只处理了猜对的情况,猜错时没有把字母加入missedLetters列表
  • 变量名拼写错误:重玩时把gameIsDone拼成了gameIsdone,导致无法重置游戏状态

修复后的完整代码

import random

HANGMANPICS = ['''
  +---+
  |   |
      |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========''', '''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========''']
words={
    'Colors':'red orange yellow green blue indigo violet white black brown'.split(),
    'Shapes':'square triangle rectangle circle ellipse rhombus trapezoid chevron pentagon hexagon septagon octagon'.split(),
    'Fruits':'apple orange lemon lime pear watermelon grape grapefruit cherry banana cantaloupe mango strawberry tomato'.split(),
    'Animals':'bat bear beaver cat cougar crab deer dog donkey duck eagle fish frog goat leech lion lizard monkey moose mouse otter owl panda python rabbit rat shark sheep skunk squid tiger turkey turtle weasel whale wolf wombat zebra'.split()}

def getRandomWord(wordDict):
    wordKey = random.choice(list(wordDict.keys()))
    wordIndex = random.randint(0, len(wordDict[wordKey]) - 1)
    return [wordDict[wordKey][wordIndex], wordKey]
    
def displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord):
    print(HANGMANPICS[len(missedLetters)])
    print()

    print(' Missed letters:', end=' ')
    for letter in missedLetters:
        print(letter, end=' ')
    print()

    spaces = '_' * len(secretWord)

    for i in range(len(secretWord)):
        if secretWord[i] in correctLetters:
            spaces = spaces[:i] + secretWord[i] + spaces[i+1:]

    for letter in spaces:
        print(letter, end=' ')
    print()
    
def GetdaGuess(alreadyGuessed):
    while True:
        print('Pick a letter for the Hangman Game')
        R_I = input().lower()
        if len(R_I) != 1:
            print('Please enter 1 letter only')
            continue
        elif R_I in alreadyGuessed:
            print("You've chosen that letter. Please try again")
            continue
        elif R_I not in 'abcdefghijklmnopqrstuvwxyz':
            print('Only letters please')
            continue
        return R_I
        
def Play1MoreTime():
    guess = input('Would you like to play again?\n').lower()
    return guess.startswith('y')

print('H A N G M A N ')
missedLetters = ''
correctLetters = ''
secretWordInfo = getRandomWord(words)
secretWord = secretWordInfo[0]
gameIsDone = False

while True:
    displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)

    guess = GetdaGuess(missedLetters + correctLetters)

    if guess in secretWord:
        correctLetters += guess
        # 检查是否猜对所有字母
        foundAllDaLetters = True
        for letter in secretWord:
            if letter not in correctLetters:
                foundAllDaLetters = False
                break
        if foundAllDaLetters:
            print(f'Good job. The correct word was {secretWord}.')
            gameIsDone = True
    else:
        missedLetters += guess
        # 检查是否用完次数
        if len(missedLetters) == len(HANGMANPICS) - 1:
            displayBoard(HANGMANPICS, missedLetters, correctLetters, secretWord)
            print(f'You are out of tries.\nAfter {len(missedLetters)} wrong guesses and {len(correctLetters)} correct guesses, the word was "{secretWord}"')
            gameIsDone = True
    
    if gameIsDone:
        if Play1MoreTime():
            missedLetters = ''
            correctLetters = ''
            gameIsDone = False
            secretWordInfo = getRandomWord(words)
            secretWord = secretWordInfo[0]
        else:
            break

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 12:55:13