基础Hangman游戏代码求助:答对后换词及单词显示异常问题
Fixing Your Hangman Game Issues
Let's break down and fix the two problems in your code—first the broken word display, then the lack of word replacement after winning:
1. Why the Word Isn't Displaying Correctly
Your core issue here is how you're updating the displayed word:
- You initialized
new_wordaslen(word)*'_ ', which creates a string like_ _ _ _ _ _ _(with spaces between underscores). This makes the index positions ofnew_wordmisaligned with the originalword(since every other character is a space). - Using
new_word.replace(new_word[i], letter)does a global replace, meaning it changes every_in the string to the guessed letter—instead of only the positions where the letter actually appears in the word.
2. Fixing the Word Display & Adding Word Replacement
Here's the revised code with fixes and quality-of-life improvements, plus support for multiple words/playing again:
def hangman(): # Expand this list with more words to play through multiple rounds word_list = ['weekend', 'python', 'hangman', 'developer'] current_word_index = 0 while current_word_index < len(word_list): word = word_list[current_word_index] incorrect_attempts = 0 max_incorrect = 6 # Standard hangman lives guessed_letters = set() # Use a list to track displayed characters (mutable, easy to update) display_chars = ['_'] * len(word) print("\nNew round! Let's play Hangman.") print(' '.join(display_chars)) while incorrect_attempts < max_incorrect: # Clean up user input (handle uppercase, extra spaces) guess = input('Enter a letter: ').lower().strip() # Validate input if len(guess) != 1 or not guess.isalpha(): print("Please enter a single letter (A-Z)!") continue if guess in guessed_letters: print(f"You already guessed '{guess}'—try another one!") continue guessed_letters.add(guess) # Check if the guess is correct if guess in word: # Update only the positions where the letter exists for idx, char in enumerate(word): if char == guess: display_chars[idx] = guess # Check if the player won this round if '_' not in display_chars: print(f"\nYou won! The word was '{word}'.") current_word_index += 1 # Move to next word break else: incorrect_attempts += 1 remaining_tries = max_incorrect - incorrect_attempts print(f"Wrong guess! You have {remaining_tries} tries left.") # Show current progress print(' '.join(display_chars)) # If player ran out of tries if incorrect_attempts >= max_incorrect: print(f"\nGame over! The word was '{word}'.") # Optionally reset to first word or let player quit play_again = input("Want to try again? (y/n): ").lower().strip() if play_again == 'y': current_word_index = 0 else: break # After all words are played play_again = input("\nAll words done! Want to play again? (y/n): ").lower().strip() if play_again == 'y': hangman() hangman()
Key Fixes & Improvements
- Proper word updating: Uses a list (
display_chars) to track underscores/guessed letters, so we can modify specific positions instead of doing global replaces. - Word replacement after winning: The
current_word_indexvariable moves to the next word inword_listonce the player wins a round. - Input validation: Ensures users enter valid single letters and don't repeat guesses.
- Standard hangman rules: Uses 6 incorrect attempts (classic hangman "lives") instead of 20, which feels more intuitive.
- Replayability: Asks the player if they want to restart after losing or finishing all words.
内容的提问来源于stack exchange,提问作者M.Papapetros
相关产品推荐
相关产品推荐

