Python入门:Hangman猜字游戏已猜字母未保留显示问题求助
Fixing Your Hangman Game & Stack Overflow Tips
Hey there! Congrats on diving into Python projects after just a week—Hangman is a great (and tricky) choice. Let's fix that "correct letters not staying visible" issue first, then I'll share some tips to make your Stack Overflow questions even more effective.
First: Fixing the Letter Persistence Problem
The main issue is your code isn't tracking all previously guessed letters—right now it only checks the current input each time. Here's how to adjust it, plus fix a few other small bugs:
Modified Working Code
import random name = input("Please enter your name to play Hangman! ") print(f"Welcome {name}! Let's play Hangman.") # Set default to 6 if user doesn't enter a valid number (optional but user-friendly) try: wrong_attempt = int(input("How many incorrect attempts do you want? ")) except ValueError: wrong_attempt = 6 print("Using default 6 attempts.") # Read the secret word and remove any extra newline/whitespace with open('words.csv', "r") as f: secret_word = f.readline().strip() # Initialize display with asterisks for each letter in the secret word display = ['*'] * len(secret_word) guessed_letters = set() # Track all guessed letters to avoid repeats while wrong_attempt > 0: # Print current progress first print("\nCurrent word: " + ''.join(display)) letter = input("Guess a letter: ").lower() # Make input case-insensitive # Handle repeated guesses if letter in guessed_letters: print(f"You already guessed '{letter}'! Try another one.") continue guessed_letters.add(letter) # Check if the letter is in the secret word if letter in secret_word: # Update display to show the correct letter(s) for idx, char in enumerate(secret_word): if char == letter: display[idx] = letter # Check if user has won if '*' not in display: print(f"\nCongratulations {name}! You won! The word was {secret_word}") break else: wrong_attempt -= 1 print(f"Bad luck! That's not in the word. You have {wrong_attempt} attempts left.") # If loop ends because no attempts left else: print(f"\nGame over! You lose. The secret word was {secret_word}")
Key Changes Explained:
- Tracking Correct Letters: We use a
displaylist to hold asterisks and replace them with correct letters as they're guessed—this keeps your progress visible between turns. - Avoid Repeats: A
guessed_lettersset stops users from guessing the same letter twice (no need to penalize them for that!). - Win Condition: We check if there are no more asterisks in
display—if so, the user wins and the game ends early. - Input Handling: Added case-insensitivity (so 'C' and 'c' count the same) and a fallback for invalid attempt numbers.
- Clean Word Reading:
strip()removes any extra newline characters from the CSV file, so your secret word doesn't have hidden whitespace.
Tips for Asking Great Stack Overflow Questions
Since you're new to asking on SO, here are some quick pointers to get better, faster answers:
- Write a Clear Title: Instead of something vague like "Hangman game problem", use specific language like "Python Hangman: Correctly guessed letters don't persist between guesses".
- Show Exact Expected vs. Actual Output: For example: "When I guess 'c' then 'o', I expect to see 'co****', but I get 'o***' instead." This helps others immediately understand the issue.
- Include Minimal, Reproducible Code: Your original code was great because it's complete—but if your
words.csvhas a specific format (like one word per line), mention that so others can replicate your setup easily. - State What You've Tried: Mention that you tried using a
guessesvariable but weren't sure how to implement it—this shows you've put in effort and helps others avoid repeating what you already know. - Format Your Code Properly: You already used code blocks, which is perfect! Never paste unformatted code—it's hard to read.
内容的提问来源于stack exchange,提问作者user11585954
相关产品推荐
相关产品推荐

