└── Rat_Rod.py /Rat_Rod.py: -------------------------------------------------------------------------------- 1 | # Python Program to illustrate 2 | # Hangman Game 3 | import random 4 | from collections import Counter 5 | 6 | someWords = '''apple banana mango strawberry 7 | orange grape pineapple apricot lemon coconut watermelon 8 | cherry papaya berry peach lychee muskmelon''' 9 | 10 | someWords = someWords.split(' ') 11 | # randomly choose a secret word from our "someWords" LIST. 12 | word = random.choice(someWords) 13 | 14 | if __name__ == '__main__': 15 | print('Guess the word! HINT: word is a name of a Car') 16 | 17 | for i in word: 18 | # For printing the empty spaces for letters of the word 19 | print('_', end = ' ') 20 | print() 21 | 22 | playing = True 23 | # list for storing the letters guessed by the player 24 | letterGuessed = '' 25 | chances = len(word) + 2 26 | correct = 0 27 | flag = 0 28 | try: 29 | while (chances != 0) and flag == 0: #flag is updated when the word is correctly guessed 30 | print() 31 | chances -= 1 32 | 33 | try: 34 | guess = str(input('Enter a letter to guess: ')) 35 | except: 36 | print('Enter only a letter!') 37 | continue 38 | 39 | # Validation of the guess 40 | if not guess.isalpha(): 41 | print('Enter only a LETTER') 42 | continue 43 | else if len(guess) > 1: 44 | print('Enter only a SINGLE letter') 45 | continue 46 | else if guess in letterGuessed: 47 | print('You have already guessed that letter') 48 | continue 49 | 50 | 51 | # If letter is guessed correctly 52 | if guess in word: 53 | k = word.count(guess) #k stores the number of times the guessed letter occurs in the word 54 | for _ in range(k): 55 | letterGuessed += guess # The guess letter is added as many times as it occurs 56 | 57 | # Print the word 58 | for char in word: 59 | if char in letterGuessed and (Counter(letterGuessed) != Counter(word)): 60 | print(char, end = ' ') 61 | correct += 1 62 | # If user has guessed all the letters 63 | else if (Counter(letterGuessed) == Counter(word)): # Once the correct word is guessed fully, 64 | # the game ends, even if chances remain 65 | print("The word is: ", end=' ') 66 | print(word) 67 | flag = 1 68 | print('Congratulations, You won!') 69 | break # To break out of the for loop 70 | break # To break out of the while loop 71 | else: 72 | print('_', end = ' ') 73 | 74 | 75 | 76 | # If user has used all of his chances 77 | if chances <= 0 and (Counter(letterGuessed) != Counter(word)): 78 | print() 79 | print('You lost! Try again..') 80 | print('The word was {}'.format(word)) 81 | 82 | except KeyboardInterrupt: 83 | print() 84 | print('Bye! Try again.') 85 | exit() 86 | --------------------------------------------------------------------------------