Day07: Hangman Game Project Overview

Day07: Hangman Game Project Overview

The Hangman game project is a classic word-guessing game where players try to guess a word one letter at a time. For each wrong guess, a part of a "hanged man" is drawn. The game ends when the player either guesses the word or completes the hangman drawing. This project allows you to practice Python programming concepts like loops, conditionals, functions, and lists.

How the hangman game works.

Play hangman game online with friend.

Flowchart

The project can be built in five steps, and each step will focus on adding more functionality until we have a fully working Hangman game.


Step 1: Getting Started with Random Word Selection and User Guessing

TODO-1:

  • Randomly select a word from the list using Python's random.choice() function and assign it to the variable chosen_word. Print the word to debug.

TODO-2:

  • Ask the user to guess a letter, store the input in a variable called guess, and convert the letter to lowercase using .lower().

TODO-3:

  • Loop through each letter in chosen_word. If the guessed letter matches a letter in the word, print "Right"; otherwise, print "Wrong".

import random

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

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

for letter in chosen_word:
    if letter == guess:
        print("Right")
    else:
        print("Wrong")        

Step 2: Creating a Placeholder for the Word

TODO-1:

  • Create an empty string placeholder to represent the word with underscores (_). For each letter in chosen_word, add an underscore to placeholder.

TODO-2:

  • Create an empty string called display. Loop through each letter in chosen_word and reveal the guessed letter in the correct position while keeping other letters as _.

import random

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

word_length = len(chosen_word)
placeholder = "_" * word_length
print(placeholder)  # Debugging

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

display = ""

for letter in chosen_word:
    if letter == guess:
        display += letter
    else:
        display += "_"

print(display)        

Step 3: Letting the User Guess Multiple Times

TODO-1:

  • Use a while loop to allow the user to keep guessing until they complete the word.

TODO-2:

  • Update the for loop so that previously guessed letters are not replaced by underscores. Add them to a list of correct guesses.

import random

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

word_length = len(chosen_word)
placeholder = "_" * word_length
print(placeholder)

game_is_over = False
correct_letters = []

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

    display = ""
    for letter in chosen_word:
        if letter == guess or letter in correct_letters:
            display += letter
        else:
            display += "_"

    print(display)

    if "_" not in display:
        game_is_over = True
        print("You guessed all the letters correctly!")        

Step 4: Adding Lives and ASCII Art

TODO-1:

  • Add a variable lives to keep track of the number of guesses remaining (set to 6).

TODO-2:

  • Deduct a life when the user guesses incorrectly. If lives reaches 0, the game ends.

TODO-3:

  • Use ASCII art to visually represent the state of the hangman after each wrong guess.

import random

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

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

lives = 6
correct_letters = []

while lives > 0:
    guess = input("Guess a letter: ").lower()

    display = ""
    for letter in chosen_word:
        if letter == guess or letter in correct_letters:
            display += letter
        else:
            display += "_"

    print(display)

    if guess not in chosen_word:
        lives -= 1
        if lives == 0:
            print(f"You lose. The word was {chosen_word}")
            break

    if "_" not in display:
        print("You win!")
        break

    print(stages[lives])        

Step 5: Final Touches

TODO-1:

  • Import a larger word_list from a separate hangman_words.py file.

TODO-2:

  • Use ASCII art stages from a separate hangman_art.py file to display hangman states visually.

TODO-3:

  • Import a logo from hangman_art.py and display it at the start of the game.

TODO-4:

  • Inform the user if they've already guessed a letter without reducing lives.

TODO-5:

  • If a letter is not in the word, print a message and reduce a life.

import random
from hangman_words import word_list
from hangman_art import stages, logo

lives = 6
chosen_word = random.choice(word_list)
correct_letters = []

print(logo)  # Display game logo

while lives > 0:
    print(f"You have {lives}/6 lives left.")
    guess = input("Guess a letter: ").lower()

    if guess in correct_letters:
        print(f"You've already guessed {guess}")
    else:
        display = ""
        for letter in chosen_word:
            if letter == guess or letter in correct_letters:
                display += letter
                correct_letters.append(letter)
            else:
                display += "_"

        print(display)

        if guess not in chosen_word:
            lives -= 1
            print(f"You guessed {guess}, that's not in the word. You lose a life.")

        if "_" not in display:
            print("You win!")
            break

        if lives == 0:
            print(f"The word was {chosen_word}. You lose!")

    print(stages[lives])        

hangman_words.py

