The purpose of this project is to build a fully functioning Hangman game using Python and understand the code fully as we do bit by bit walkthrough of the code.
Hangman is actually a guessing game where the player will have to guess a word correctly. Usually, the number of guesses is limited by drawing a hanging man. If the guessing player suggests a letter that occurs in the word, the letter is written in all its correct positions. If the suggested letter does not occur in the word, one element of a hanged man stick figure is drawn as a tally mark. If the drawing gets completed before the word is guessed completely, the player loses.
Here, although we won't be drawing anything, rather we will keep track of something called health. For every wrong suggestion, the health gets decreased by 1. The game will be over if the player's health becomes 0 before he/she guesses the word completely. On the other hand, the player wins if he/she can correctly guess the word without losing all of his/her health. It's really a fun game to play. So, let's directly jump into the code!
First, we will make a python file named wordslist.py where we will store a huge list of words. By downloading this project, you can get all the required files. We store the words in a variable named words.
words = ["aback","abaft","abandoned","abashed","aberrant","abhorrent","abiding","abject","ablaze","able","abnormal","aboard","aboriginal","abortive","abounding","abrasive","abrupt","absent","absorbed","absorbing","abstracted","absurd","abundant","abusive","acceptable","accessible","accidental","accurate","acid","acidic","acoustic","acrid","actually","ad hoc","adamant","adaptable","addicted","adhesive","adjoining","adorable","adventurous","afraid","aggressive","agonizing","agreeable","ahead","ajar","alcoholic","alert","alike","alive","alleged","alluring","aloof","amazing","ambiguous","ambitious","amuck","amused","amusing","ancient","angry","animated","annoyed","annoying","anxious","apathetic","aquatic","aromatic","arrogant","ashamed","aspiring","assorted","astonishing","attractive","auspicious","automatic","available","average","awake","aware","awesome","awful","axiomatic","bad","barbarous","bashful","bawdy","beautiful","befitting","belligerent","beneficial",...........................................]
Now, let's create the main file, i.e, hangman.py. We will import some modules like random and string, and also the words from wordslist.
import random from wordslist import words import string
Next, we will define a function named valid_word_generator(words). This function will take the words list as its parameter and perform the job of choosing a valid word from the list.
def valid_word_generator(words): word = random.choice(words) # randomly chooses from the words list while ' ' in word or '-' in word: # the list of words used here contains ' ' or '-' in some cases. Using while loop # to keep on choosing randomly until there is no ' ' or '-' in the chosen word # i.e ensuring that a single valid word is chosen finally word = random.choice(words) return word.upper() # returns the word in all uppercase letters
Next, we will define a function named hangman_game(). This function is responsible for the functioning of the game.
def hangman_game(): # calling the valid_word_generator function to get a valid word word = valid_word_generator(words) # storing the letters of the word in a set such that repeating letters are stored only once letters = set(word) # storing the letters of English alphabets in a set alphabets = set(string.ascii_uppercase) already_used = set() # for storing the letters already guessed by the user in a set health = 7 # the health of the player is set to 7. Player loses if health becomes 0 # code for functioning of the game # the game will be over if player's health reaches 0 before the guessing the word correctly # the player will win if he/she guesses the word completely before losing all of his/her health # the while loop below will continue until the size of the letters set becomes 0 or the health of the player becomes 0 # loop stopping when size of the letters set becomes 0 -> player wins # loop stopping when health becomes 0 -> player loses while len(letters) > 0 and health > 0: if len(already_used) == 0: # for the first iteration when player has not guessed any letter yet print('Your total health =', health) else: print('\nYour health is', health, 'and you have used these letters: ', ' '.join(already_used)) # displaying the health remaining and the letters already guessed by the player
# ' '.join(['hello', 'm', 'cd']) -> 'hello m cd' current_word = [letter if letter in already_used else '-' for letter in word] # current_word constitues of the letters that player has guessed correctly and '-' # for the letters of the words that the player has not guessed yet # ex -> - - N - - A - is the current_word if player has guessed two letters 'N' and 'A' # until now, thereby rest of the places in the word are left blank print('Current word: ', ' '.join(current_word)) # displaying the current_word contents separated by a ' ' input_letter = input('Guess a letter: ').upper() # taking a letter input from the user if input_letter in alphabets - already_used: # if the input letter has not been already guessed, already_used.add(input_letter) # the letter gets added to the already_used if input_letter in letters: # if input letter is present in the word, letters.remove(input_letter) # then letter is correctly guessed and it is removed from the 'letters' set indicating that # all the places in the word containing that letter has been filled and rest of the contents of the # letters set need to be guessed further # ** size of letters set becoming 0 indicates that the word has been guessed completely ** else: # if input letter is not present in word, guess is wrong health = health - 1 # health decreases by 1 due to wrong guess print('Your letter,', input_letter, 'is not in the word.') elif input_letter in already_used: # if letter has been already guessed by the user print('You have already used that letter. Guess another letter.') else: # if the letter is not present in English alphabet print('That is not a valid letter.') if health == 0: # at the end check whether the health is 0 print('You died! The word was', word) else: # if word is guessed completely without losing all health print('Congrats! You win! You guessed the word', word, '!!')
Finally, the driver-code:
# driver code if __name__ == '__main__': hangman_game()
G:\CodeSpeedy Internship\Submission 2>python hangman.py Your total health = 7 Current word: - - - - Guess a letter: o Your letter, O is not in the word. Your health is 6 and you have used these letters: O Current word: - - - - Guess a letter: e Your letter, E is not in the word. Your health is 5 and you have used these letters: O E Current word: - - - - Guess a letter: i Your letter, I is not in the word. Your health is 4 and you have used these letters: O E I Current word: - - - - Guess a letter: a Your health is 4 and you have used these letters: A O E I Current word: - A - - Guess a letter: s Your letter, S is not in the word. Your health is 3 and you have used these letters: A S E I O Current word: - A - - Guess a letter: g Your letter, G is not in the word. Your health is 2 and you have used these letters: A S E I O G Current word: - A - - Guess a letter: n Your health is 2 and you have used these letters: A S E I O N G Current word: - A N - Guess a letter: g You have already used that letter. Guess another letter. Your health is 2 and you have used these letters: A S E I O N G Current word: - A N - Guess a letter: d Your health is 2 and you have used these letters: A S D E I O N G Current word: - A N D Guess a letter: s You have already used that letter. Guess another letter. Your health is 2 and you have used these letters: A S D E I O N G Current word: - A N D Guess a letter: n You have already used that letter. Guess another letter. Your health is 2 and you have used these letters: A S D E I O N G Current word: - A N D Guess a letter: h Congrats! You win! You guessed the word HAND !!