import random

def choose_word():
    word_list = ["apple", "banana", "orange", "grape", "strawberry", "melon"]
    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 hangman():
    word = choose_word()
    guessed_letters = []
    max_attempts = 6
    attempts = 0
    
    print("Welcome to Hangman!")
    print("Try to guess the word.")

    while attempts < max_attempts:
        print("\n" + display_word(word, guessed_letters))
        guess = input("Guess a letter: ").lower()

        if len(guess) != 1 or not guess.isalpha():
            print("a.")
            continue

        if guess in guessed_letters:
            print("You already guessed that letter.")
            continue

        guessed_letters.append(guess)

        if guess in word:
            print("Correct!")
            if all(letter in guessed_letters for letter in word):
                print("Congratulations! You guessed the word:", word)
                break
        else:
            print("Incorrect!")
            attempts += 1
            print("Attempts left:", max_attempts - attempts)

    if attempts == max_attempts:
        print("\nSorry, you've run out of attempts!")
        print("The word was:", word)

    play_again = input("Do you want to play again? (yes/no): ").lower()
    if play_again == "yes":
        hangman()
    else:
        print("Thanks for playing!")

if __name__ == "__main__":
    hangman()