|
| 1 | +import random |
| 2 | + |
| 3 | +def play_hangman(): |
| 4 | + """Plays a game of Hangman with the user.""" |
| 5 | + |
| 6 | + words = ["python", "javascript", "coding", "developer", "computer", "science", "algorithm", "programming", "github"] |
| 7 | + chosen_word = random.choice(words).lower() |
| 8 | + guessed_letters = [] |
| 9 | + attempts = 6 |
| 10 | + word_display = ["_" for _ in chosen_word] |
| 11 | + |
| 12 | + print("Welcome to Hangman!") |
| 13 | + |
| 14 | + while attempts > 0 and "".join(word_display) != chosen_word: |
| 15 | + print(f"\nWord: {' '.join(word_display)}") |
| 16 | + print(f"Guessed letters: {', '.join(sorted(guessed_letters))}") |
| 17 | + print(f"Attempts remaining: {attempts}") |
| 18 | + |
| 19 | + guess = input("Guess a letter: ").lower() |
| 20 | + |
| 21 | + # Validate input |
| 22 | + if not guess.isalpha() or len(guess) != 1: |
| 23 | + print("Invalid input. Please enter a single letter.") |
| 24 | + continue |
| 25 | + |
| 26 | + if guess in guessed_letters: |
| 27 | + print(f"You've already guessed '{guess}'. Try another letter.") |
| 28 | + continue |
| 29 | + |
| 30 | + guessed_letters.append(guess) |
| 31 | + |
| 32 | + if guess in chosen_word: |
| 33 | + print(f"Good guess! '{guess}' is in the word.") |
| 34 | + for i, letter in enumerate(chosen_word): |
| 35 | + if letter == guess: |
| 36 | + word_display[i] = guess |
| 37 | + else: |
| 38 | + print(f"Sorry, '{guess}' is not in the word.") |
| 39 | + attempts -= 1 |
| 40 | + |
| 41 | + # Game over |
| 42 | + if "".join(word_display) == chosen_word: |
| 43 | + print(f"\nCongratulations! You guessed the word: {chosen_word}") |
| 44 | + else: |
| 45 | + print(f"\nGame Over! You ran out of attempts. The word was: {chosen_word}") |
| 46 | + |
| 47 | +def main(): |
| 48 | + """Main function to run the Hangman game and allow replays.""" |
| 49 | + while True: |
| 50 | + play_hangman() |
| 51 | + play_again = input("Play again? (yes/no): ").lower() |
| 52 | + if play_again != "yes": |
| 53 | + print("Thanks for playing Hangman!") |
| 54 | + break |
| 55 | + |
| 56 | +if __name__ == "__main__": |
| 57 | + main() |
0 commit comments