word_list = [
    'abruptly',
    'absurd',
    'abyss',
    'affix',
    'askew',
    'avenue',
    'awkward',
    'axiom',
    'azure',
    'bagpipes',
    'bandwagon',
    'banjo',
    'bayou',
    'beekeeper',
    'bikini',
    'blitz',
    'blizzard',
    'boggle',
    'bookworm',
    'boxcar',
    'boxful',
    'buckaroo',
    'buffalo',
    'buffoon',
    'buxom',
    'buzzard',
    'buzzing',
    'buzzwords',
    'caliph',
    'cobweb',
    'cockiness',
    'croquet',
    'crypt',
    'curacao',
    'cycle',
    'daiquiri',
    'dirndl',
    'disavow',
    'dizzying',
    'duplex',
    'dwarves',
    'embezzle',
    'equip',
    'espionage',
    'euouae',
    'exodus',
    'faking',
    'fishhook',
    'fixable',
    'fjord',
    'flapjack',
    'flopping',
    'fluffiness',
    'flyby',
    'foxglove',
    'frazzled',
    'frizzled',
    'fuchsia',
    'funny',
    'gabby',
    'galaxy',
    'galvanize',
    'gazebo',
    'giaour',
    'gizmo',
    'glowworm',
    'glyph',
    'gnarly',
    'gnostic',
    'gossip',
    'grogginess',
    'haiku',
    'haphazard',
    'hyphen',
    'iatrogenic',
    'icebox',
    'injury',
    'ivory',
    'ivy',
    'jackpot',
    'jaundice',
    'jawbreaker',
    'jaywalk',
    'jazziest',
    'jazzy',
    'jelly',
    'jigsaw',
    'jinx',
    'jiujitsu',
    'jockey',
    'jogging',
    'joking',
    'jovial',
    'joyful',
    'juicy',
    'jukebox',
    'jumbo',
    'kayak',
    'kazoo',
    'keyhole',
    'khaki',
    'kilobyte',
    'kiosk',
    'kitsch',
    'kiwifruit',
    'klutz',
    'knapsack',
    'larynx',
    'lengths',
    'lucky',
    'luxury',
    'lymph',
    'marquis',
    'matrix',
    'megahertz',
    'microwave',
    'mnemonic',
    'mystify',
    'naphtha',
    'nightclub',
    'nowadays',
    'numbskull',
    'nymph',
    'onyx',
    'ovary',
    'oxidize',
    'oxygen',
    'pajama',
    'peekaboo',
    'phlegm',
    'pixel',
    'pizazz',
    'pneumonia',
    'polka',
    'pshaw',
    'psyche',
    'puppy',
    'puzzling',
    'quartz',
    'queue',
    'quips',
    'quixotic',
    'quiz',
    'quizzes',
    'quorum',
    'razzmatazz',
    'rhubarb',
    'rhythm',
    'rickshaw',
    'schnapps',
    'scratch',
    'shiv',
    'snazzy',
    'sphinx',
    'spritz',
    'squawk',
    'staff',
    'strength',
    'strengths',
    'stretch',
    'stronghold',
    'stymied',
    'subway',
    'swivel',
    'syndrome',
    'thriftless',
    'thumbscrew',
    'topaz',
    'transcript',
    'transgress',
    'transplant',
    'triphthong',
    'twelfth',
    'twelfths',
    'unknown',
    'unworthy',
    'unzip',
    'uptown',
    'vaporize',
    'vixen',
    'vodka',
    'voodoo',
    'vortex',
    'voyeurism',
    'walkway',
    'waltz',
    'wave',
    'wavy',
    'waxy',
    'wellspring',
    'wheezy',
    'whiskey',
    'whizzing',
    'whomever',
    'wimpy',
    'witchcraft',
    'wizard',
    'woozy',
    'wristwatch',
    'wyvern',
    'xylophone',
    'yachtsman',
    'yippee',
    'yoked',
    'youthful',
    'yummy',
    'zephyr',
    'zigzag',
    'zigzagging',
    'zilch',
    'zipper',
    'zodiac',
    'zombie',
]        

hangman_art.py

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

logo = ''' 
 _                                             
| |                                            
| |__   __ _ _ __   __ _ _ __ ___   __ _ _ __  
| '_ \ / _` | '_ \ / _` | '_ ` _ \ / _` | '_ \ 
| | | | (_| | | | | (_| | | | | | | (_| | | | |
|_| |_|\__,_|_| |_|\__, |_| |_| |_|\__,_|_| |_|
                    __/ |                      
                   |___/    '''        

?? Key Takeaways:

  • Random module: Used to select a random word from a list.
  • String manipulation: Loop through strings to check guessed letters.
  • Control flow: Use loops (while and for) and conditionals (if/else) to control the game flow.
  • Lives management: Deduct lives for wrong guesses.
  • User feedback: Inform users of the state of the game and handle already guessed letters.

Try to complete the project step-by-step using the demo, and good luck building your own Hangman game!

要查看或添加评论,请登录

Muhammad Hanzala的更多文章

社区洞察

其他会员也浏览了