Untitled

 avatar
unknown
python
3 years ago
1.7 kB
2
Indexable
import random
import string

words = ['apple', 'mango', 'banana', 'pen', 'normal', 'water', 'sky', 'red']


def get_valid_word(words):
    word = random.choice(words)  # randomly chooses anu word from the list
    return word.upper()


def hangman():
    word = get_valid_word(words)
    word_letters = set(word)  # letters in the word
    alphabet = set(string.ascii_uppercase)
    used_letters = set()  # what the user has guessed

    lives = 7
    while len(word_letters) > 0 and lives > 0:

        # letters used
        print('you have used these letters: ', ' '.join(used_letters))
        print('You have', lives, 'lives left')

        # what current word is (ie W - R D)
        word_list = [
            letter if letter in used_letters else '-' for letter in word]
        print('Current word: ', ' '.join(word_list))

        user_letter = input('Guess a letter: ').upper()

        if user_letter in alphabet - used_letters:
            used_letters.add(user_letter)
            if user_letter in word_letters:
                word_letters.remove(user_letter)
                print('')
            else:
                lives = lives - 1  # takes away a life if wrong
                print('\nYour letter,', user_letter, 'is not in the word.')

        elif user_letter in used_letters:
            print('\nYou have already used that letter. Guess another letter.')

        else:
            print('\nThat is not a valid letter.')

        if lives == 0:
            print('You died, sorry. The word was', word)
        elif len(word_list) == len(word):
            print('YAY! You guessed the word', word, '!!')


hangman()
Editor is loading...