👩🏼‍💻 Day7 — #100DaysOfCode in Python

Day 7 — Building the Hangman Game

👩🏼‍💻 Day7 — #100DaysOfCode in Python

Today’s Goals:

Perform a Hangman project, and for this, you need to use For & While Loops, IF/ELSE statements, Lists, Strings, Range, Modules and much more.

🔗 Link to the explanation of the Hangman Game

What I’ve seen:

📌 I’ve practiced For & While Loops, IF/ELSE statements, Lists, Strings, Range, Modules and much more..

📌 And also I’ve incorporated Flow Chart Programming.

What I Learned Today:

Flow Chart Programming

Flow chart programming is a method of designing and documenting software systems. It’s particularly useful for visualizing the flow of a program or algorithm, making it easier to understand and communicate the logic. Here’s how flow charts are typically used in programming, especially for projects like a Hangman game in Python:

  1. Visual Representation: Flow charts use symbols like rectangles, diamonds, ovals, and arrows to represent different types of actions and decisions. This visual representation helps in understanding the flow of a program.

  2. Planning and Designing: Before writing code, you can use a flow chart to plan the structure of your program. For a Hangman game, this could involve charting out the main gameplay loop, decision points (like checking if a letter is in the word), and the end conditions (winning or losing the game).

  3. Algorithm Development: Flow charts are excellent for developing and refining algorithms. They help you think through each step and decision point in your code.

  4. Debugging and Problem Solving: If you encounter issues while coding, referring to your flow chart can help you identify where the logic might be going wrong.

  5. Communication: Flow charts are a great tool for explaining your code to others, which can be especially helpful in team projects or when seeking help from instructors or peers.

  6. Documentation: A flow chart can serve as part of the documentation for your code, making it easier for others (or yourself at a later time) to understand how your program works.

For instance: In the context of a Hangman game in Python, the flow chart might include the following elements:

  • Start and End Points: Indicate the beginning and end of your game.

  • User Input: Represent how the player’s input (guessing letters) is handled.

  • Process Blocks: Show how the game checks if the guessed letter is in the word, updates the display, keeps track of incorrect guesses, etc.

  • Decision Points: Indicate where the game decides if the player has won, lost, or if the game continues.

  • Looping: Since Hangman is a game of repeated guessing, your flow chart should clearly show the loops involved in player input and game response.

Using flow charts in programming is about breaking down a problem into manageable parts and visually mapping out the solution. This approach can be highly effective in learning and mastering programming concepts.

Our real solution:

Let’s Build The Project: Hangman Game

I created the different steps to create the Hangman game:

Step 1:

  • Picking a random word and checking the user’s answers.
#Step 1

word_list = ["aardvark", "baboon", "camel"]

#TODO-1 - Randomly choose a word from the word_list and assign it to a variable called chosen_word.
import random

chosen_word = random.choice(word_list)

#TODO-2 - Ask the user to guess a letter and assign their answer to a variable called guess. Make guess lowercase.
guess = input("Guess a letter: ").lower()

#TODO-3 - Check if the letter the user guessed (guess) is one of the letters in the chosen_word.
# if guess in chosen_word:
#     print("Correct!")
# else:
#     print("Incorrect!")

for letter in chosen_word:
    if letter == guess:
        print("Correct!")
    else:
        print("Incorrect!")
print(f"The word is: {chosen_word}")

Step 2:

  • Replacing blanks with guesses.
#Step 2

import random

word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)

#Testing code
print(f'Pssst, the solution is {chosen_word}.')

#TODO-1: - Create an empty List called display.
#For each letter in the chosen_word, add a "_" to 'display'.
#So if the chosen_word was "apple", display should be ["_", "_", "_", "_", "_"] with 5 "_" representing each letter to guess.
display = []
word_length = len(chosen_word)
for _ in range(word_length):
    display += "_"

guess = input("Guess a letter: ").lower()

#TODO-2: - Loop through each position in the chosen_word;
#If the letter at that position matches 'guess' then reveal that letter in the display at that position.
#e.g. If the user guessed "p" and the chosen word was "apple", then display should be ["_", "p", "p", "_", "_"].
for position in range(word_length):
    letter = chosen_word[position]
    #print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}")
    if letter == guess:
        display[position] = letter

#TODO-3: - Print 'display' and you should see the guessed letter in the correct position and every other letter replace with "_".
#Hint - Don't worry about getting the user to guess the next letter. We'll tackle that in step 3.
print(display)

