DEV Community

Cover image for Develop a hangman game in Python in just 5 minutes
AP
AP

Posted on

Develop a hangman game in Python in just 5 minutes

Hello, world! In this post, I will walk you through a simple hangman game in Python. This post already assumes that you have prior programming experience in Python. If not, a great way to get started is via here.

Now, this is isn't a GUI based game - just a terminal based I/O game that can improve your pythonic knowledge.

What's a hangman game?

Hangman is a paper and pencil guessing game for two or more players. One player thinks of a word, phrase, or sentence, and the other tries to guess it by suggesting letters within a certain number of guesses. (Source: Wikipedia)

So, what's the plan?

Now that you know what's Hangman, let me provide you with a fine pseudocode for the same:

Pick a random word from a large dataset.
initialize points to 0
while True:
    set POSSIBLE_ALPHABETS = list of "abcdefghijklmnopqrstuvwxyz"
    set RANDOM_ALPHABETS = pick 3 random alphabets from POSSIBLE_ALPHABETS
    for ALPHABET in RANDOM_ALPHABETS:
        replace ALPHABET from the random word with a "_"

    print the random word (after replacement of alphabets)
    take input from the user as ANSWER

    if ANSWER is equal to the random word:
        #Hurray!
        increment points by 1
    else:
        #Alas!
        print the total points
        break
Enter fullscreen mode Exit fullscreen mode

This will be the infrastructure of our game - feel free to change or modify this pseudocode according to your means.

Pip requirements

Install the following packages:

  1. colorama (optional)
  2. nltk

Alright! With a nice and firm pseudocode, let's get into the actual code:

First of all, we want to import all modules.

import random
import colorama

from nltk.corpus import brown
Enter fullscreen mode Exit fullscreen mode

Note: Here I'm using brown dataset from nltk.corpus which is a large collection of words - alternatively, you can replace the usage of Brown with your own dataset.

Now, we want to get all the words of the Brown dataset and put it in a variable:

word_list = brown.words()
Enter fullscreen mode Exit fullscreen mode

Note: If you are using your own dataset, try this: word_list = ['apple', 'computer', 'banana', 'soap', 'snake', ...]

Now, let's initialize a points variable and set its initial value to zero 0.

points = 0
Enter fullscreen mode Exit fullscreen mode

Now, I came up with an idea of using "Colorama" which can provide you with colored output on the terminal window. It is optional, and I did this to make the output a bit nice.

colorama.init(autoreset=True)
Enter fullscreen mode Exit fullscreen mode

Since we need to loop our game till the player loses (so that we can increment the points), let's wrap the upcoming lines of code with an infinite loop:

while True:
    #rest of the code goes here.
Enter fullscreen mode Exit fullscreen mode

Now, I don't why I did this, but I re-initialized the word_list with another variable words:

words = word_list
Enter fullscreen mode Exit fullscreen mode

Ok, this is the time we need a list of all possible alphabets (from A to Z):

possible_alphabets = list("abcdefghijklmnopqrstuvwxyz")
old_word = random.choice(words)
Enter fullscreen mode Exit fullscreen mode

Note: I also added a variable old_word to choose a random word from word_list - I named it like that, just so that I can differentiate it from the word after that it has been modified.

Now, add these lines of code to your existing Python code:

alphabets = [] #initialize alphabets list

for i in range(3):
    alphabets += random.choice(possible_alphabets) 
Enter fullscreen mode Exit fullscreen mode

I did this so that I have an alphabets list, and that I append 3 random letters to the alphabets list from the possible_alphabets list (as per the pseudocode we designed before).

Now that we have that, let's replace all these random alphabets from the old_word with an underscore, so that we could make our guessable string (Eg: "developer" as "de_e_ope_")

for alphabet in alphabets:
    word = old_word.replace(alphabet, '_')
Enter fullscreen mode Exit fullscreen mode

Cool! Everything seems to be right till now; let's start getting the user input.

if "_" in word: #additional error checking
    print(word) #printing the word with underscore
    answer = input('word: ')
else:
    continue
Enter fullscreen mode Exit fullscreen mode

Now, as a conslusion, add these lines of code:

if answer == old_word:
    points += 1
    print(f'That\'s correct! Total points: {colorama.Fore.CYAN}{points}')

else:
    print(f'Sorry, but you lost. (The actual word was {colorama.Fore.GREEN}{old_word}{colorama.Fore.WHITE})\n')
    print('------GAME OVER------')
    print(f'\nTotal points: {colorama.Fore.CYAN}{points}\n')

    break
Enter fullscreen mode Exit fullscreen mode

We finally checked whether the user input was the same as of the original word, and if it was, we incremented the points by 1. If it wasn't, we then broke out of the loop, saying that the game was over.

In a nutshell (for lazy developers):

import random
import colorama

from nltk.corpus import brown

word_list = brown.words()
#word_set = set(word_list)

#print(random.choice(word_list))

points = 0

colorama.init(autoreset=True)

while True:
    words = word_list

    possible_alphabets = list("abcdefghijklmnopqrstuvwxyz")

    old_word = random.choice(words)

    alphabets = []

    for i in range(3):
        alphabets += random.choice(possible_alphabets)


    for alphabet in alphabets:
        word = old_word.replace(alphabet, '_')

    if "_" in word:
        print(word)

        answer = input('word: ')
    else:
        continue

    if answer == old_word:
        points += 1
        print(f'That\'s correct! Total points: {colorama.Fore.CYAN}{points}')

    else:
        print(f'Sorry, but you lost. (The actual word was {colorama.Fore.GREEN}{old_word}{colorama.Fore.WHITE})\n')
        print('------GAME OVER------')
        print(f'\nTotal points: {colorama.Fore.CYAN}{points}\n')

        break


Enter fullscreen mode Exit fullscreen mode

Run the code, and see what you get!

This was just a beginning; here's an idea for you to make our project more interesting: why not create a GUI for the same?

Having any doubts or queries regarding the topic? Feel free to mention it in the comments below and I will try my best to respond to you!

Conclusion

Python is so amazing that it is meant for any branches of computer science. It's way of implementing algorithms in easier syntaxes makes it unchallenging to execute any plan.

If you liked the project, give it a thumbs up 👍, so that I can make cooler projects like this - till then, see you next time!

Top comments (0)