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:
- No progress tracking: It never shows the user their current guess state (like
-------or-A----A). - Incorrect letter matching: Your secret words are uppercase (e.g.,
ABANDON) but you convert the user's guess to lowercase—souserGuess in wordwill never be true, leading to wrong "already guessed" messages. - No error counter or hangman drawing: It doesn’t track wrong guesses or call
hangmanSketch()when the user guesses incorrectly. - No win/lose condition: It never checks if the user has guessed all letters (win) or used up 8 wrong attempts (lose).
- 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
- Game State Tracking: We use a set for
guessed_lettersto avoid duplicates, a counter forwrong_guesses, and a listprogressto build the visible guess string. - 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.
- 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.
- Better User Feedback: Shows the current guess progress after every move, clear messages for good/wrong guesses, and handles invalid inputs gracefully.
- 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




