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

基础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_word as len(word)*'_ ', which creates a string like _ _ _ _ _ _ _ (with spaces between underscores). This makes the index positions of new_word misaligned with the original word (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_index variable moves to the next word in word_list once 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:47:18