You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Hangman猜词游戏guessWord函数异常问题排查求助

Fixing Your Hangman guessWord Function

Let's walk through exactly why your guessWord function isn't working as expected, then fix it to match your desired output.

The Core Issues in Your Current guessWord

Right now, your function only does one thing: asks for a single letter, runs a broken check, then returns immediately. It completely misses all the core hangman logic:

  1. No progress tracking: It never shows the user their current guess state (like ------- or -A----A).
  2. Incorrect letter matching: Your secret words are uppercase (e.g., ABANDON) but you convert the user's guess to lowercase—so userGuess in word will never be true, leading to wrong "already guessed" messages.
  3. No error counter or hangman drawing: It doesn’t track wrong guesses or call hangmanSketch() when the user guesses incorrectly.
  4. No win/lose condition: It never checks if the user has guessed all letters (win) or used up 8 wrong attempts (lose).
  5. No loop for multiple guesses: It exits after one input instead of letting the user keep guessing the same word.

Fixed guessWord Function + Full Updated Code

Here's the corrected version, with comments explaining each key change:

from random import choice

def readDictionary():
    file = open("dictionary.txt", "r")
    # Strip newline characters and standardize to uppercase
    lines = [line.strip().upper() for line in file.readlines()]
    file.close()  # Always close files to avoid resource leaks
    return lines

def hangmanSketch(n):
    if n <= 0:
        pic = ''' --------\n'''
        return pic
    pic = hangmanSketch(n-1)
    if n == 1:
        pic += ''' |\n'''
    elif n == 2:
        pic += ''' O\n'''
    elif n == 3:
        pic += '''_/'''
    elif n == 4:
        pic += '''|'''
    elif n == 5:
        pic += '''\_ \n'''
    elif n == 6:
        pic += ''' |\n'''
    elif n == 7:
        pic += '''_/'''
    elif n == 8:
        pic += ''' \_ \n'''
    return pic

def guessWord(word):
    # Initialize game state variables
    guessed_letters = set()
    wrong_guesses = 0
    # Build initial progress string (all dashes matching word length)
    progress = ["-" for _ in word]
    print(f"Your guess so far: {''.join(progress)}")

    # Loop until user wins or uses all 8 wrong attempts
    while wrong_guesses < 8:
        print("\nGuess a letter from the secret word:")
        userGuess = input().strip().upper()  # Match word's uppercase format

        # Validate input is a single letter
        if len(userGuess) != 1 or not userGuess.isalpha():
            print("Please enter a single letter.")
            continue
        # Check if letter was already guessed
        if userGuess in guessed_letters:
            print("Letter already guessed, try another.")
            continue

        # Add the letter to our guessed set
        guessed_letters.add(userGuess)

        # Handle correct guess
        if userGuess in word:
            # Update progress string with the correct letter
            for idx, char in enumerate(word):
                if char == userGuess:
                    progress[idx] = userGuess
            current_progress = ''.join(progress)
            print(f"Good guess; Your guess so far: {current_progress}")
            # Check if user has completed the word
            if current_progress == word:
                print("Congratulations! You guessed the word!")
                return True
        # Handle wrong guess
        else:
            wrong_guesses += 1
            print("Wrong guess")
            # Draw the current stage of the hangman
            print(hangmanSketch(wrong_guesses))
            print(f"Your guess so far: {''.join(progress)}")

    # If loop exits, user used all 8 wrong attempts
    print(f"Game over! The secret word was {word}.")
    return False

def main():
    print("Welcome to the hangman game.")
    print("You will be guessing words, one letter at a time")
    # Use readDictionary if your file is set up, else use the sample list
    # words = readDictionary()
    words = ['ABANDON', 'INQUIRING', 'LACROSSE', 'REINITIALISED']
    nAttemptedWords = 0
    nGuessedWords = 0
    play = "Y"
    while play == "Y":
        secretWord = choice(words)
        nAttemptedWords += 1
        if guessWord(secretWord):
            nGuessedWords += 1
        # Handle invalid input for play prompt
        while True:
            play = input("Would you like to guess a new word? Y/N: ").strip().upper()
            if play in ["Y", "N"]:
                break
            print("Please enter Y or N.")
    print(f"You guessed {nGuessedWords} words out of {nAttemptedWords}")

if __name__ == "__main__":
    main()

Key Improvements Explained

  1. Game State Tracking: We use a set for guessed_letters to avoid duplicates, a counter for wrong_guesses, and a list progress to build the visible guess string.
  2. Input Handling: Convert user input to uppercase to match the secret word, validate it's a single letter, and check if it's already been guessed.
  3. Win/Lose Logic: After each correct guess, we check if the progress string matches the secret word. After each wrong guess, we increment the counter and draw the hangman, stopping when wrong guesses hit 8.
  4. Better User Feedback: Shows the current guess progress after every move, clear messages for good/wrong guesses, and handles invalid inputs gracefully.
  5. Fixed readDictionary: Strips newline characters from each word and closes the file properly to avoid resource leaks.

This code will now produce the exact output you're expecting, with the hangman sketch updating on wrong guesses and the progress string filling in as you guess correctly.

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

火山引擎 最新活动