slash-root

Creating a Hangman game (including functions and reading files)


In this tutorial we are going to create a game of Hangman in Python. We will be utilising a number of 'if' statements, loops, functions including reading files. This guide assumes you have an environment set up in order to compile Python code. If you are unsure on the dynamics of the game Hangman, you can read about it here: Wikipedia Hangman (Game).

Functionality Required


A function to configure the game.
A function to manage the conditions of a live game.
A function to check for a winning condition (all letters revealed).
A function to check for a losing condition (no lives left).
A function to restart or quit the game.

Structure


Our starting structure is the following:

def configure_game():
...

def play():
...

def check_win():
...

def check_lose():
...

def play_again():
...

if __name__ == "__main__":
...

configure_game()


The first function we are going to setup is the logic to initiate the game starting condition, such as the word to be guessed and total lives.

def configure_game():

A variable to hold the number of starting lives
lives = 5

A list of words to be used for guessing. This 'for' loop is reading in each line from the file 'words.txt' and then removing the new line identifier '\n' from the end of each word being loaded. Ensure a file 'words.txt' is available and contains a few words, each on a new line. We also encapsulate this in a TRY/EXCEPT block. This will alert the player the words.txt file could not be loaded if it is in fact missing.
try:
    words = [line.rstrip("\n") for line in open(r"c:/Users/slashroot/Desktop/words.txt")]
except FileNotFoundError:
    print("*** WORDS.TXT FILE NOT FOUND ***")

A word to be used for this instance of the game. We are randomly choosing a word from the list with the help of the 'random' library. We now need to make sure we import this library.
word_to_guess = random.choice(words)

As we do not want to display the word to the player, we will create a 'current_guess' variable that is the same length as the 'word_to_guess' variable. This variable will simply be the character '_' multiplied by the number of characters in the 'word_to_guess'. Therefore, if the 'word_to_guess' is 'cheese'. The starting point for 'current_guess' is '_ _ _ _ _ _'. We will then dynamically update this variable with the characters the player guesses.
current_guess = len(word_to_guess) * '_'

This completes the function. We do have one last thing to do however, we need to make these variables accessible from outside of this function, therefore, we need to make them 'global'. We do this by using the keyword 'global'. We'll reposition this statement in our final function below.
global lives, word_to_guess, current_guess

The complete configure_game() function is below:

def configure_game():
    global lives, word_to_guess, current_guess
    lives = 5
    try:
       words = [line.rstrip("\n") for line in open(r"c:/Users/slashroot/Desktop/words.txt")]
    except FileNotFoundError:
       print("*** WORDS.TXT FILE NOT FOUND ***")
    word_to_guess = random.choice(words)
    current_guess = len(word_to_guess) * '_'

My 'words.txt' document holds the following:

cheese
hard
blueberries
computer
slashroot

check_win()


def check_win():

This function is used to check whether is symbol "_" currently exists within the current_guess variable. If it does, not all characters have been guessed, therefore, the win condition has not been met and the bool false is returned. The symbol "_" is replaced with guesses in the play function - if the guess is in the word.
if "_" in current_guess:
    return True
       else:
    return False

The complete check_win() function is below:

def check_win():
    if "_" in current_guess:
       return True
    else:
       return False

check_lives()


def lives():

Tell the function we are using the global lives variable.
global lives

This if statement is used to check if the current lives integer is above the value 0. If it is, the game continues with a bool value of true being returned. The play function decrements the lives integer if the current_guess is not present in the word_to_guess.
if lives > 0:
    return True
else:
    return False

The complete check_lives() function is below:

def check_lives():
   global lives
   if lives > 0:
       return True
   else:
       return False

play()


def play():

   Declare the usage of global variables: lives, current_guess.
   global lives, current_guess

   Start an infinite loop for the game.
   while True:

      Check if the player has lost the game.
      if check_lives() == False:
        print("You have lost!")
        break

      Check if the player has won the game.
      if check_win() == False:
        print("You have won!")
        break

      Ask the player to input a letter for guessing.
      while True:
        guess = input("Guess a letter: ")
        if guess.isalpha() != True:
          print("You must enter a single letter!")
        elif len(guess) > 1:
          print("You are only allowed to enter a single character!")
        else:
          break

      Check if the guessed letter is not in the word to guess.
      if guess not in word_to_guess:
        lives -= 1
        print("Letter not found!")
        time.sleep(1)

      If the guessed letter is in the word to guess, update the current guess.
      else:
        for i in range(len(word_to_guess)):
          if guess == word_to_guess[i]:
            temp = list(current_guess)
            temp[i] = guess
            current_guess = "".join(temp)
            print(guess + " is in the word!")
            time.sleep(1)

      Clear the console screen.
      os.system('cls')

      Print the current lives and current guess.
      print("Current lives: " + str(lives))
      print("Current guess: " + current_guess)

play_again()


def play_again():

   Start an infinite loop for prompting the player.
   while True:

      Ask the player if they want to play again.
      again = input("Do you want to play again 'y' or 'n'? ")

      Check if the input is not 'y' or 'n' and display an error message.
      if not (again == 'y' or again == 'n'):
        print("You must enter a single 'y' or 'n' to play again or quit!")

      If the input is valid, exit the loop.
      else:
        break

   Check if the player wants to play again or quit and return the corresponding value.
   if again == 'y':
      return True
   else:
      return False

main()


if __name__ == "__main__":

   Start an infinite loop for the game.
   while True:

      Configure the game settings.
      configure_game()

      Play the game.
      play()

      Check if the player wants to play again.
      if play_again() == False:

        If not, break out of the infinite loop and end the program.
        break

Complete Code


import random
import os
import time

def play_again():
    while True:
        again = input("Do you want to play again 'y' or 'n'? ")
        if not (again == 'y' or again == 'n'):
            print("You much enter a single 'y' or 'n' to play again or quit!")
        else:
            break
    if again == 'y':
        return True
    else:
        return False

def configure_game():
    global lives, word_to_guess, current_guess
    lives = 5
    try:
        words = [line.rstrip("\n") for line in open(r"c:/Users/slashroot/Desktop/words.txt")]
    except FileNotFoundError:
        print("*** WORDS.TXT FILE NOT FOUND ***")
        return
    word_to_guess = random.choice(words)
    current_guess = len(word_to_guess) * '_'

def check_win():
    if "_" in current_guess:
        return True
    else:
        return False

def check_lives():
    global lives
    if lives > 0:
        return True
    else:
        return False

def play():
    global lives, current_guess

    while True:
        if check_lives() == False:
            print("You have lost!")
            break
        if check_win() == False:
            print("You have won!")
            break

        while True:
            guess = input("Guess a letter: ")
            if guess.isalpha() != True:
                print("You much enter a single letter!")
            elif len(guess) > 1:
                print("You are only allowed to enter a single character!")
            else:
                break

        if guess not in word_to_guess:
            lives -= 1
            print("Letter not found!")
            time.sleep(1)
        else:
            for i in range(len(word_to_guess)):
                if guess == word_to_guess[i]:
                    temp = list(current_guess)
                    temp[i] = guess
                    current_guess = "".join(temp)
                    print(guess + " is in the word!")
                    time.sleep(1)
        os.system('cls')
        print("Current lives: " + str(lives))
        print("Current guess: " + current_guess)

if __name__ == "__main__":
    while True:
        configure_game()
        play()
        if play_again() == False:
            break

Enquiries

[email protected]

Copyright © 2023 - slash-root.com