hHi

mail@pastecode.io avatar
unknown
python
a year ago
1.6 kB
5
Indexable
Never
import random

def choose_random_word():
    words = ["apple", "banana", "cherry", "dragon", "elephant", "flamingo", "grape", "honey", "iguana", "jungle"]
    return random.choice(words)

def play_hangman():
    secret_word = choose_random_word()
    guessed_letters = []
    attempts = 6

    print("Welcome to Hangman!")
    print("You have 6 attempts to guess the secret word.")

    while attempts > 0:
        display_word = ""
        for letter in secret_word:
            if letter in guessed_letters:
                display_word += letter
            else:
                display_word += "_"

        print("Current word:", display_word)
        print("Guessed letters:", ", ".join(guessed_letters))

        guess = input("Guess a letter: ").lower()

        if len(guess) != 1 or not guess.isalpha():
            print("Invalid input. Please enter a single letter.")
            continue

        if guess in guessed_letters:
            print("You've already guessed that letter.")
            continue

        guessed_letters.append(guess)

        if guess in secret_word:
            print("Correct guess!")
        else:
            print("Incorrect guess. You have", attempts - 1, "attempts left.")
            attempts -= 1

        if all(letter in guessed_letters for letter in secret_word):
            print("Congratulations! You guessed the word:", secret_word)
            break

    if attempts == 0:
        print("Game over. The secret word was:", secret_word)

if __name__ == "__main__":
    play_hangman()