import random

# List of words to choose from
word_list = ["apple", "banana", "orange", "grape", "kiwi", "mango"]

def choose_word():
    return random.choice(word_list)

def display_word(word, guessed_letters):
    display = ""
    for letter in word:
        if letter in guessed_letters:
            display += letter
        else:
            display += "_"
    return display

def display_hangman(incorrect_guesses):
    stages = [
        """
        +---+
        |   |
            |
            |
            |
            |
      =========
        """,
        """
        +---+
        |   |
        O   |
            |
            |
            |
      =========
        """,
        """
        +---+
        |   |
        O   |
        |   |
            |
            |
      =========
        """,
        """
        +---+
        |   |
        O   |
       /|   |
            |
            |
      =========
        """,
        """
        +---+
        |   |
        O   |
       /|\\  |
            |
            |
      =========
        """,
        """
        +---+
        |   |
        O   |
       /|\\  |
       /    |
            |
      =========
        """,
        """
        +---+
        |   |
        O   |
       /|\\  |
       / \\  |
            |
      =========
        """
    ]
    return stages[incorrect_guesses]

def hangman():
    word = choose_word()
    guessed_letters = []
    incorrect_guesses = 0
    max_attempts = len(display_hangman(0).split('\n')) - 1

    print("Welcome to Hangman!")
    print(display_word(word, guessed_letters))

    while incorrect_guesses < max_attempts:
        guess = input("Guess a letter: ").lower()

        if guess in guessed_letters:
            print("You've already guessed that letter!")
            continue

        guessed_letters.append(guess)

        if guess not in word:
            incorrect_guesses += 1
            print(display_hangman(incorrect_guesses))
        else:
            print("Correct guess!")

        displayed_word = display_word(word, guessed_letters)
        print(displayed_word)

        if "_" not in displayed_word:
            print("Congratulations! You guessed the word!")
            break

    if "_" in displayed_word:
        print("You ran out of attempts! The word was:", word)

    play_again = input("Do you want to play again? (yes/no): ").lower()
    if play_again == "yes":
        hangman()
    else:
        print("Thank you for playing Hangman!")

if __name__ == "__main__":
    hangman()