Python Hangman游戏开发问题:如何将正确猜测的字母替换对应位置的下划线
Hey there! Great start on your Hangman game—let's get that dash replacement working first, then walk through some tweaks to make your code cleaner and more robust.
Core Fix: Replacing Dashes with Correct Letters
You're already correctly finding the positions of the guessed letter with letListPlus—we just need to use those indices to update your lenghtDashes list (quick note: you might want to fix the spelling to lengthDashes for better readability!).
Here's where to add the update logic in your letter-guessing branch:
elif guessThing == "l": letList = list(secWord) # Simplified from list comprehension guLett = input("Guess the letter \n(single letter only): ") usedLetters.append(guLett) if guLett in letList: guessedLetters.append(guLett) letListPlus = [letter for letter, x in enumerate(letList) if x == guLett] letListPlusPlus = [num + 1 for num in letListPlus] # THIS IS THE NEW CODE TO UPDATE DASHES for idx in letListPlus: lenghtDashes[idx] = guLett # Update the displayed string and print it appended = "".join(lenghtDashes) print(f"Current word: {appended}") print("///") print("Letters that you have used : " + str(usedLetters)) print("Letter that are correct: " + str(guessedLetters)) print(f"The position of letter {guLett} is {letListPlusPlus}") # Check if the player has won by guessing all letters if appended == secWord: print("Congratulations, you've guessed all letters!\nYou won!") break
This loop goes through each index where the guessed letter appears in the secret word and replaces the corresponding underscore in lenghtDashes. We then rejoin the list into a string and display it so the player can see their progress. We also add a check to end the game if all letters are guessed correctly.
Optimization Suggestions
Let's make your code cleaner and more user-friendly with these tweaks:
- Fix variable names:
lenghtDashes→lengthDashes,guLett→guessed_letter(snake_case is standard in Python for readability). - Reduce repeated code: The dot-printing loops can be turned into a function:
Then calldef print_delay_dots(): i = 1 while i < 10: print(".") i += 0.01print_delay_dots()instead of repeating the loop twice. - Input validation:
- For letter guesses: Ensure the input is a single alphabetic character (not numbers, symbols, or multiple letters). Example:
while True: guLett = input("Guess the letter \n(single letter only): ").strip().lower() if len(guLett) == 1 and guLett.isalpha(): break print("Please enter a single valid letter!") - Make the game case-insensitive by converting the secret word and all guesses to lowercase:
secWord = input("What is the word for others to guess?: ").strip().lower()
- For letter guesses: Ensure the input is a single alphabetic character (not numbers, symbols, or multiple letters). Example:
- Improve game end conditions: Your current loop uses
ans != secWord, butansonly gets updated when guessing a full word. Instead, check if the displayed dashes match the secret word (like we did in the core fix) to handle letter-only wins. - Avoid
exit(): Instead of usingexit()when the player guesses the wrong word, setlife = 0and let the loop terminate naturally, then print the loss message after the loop. - Use f-strings for cleaner formatting: Replace string concatenation like
print("the word has " + str(len(secWord)) + " letters.")withprint(f"The word has {len(secWord)} letters.").
Full Modified Code
Here's the complete code with all fixes and optimizations applied:
def print_delay_dots(): i = 1 while i < 10: print(".") i += 0.01 secWord = input("What is the word for others to guess?: ").strip().lower() life = 10 print_delay_dots() print("You have 10 tries to guess the word") print("You will have to choose between guessing a letter (l) or a word (w) at the start of every turn") print("However, if you guess the word incorrectly you will lose immediately") ans = input("Are you ready to begin?: ").strip().lower() while ans != "yes": ans = input("Now? ").strip().lower() print_delay_dots() lengthDashes = ["_" for _ in range(len(secWord))] # Simplified list creation print("Let's begin") print(f"The word has {len(secWord)} letters.") appended = "".join(lengthDashes) print(appended) usedLetters = [] guessedLetters = [] while life > 0 and appended != secWord: print("\nAre you guessing a letter or a word?") guessThing = input("l / w : ").strip().lower() # For guessing a word if guessThing == "w": ans = input("What is the secret word?: ").strip().lower() if ans == secWord: print("Congratulations, you have guessed the right word\nYou won!") break else: life = 0 # Trigger loop exit # For guessing a letter elif guessThing == "l": # Input validation for single letter while True: guessed_letter = input("Guess the letter \n(single letter only): ").strip().lower() if len(guessed_letter) == 1 and guessed_letter.isalpha(): break print("Please enter a single valid letter!") if guessed_letter in usedLetters: print(f"You've already guessed '{guessed_letter}'! Try another one.") continue usedLetters.append(guessed_letter) letList = list(secWord) if guessed_letter in letList: guessedLetters.append(guessed_letter) letter_positions = [idx for idx, char in enumerate(letList) if char == guessed_letter] human_readable_positions = [pos + 1 for pos in letter_positions] # Update dashes with correct letter for idx in letter_positions: lengthDashes[idx] = guessed_letter appended = "".join(lengthDashes) print("\n///") print(f"Current word: {appended}") print(f"Letters you have used: {usedLetters}") print(f"Correct letters: {guessedLetters}") print(f"The position of letter '{guessed_letter}' is {human_readable_positions}") else: life -= 1 print("\n///") print(f"Incorrect guess, you have {life} guesses remaining") print(f"Letters you have used: {usedLetters}") print(f"Correct letters: {guessedLetters}") else: print("Invalid input! Please enter 'l' or 'w'.") # After loop ends, check if player lost if life == 0: print(f"\nYou lost! The secret word was '{secWord}'")
This version fixes the dash replacement, adds input validation, cleans up variable names, and makes the game flow smoother.
内容的提问来源于stack exchange,提问作者HMNNikoloz

