|
| 1 | +""" |
| 2 | +A classic word-guessing game: Hangman. |
| 3 | +The computer picks a secret word, and the player tries to guess it letter by letter. |
| 4 | +""" |
| 5 | + |
| 6 | +import random |
| 7 | + |
| 8 | + |
| 9 | +def play_hangman() -> None: |
| 10 | + """ |
| 11 | + Starts an interactive session of Hangman. |
| 12 | + This function is interactive and does not have a testable return value. |
| 13 | + """ |
| 14 | + words = ["python", "github", "algorithm", "developer", "computer"] |
| 15 | + secret_word = random.choice(words) |
| 16 | + guessed_letters = set() |
| 17 | + incorrect_guesses = 0 |
| 18 | + max_attempts = 6 |
| 19 | + |
| 20 | + print("Welcome to Hangman!") |
| 21 | + |
| 22 | + while incorrect_guesses < max_attempts: |
| 23 | + # Display the current state of the word |
| 24 | + display_word = "".join( |
| 25 | + letter if letter in guessed_letters else "_" for letter in secret_word |
| 26 | + ) |
| 27 | + print(f"\nWord: {display_word}") |
| 28 | + print(f"Incorrect guesses left: {max_attempts - incorrect_guesses}") |
| 29 | + |
| 30 | + if display_word == secret_word: |
| 31 | + print(f"Congratulations! You guessed the word: {secret_word}") |
| 32 | + return |
| 33 | + |
| 34 | + guess = input("Guess a letter: ").lower() |
| 35 | + |
| 36 | + if len(guess) != 1 or not guess.isalpha(): |
| 37 | + print("Please enter a single letter.") |
| 38 | + continue |
| 39 | + |
| 40 | + if guess in guessed_letters: |
| 41 | + print("You already guessed that letter.") |
| 42 | + elif guess in secret_word: |
| 43 | + print("Good guess!") |
| 44 | + guessed_letters.add(guess) |
| 45 | + else: |
| 46 | + print("Sorry, that letter is not in the word.") |
| 47 | + incorrect_guesses += 1 |
| 48 | + guessed_letters.add(guess) |
| 49 | + |
| 50 | + print(f"\nGame over! The word was: {secret_word}") |
| 51 | + |
| 52 | + |
| 53 | +if __name__ == "__main__": |
| 54 | + play_hangman() |
0 commit comments