Step 3:

  • Checking if the player won.
#Step 3

import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
word_length = len(chosen_word)

#Testing code
print(f'Pssst, the solution is {chosen_word}.')

#Create blanks
display = []
for _ in range(word_length):
    display += "_"

#TODO-1: - Use a while loop to let the user guess again. The loop should only stop once the user has guessed all the letters in the chosen_word and 'display' has no more blanks ("_"). Then you can tell the user they've won.
end_of_game = False

while not end_of_game:
    guess = input("Guess a letter: ").lower()

    #Check guessed letter
    for position in range(word_length):
        letter = chosen_word[position]
        #print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}")
        if letter == guess:
            display[position] = letter

    print(display)

    #Check if there are no more "_" left in 'display'. Then all letters have been guessed.
    if "_" not in display:
        end_of_game = True
        print("You win.")

Step 4:

  • Keeping track of the player’s lives.
#Step 4

import random

stages = ['''
  +---+
  |   |
  O   |
 /|\  |
 / \  |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
 /    |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|\  |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
 /|   |
      |
      |
=========''', '''
  +---+
  |   |
  O   |
  |   |
      |
      |
=========
''', '''
  +---+
  |   |
  O   |
      |
      |
      |
=========
''', '''
  +---+
  |   |
      |
      |
      |
      |
=========
''']

end_of_game = False
word_list = ["ardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
word_length = len(chosen_word)

#TODO-1: - Create a variable called 'lives' to keep track of the number of lives left. 
#Set 'lives' to equal 6.
lives = 6

#Testing code
print(f'Pssst, the solution is {chosen_word}.')

#Create blanks
display = []
for _ in range(word_length):
    display += "_"

while not end_of_game:
    guess = input("Guess a letter: ").lower()

    #Check guessed letter
    for position in range(word_length):
        letter = chosen_word[position]
       # print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}")
        if letter == guess:
            display[position] = letter

    #TODO-2: - If guess is not a letter in the chosen_word,
    #Then reduce 'lives' by 1. 
    #If lives goes down to 0 then the game should stop and it should print "You lose."
    if guess not in chosen_word:
        lives -= 1
        if lives == 0:
            end_of_game = True
            print("You lose.")

    #Join all the elements in the list and turn it into a String.
    print(f"{' '.join(display)}")

    #Check if user has got all letters.
    if "_" not in display:
        end_of_game = True
        print("You win.")

    #TODO-3: - print the ASCII art from 'stages' that corresponds to the current number of 'lives' the user has remaining.
    print(stages[lives])

Step 5:

  • Improving the UX: Adding ASCII Art and the UI.
#Step 5

import random

#TODO-1: - Update the word list to use the 'word_list' from hangman_words.py
#Delete this line: word_list = ["ardvark", "baboon", "camel"]
from hangman_words import word_list

chosen_word = random.choice(word_list)
word_length = len(chosen_word)

end_of_game = False
lives = 6

#TODO-3: - Import the logo from hangman_art.py and print it at the start of the game.
from hangman_art import logo
print(logo)

#Testing code
# print(f'Pssst, the solution is {chosen_word}.')

#Create blanks
display = []
for _ in range(word_length):
    display += "_"

while not end_of_game:
    guess = input("Guess a letter: ").lower()

    #TODO-4: - If the user has entered a letter they've already guessed, print the letter and let them know.
    if guess in display:
        print(f"You've already guessed {guess}")

    #Check guessed letter
    for position in range(word_length):
        letter = chosen_word[position]
        #print(f"Current position: {position}\n Current letter: {letter}\n Guessed letter: {guess}")
        if letter == guess:
            display[position] = letter

    #Check if user is wrong.
    if guess not in chosen_word:
        #TODO-5: - If the letter is not in the chosen_word, print out the letter and let them know it's not in the word.
        print(f"You guessed {guess}, that's not in the word. You lose a life.")

        lives -= 1
        if lives == 0:
            end_of_game = True
            print("You lose.")

    #Join all the elements in the list and turn it into a String.
    print(f"{' '.join(display)}")

    #Check if user has got all letters.
    if "_" not in display:
        end_of_game = True
        print("You win.")

    #TODO-2: - Import the stages from hangman_art.py and make this error go away.
    from hangman_art import stages
    print(stages[lives])

Thanks! 🫶🏻

📌 Now you can also find me at the following links:

👉🏻 Instagram
👉🏻 Twitter
👉🏻 Medium
👉🏻 LinkedIn