Python for everyone: create your own Halloween edition Hangman game

October 27, 2023

Learning to program is learning a new language. Among the programming languages, one of the most used is Python, as we have already told you in some previous posts. On this occasion, we propose the popular game of Hangman Halloween edition, with words related to this celebration.

And why a game? Because learning in a playful way helps us to understand and retain complex concepts, as well as to develop problem-solving, critical thinking and decision-making skills. They also foster our creativity and imagination, as users can experiment with different ideas and solutions to the same challenge.

And, in the case of programming, especially with languages such as Python (one of the most widely used for the development of Artificial Intelligence applications), learning to program by playing is a great excuse to lose the fear of coding. Get to work and create your own Halloween edition Hangman game!

1. Initial arrangements

Very simple! To create your game just log in with your Gmail account to Google Colab, Google's online platform for writing, accessing libraries and running Python code in a Cloud environment, for free and with collaboration between users on Jupyter notebooks.

2. Fundamental concepts of Python

To create our Hangman, we must understand the operation of some Python language structures that will serve as a basis: if and else, for and while.

If, elif and else structures

We are going to use this selection control structure to execute a block of code based on conditions. In our Hangman, we will use it to determine whether or not the letter entered by the user is in our hidden word, or if it has already been used.

In if (the first condition) and elif (the following added conditions) we will include the cases in which we want our Hangman game to give a specific answer, considering that the entered letter is not valid (false). In else, which serves for all those cases not mentioned in if and elif we will give the letter as valid (true).

For loop

The control structure in Python will be another of the bases of our game, and will allow us to iterate over a sequence of elements.

In our Hangman game, the elements will be the letters that make up the hidden word, and the dashes that we show to the user, corresponding to the word to guess. As every time the user enters a letter we must verify that it is in the word, the for loop will serve us to go through these elements one by one and to execute the instructions that we indicate to it.

While Loop

Finally, we need the while loop to control the main logic of the game. It allows the game to continue as long as the player has attempts remaining and as long as there are letters left to guess in the hidden word. Once the condition becomes false, the loop stops and a win or loss message is displayed.

3. Hangman game design

We will start by creating the game structure from a series of variables, which will allow us to make the code more efficient. First, the visual representation of the Hangman:

  • The hidden word will have exactly the same length (underscores) as the word elements. For this, we use the len function.
  • The number of game attempts. Later, we will indicate to the program that, for each failure, an attempt will be subtracted (attempts -1) .
  • We determine the alphabet in a list. Later, we will indicate that only the letters included in the said list are valid.
  • Finally, the discarded letters variable, since during the game we will show the user the incorrect words already used:
hangman_drawing = [
    '''
       +---+
       |   |
           |
           |
           |
           |
    =========
    ''', 
    '''
       +---+
       |   |
       O   |
           |
           |
           |
    =========
    ''',
    '''
       +---+
       |   |
       O   |
       |   |
           |
           |
    =========
    ''',
    '''
       +---+
       |   |
       O   |
      /|   |
           |
           |
    =========
    ''',
    '''
       +---+
       |   |
       O   |
      /|\  |
           |
           |
    =========
    ''',
    '''
       +---+
       |   |
       O   |
      /|\  |
      /    |
           |
    =========
    ''',
]

word = list('skull')
hidden_word =['_']*len(word)
attempts = 6
alphabet_list = list('abcdefghijklmnopqrstuvwxyz')
discarded_letters = []

4. Programming user interaction

Let's dive into the 'guts' of the Hangman game to translate into code how we allow the user to guess letters, and how to keep track of the correct and incorrect letters.

First of all, we'll show the current state of the game: the number of remaining attempts, discarded letters, and how the corresponding letters are guessed for the dashes of the hidden word.

Game state

We will use the join method to combine elements in a list so that the visual representation is more readable. It helps us format the output of the discarded letters and the hidden word:

def show_state():
    print(f'Left attemps: {attemps}')
    print(f'Discarded letters: {", ".join(discarded_letters)}\n')
    print(f'Word: {" ".join(hidden_word)}\n')
    print(hangman_drawing[6 - attemps])

Valid Letter Verification

When the user plays, there are different scenarios that we must reflect in the code, as the entered letter may have already been used, the user might enter a symbol that is not a letter, or they might enter more than one character.

To develop the code to verify if the entered letter is valid or not, we will create conditional structures (if, elif, else). We will define the valid letter function based on the 'letter' parameter.

def valid_letter(letter):
    if len(letter) != 1 :
        print('You have entered more than one letter, please try again.')
        return False
    elif letra not in alphabet_list:
        print('You have not entered a letter from the alphabet.')
        return False
    elif letra in hidden_word:
        print('You have already guessed the letter you entered, please try again.')
        return False
    elif letra in discarded_letters:
        print('You have already used that letter, please try again.')
        return False
    else:
        return True


Handle Letter

Now we will define the letter management function with the for loop, which will update the representation of the hidden word when the user guesses a letter.

We will combine the for loop with range(len(word)), which will traverse each position in the 'word' list, assigning a sequence of indices for each element of the list. When the game finds a match, it will update both hidden_word and word.

In each iteration of the loop, i takes the value of one of those indices. In the case of the word, it will identify the position of the guessed letter, which it will take and replace the underscore in its same position in hidden_word:

def handle_letter(letter):
    for i in range(len(word)):
        if word[i] == word:
            hidden_word[i] = word
            word[i] = '_'


Now we will print what the user will see on the screen at the beginning of our Hangman game, as well as the conditions that must be met in our while loop for them to continue playing.

We will use lower to ensure the program always takes lowercase letters, regardless of how the user enters them. On the other hand, we will use the .append method to add the value of invalid letters to the discarded letters list.

And finally, the if statement and the join method to determine whether the user wins or loses.

print('WELCOME TO THE HANGMAN GAME 🎃 HALLOWEEN EDITION 🎃\n')
print('Game rules: Enter letters to guess the hidden word.')
print(f'You have {attempts} attempts. Good luck!')

while attempts > 0 and '_' in hidden_word:
    show_state()
    print('-'*50)
    letra = input('ENTER LETTER: ').lower()

    while not valid_letter(letter):
        letra = input('ENTER ANOTHER LETTER: ').lower()

    if letter in word:
        handle_letter(letter)
        print('-'*50)
        print('You guessed the letter! Keep it up.')
    else:
        print('-'*50)
        print('You missed the letter!')
        discarded_letters.append(letter)
        attempts -= 1

if '_' not in hidden_word:
    print('\n\n🏆🎃Congratulations! You've won the game!🎃🏆')
else:
    print(f'\nOh!😞 Sorry, you've lost!'
        '''\n
       +---+
       |   |
      💀   |
      /|\  |
      / \  |
           |
    =========
    ''')


And there you have it! By running all the code in Google Colab, you will have your Hangman game. You can also view the complete code in this notebook.

Now it's your turn to practice Python with spooky Halloween words. We challenge you to improve the code that will enhance the experience. For example, the random module, commonly used in Python to generate pseudo-random numbers, will allow each game to be different by randomly selecting a word from a list of predefined words.

Remember that you can customize the code to your liking by adding more words, graphics, sounds, or whatever you can think of. Additionally, giving it a Halloween twist can make it more fun and thematic. Don't limit yourself and explore Python's possibilities!