import random

# List of words
words_list = ['programming', 'computer', 'hangman', 'language', 'code','rawan','home','key','python']

# Hangman drawings
hangman_pics = [
    '''
     +---+
     |   |
         |
         |
         |
         |
    =========
    ''', '''
     +---+
     |   |
     O   |
         |
         |
         |
    =========
    ''', '''
     +---+
     |   |
     O   |
     |   |
         |
         |
    =========
    ''', '''
     +---+
     |   |
     O   |
    /|   |
         |
         |
    =========
    ''', '''
     +---+
     |   |
     O   |
    /|\  |
         |
         |
    =========
    ''', '''
     +---+
     |   |
     O   |
    /|\  |
    /    |
         |
    =========
    ''', '''
     +---+
     |   |
     O   |
    /|\  |
    / \  |
         |
    =========
    '''
]

def choose_word():
    return random.choice(words_list)

def display_hangman(tries):
    print(hangman_pics[tries])

def play(word):
    word_completion = "_" * len(word)  # Hidden word
    guessed = False
    guessed_letters = []
    tries = 6
    print("Let's play Hangman!")
    print(display_hangman(tries))
    print(word_completion)
    print("\n")
    while not guessed and tries > 0:
        guess = input("Please guess a letter: ").lower()
        if len(guess) == 1 and guess.isalpha():
            if guess in guessed_letters:
                print("You have already guessed that letter.")
            elif guess not in word:
                print(guess, "is not in the word.")
                tries -= 1
                guessed_letters.append(guess)
            else:
                print("Good job!", guess, "is in the word!")
                guessed_letters.append(guess)
                word_as_list = list(word_completion)
                indices = [i for i, letter in enumerate(word) if letter == guess]
                for index in indices:
                    word_as_list[index] = guess
                word_completion = "".join(word_as_list)
                if "_" not in word_completion:
                    guessed = True
        else:
            print("Invalid guess.")
        print(display_hangman(tries))
        print(word_completion)
        print("\n")
    if guessed:
        print("Congratulations, you've guessed the word! You win!")
    else:
        print("Sorry, you've run out of tries. The word was " + word + ". Better luck next time!")

def main():
    word = choose_word()
    play(word)
    while input("Play again? (yes/no) ").lower() == 'yes':
        word = choose_word()
        play(word)

if __name__ == "__main__":
    main()
