< Prev  |  Home  |  Next >

Python Hangman Game

If you’ve been following the tutorials up to this point, you’ve now learnt everything you need to make a range of fun, playable games. The first game we’ll attempt to make is Hangman. I’m not going to provide a step-by-step solution to this game, but instead give you ideas on how you might go about making it.

If you have a variable storing a word to guess, you can initially show the player a series of blanks (underscores) to show how many letters are in the word they have to guess:

The player can then start entering letters to see if they’re in the word. Can you see a problem with the program output:

Enter a word to guess: hangman
_ _ _ _ _ _ _

This game isn’t fun at all, because the answer is now displayed as part of the program. There are 2 ways to solve this: one way is to import and use the ‘getpass’ module (Google it!) and the other way is just to flush the screen with a series of spaces:

This way isn’t quite as robust, as the user can simply scroll up to find the answer. However, either will do for now.

You can then keep asking the player for a letter to guess, and then re-print the word with the letter added (if the guess was correct). Here’s what we have so far:

You can now use this starting point to create your own game. It’s up to you how much you add to this, but here are some ideas as to what you could do:

  • Add a number of lives, and take one from the player for an incorrect guess;
  • Obviously, you should allow the player to eventually win or lose;
  • Create a list (or file) of possible words to guess, and randomly select one at the start of the game;
< Prev  |  Home  |  Next >