Creating a Simple Hangman Game in Python

In this tutorial, we will look at one of the ways to make the classic word guessing game ‘Hangman’.

The Python concepts that we will use in this game are: strings, loops, conditional (If/else) statements, lists, and functions. We will also make use of the random and time module.
Step 1: Importing Modules

First, we will import ‘random‘ and ‘timemodules. The ‘choice()‘ method from the ‘random’ module will be used to pick random words from our word lists and the ‘sleep()‘ method from the time module will be used to introduce delays where needed.

STEP 2: Create word-lists and variables

Next, we will create our word list(s) that will be used by the program to pick words randomly for the players to guess. I created two lists in this program: the first one has fruit names and the second one consists of superhero names. The two lists were created to give the players the option of picking the category for the word they would like to guess. You can make one or more word lists depending on the number of categories you want to add in the game.

We will create a few variables to store the game statistics:

STEP 3: Game-Info

We will prompt the player for their name and store it in a variable. Before starting the game, we display some details about the game. Here we are using the time module’s ‘sleep()‘ method to pause for a few seconds between the displays.

STEP 4: Choosing a random word from the desired category

Next, we will add the logic to allow the program to choose a random word from the desired category. This is how the code looks like.

Here we will make use of the while loop and if/elif/else conditionals to pick the random word. The players are given an option to choose a category (Fruits / Superheroes) for the word they would like to guess. An option to exit the game is also provided, in case they decide not to play.

The if block of the code will be executed if the player chooses ’S’ indicating that they want to play the game with words from the ‘superhero’ category. In this case, a word from the superHeroes list will be picked randomly using the ‘random.choice‘ from ‘random‘ module. The word will then be stored in the secretWord variable.

The elif (else if) block of the code will be executed if the player chooses ’F’ indicating that they want to play the game with words from the ‘fruit’ category. In this case, a word from the fruits list will be picked randomly using the ‘random.choice‘ from the ‘random‘ module and stored in the secretWord variable.

NOTE: In case you have more word categories, you can add corresponding elif blocks similar to this.

If the player chooses any other letter apart from ’S’ / ‘F’, the player will be prompted to select a valid category (’S’ or ‘F’) or ‘X’ to exit. Note the use of ‘upper()’ for converting the input to upper case before validating the category. Since we want to force the player to select a correct option or exit the game, we will wrap our if/elif/else block inside a while True (forever loop) block. We are using the keyword break to break out of the loop once the right option is chosen.

The else block will be executed if the player chooses ‘X’ indicating a desire to quit the game. In this case, the rest of the program will not be executed and the game will end.

We are using a boolean variable ‘playGame to facilitate this. A value of True will allow the players to continue playing the game and a value of False will allow them to quit the game. This variable is initialized with the value True at the beginning of the game assuming that the players invoke the program with a desire to play the game.

If the player opts to quit the game by choosing ‘X’, the boolean playGame is set to False which results in bypassing the portion of the program containing the game logic and the game ends.

STEP 5: Showing blank lines for every letter in the chosen word

This step is executed once the player selects a category for the word list. After the random word is chosen by the program we want to show the player placeholders (we are using blank lines in this program) for every letter in the chosen word. The number of placeholders indicates the length of the word to be guessed.  Here’s how we will accomplish it:

Note that this part of the program will run only if the player chooses the right category for the word list. We also need to ensure that this part of the code is not executed if the player wants to quit the game. If the player selects a correct category and does not want to quit the game, the boolean playGame will have a value True. We check the value of this variable using an if condition.

We will first convert our secretWordto a list and store it in a variable called ‘secretWordList.

In order to make the game interesting, we are also limiting the number of allowed attempts dynamically based on the secret word. In this program, the number of attempts allowed is being limited to two more than the number of letters in the secret word. In order to achieve this, we need to keep track of the length of the secret word as well as the number of attempts the player took to guess the word. The length property is used to find the length of the ‘secretWord variable. The number of allowed attempts is set by adding 2 to this length and stored it in the variable attempts. This variable will be used to track the number of attempts remaining as the game progresses.

Every time the player makes a guess the number of attempts will be reduced by 1 (attempts -= 1) till the player guesses the correct word or there aren’t any more attempts left (attempts == 0)

Now, we will work on showing the placeholders for the secret word. For this, we will first create a variable called ’userGuesslist. We will initiate this variable with an empty list.

Next,  we will loop through our ‘secretWordList list and for each element in the list we will append an ‘_’  to our ‘userGuesslist list.

To display our ‘userGuesslist we will create a function ‘printGuessedLetter()‘ and use it every time we want to print our list.

STEP 6: Logic to ask for a letter and display it in the placeholder

Next, we will work on the logic of asking the player to enter a letter until they guess the word correctly or run out of allowed attempts. If the letter is in the chosen word, we will add the letter to the correct position in our ‘userGuesslist list and then display the list.

We will start by creating a while loop to keep asking for letter input from the player.

Next, we will check if the letter input by the player has already been entered. We will create an emptyuserGuesses list and every time the player enters a letter we will append that to the ‘userGuesses list. If the letter exists in the ‘userGuesses list, we will ask the player to choose another letter.

Otherwise, the program will loop through our ‘secretWordList, get the index of the letter input and in the same index number, add the letter in the ‘userGuesslist list.

STEP 7: win/loss logic

We are almost at the end of our game. Here we will work on our win / loss logic.

We will join the ‘userGuesslist variable and store it in the variablejoinedList.

To determine win / loss we will compare the ‘secretWord (the computer chosen word) with the ‘joinedList variable. If they both match, the player will win. As mentioned earlier, after each guess, we will also track the number of attempts remaining to check if it equals ‘0’, in which case the player will lose.

SETP 8: Play-again logic

Last but not least we will work on the ‘Play Again logic for the game. We prompt the player to check if they want to play again and will store the response in a variable.

If the player wants to play again, we will prompt the word category thereby allowing the player to change it from their previous selection. We will also empty the ‘userGuessList list and the userGuesses list to reset them so that the new game is tracked properly. We will also set theplayGame boolean variable to True.

If the player chooses not to play again, we will break out of the loop in the else block.

Here is the complete code for the game:

So there we have it. A working Python script ‘Hangman’ game. Do give it a try and hone your Python skills.

Related Posts