Programming Games
Python
Hangman

Programming Games Python Hangman

In this post, I'm going to write a hangman game.

Hangman game is a game where you choose a letter until you find the word

Here we go!

# Library to get numbers random.
import random
# Library to manipulate the console.
import os

# The function to read the list of words.
def read():
  # Initialize.
  words = []
  # Read the file.
  with open("./files/data.txt", "r", encoding="utf-8") as f:
    # Add all words from file to list, with list comprehensions.
    words = [line for line in f]

  # Return one word from the list.
  return random.choice(words)

# Function to print the message for the player.
def print_message(hidden, error=None, fail=0):
  # Clean the console.
  os.system("clear") # On windows os.system('cls')
  # Print header.
  print("Hangman game: ")
  # Print the word hidden.
  print(hidden)
  # Print faults if has.
  print_faults(fail)
  # Print error if the player puts a number or more than one letter.
  if error:
    print("***" + str(error) + "***")


# Print faults.
def print_faults(fail):
  # Print if the first fails.
  if fail >= 1:
    print("   ______ ")
    print(" ( .  .   )")
  # Print if the second fails.
  if fail >= 2:
    print("  \ ~~~~ /")
    print("   \____/")
  # Print if the third fails.
  if fail >= 3:
    print("     ||  ")
    print("  // || \\")
    print(" //  ||  \\")
    print(" M   ||  M")
  # Print if the fourth fails.
  if fail >= 4:
    print("   ||  ||    ")
    print("   ||  ||    ")
  # Print if the fifth fails.
  if fail >= 5:
    print("   ||  ||    ")
    print("   ==  ==    ")


# Principal function.
def run():
  # Initialize.
  success = ''
  error = None
  fail = 0
  letter_used = []
  # Get the word.
  word = read()
  # Replace line break.
  word = word.replace("\n", "")
  # Turn the word to hidden word.
  hidden = " ".join(list(map(lambda letra: "_", word)))


  # Loop to repeat while the player doesn't find the word.
  while word != success:
    # Initialize the try except method.
    try:
      # Print message.
      print_message(hidden, error, fail)

      # Get the letter from the console.
      letter = input("Choose a letter:").lower()
      # Assert is a method to validate if the affirmation is true.
      assert not letter.isnumeric(), "You must to put a letter"
      assert len(letter) == 1, "You must to put just one letter"
      # Validate if the player used this letter before.
      if len([old_letter for old_letter in letter_used if old_letter == letter]) > 0:
        raise ValueError("This letter has already been used")

      # Add the letter to the list.
      letter_used.append(letter)

      # Turn the string to list.
      hidden = hidden.split(" ")

      # Assumed the player fails.
      no_fail = False

      # Validate if the letter is in the word.
      for i, letter_hidden in enumerate(word):
        # If the letter exists in the word.
        if letter_hidden == letter:
          # Replace the position with the letter.
          hidden[i] = letter_hidden
          # Set the player didn't fail.
          no_fail = True

      # Turn the list to string.
      hidden = " ".join(hidden)

      # Set the success variable with the hidden word.
      success = hidden.replace(' ', '')

      # Set the error variable.
      error = None

      # If fail.
      if not no_fail:
        # Plus 1 for failing.
        fail += 1
        # If fail is 5, breaks the loop.
        if fail >= 5:
          break
    # Manage the exceptions.
    except AssertionError as ae:
      error = ae
    except ValueError as ve:
      error = ve

  # Print message.
  print_message(hidden, fail=fail)

  # If fail is 5 the player lost.
  if fail >= 5:
    print(f"Try again the word was {word}")
  # Else the player won.
  else:
    print(f"You win the word was {word}")

# Executed when invoked directly
if __name__ == '__main__':
  run()

data.txt

cream
coffe
star
explosion
guitar
plastic
razor
luffy
hammer
books
pencil
pen
aluminum
boat
letter
lace
window
bookshop
sound
college
wheel
dog
keys
shirt
hair
zoro
father
armchair
happiness
cot
keyboard
napkin
school
screen
sun
elbow
fork
statistics
map
watter
message
lime
rocket
king
edifice
sanji
grass
presidency
sheets
talking
hail
tab
lamp
hand
flower
music
man
screw
bedroom
sailboat
nami
grandma
grandpa
stick
robbin
satelite
temple
lenses
dish
cloud
government
bottle
castle
dwarf
house
book
person
planet
gloves
metal
telephone
projector
monkey
usopp
tooth
petroleum
hanger
auction
debate
ring
notebook
noise
wall
drill
tool
cards
jinbe
chocolate
glasses
printer
candies
lights
anguish
shoe
bomb
rain
eye

Would you like that I write more games?

I hope you enjoy my post and remember that I am just a Dev like you!