Hangman - classic word game

dev3058

Dev Anand

Posted on March 11, 2023

Hangman - classic word game

Are you interested in creating a fun and interactive game in Python? If so, let's dive into building a Hangman game!

'Hangman'

About Hangman

Hangman is a word guessing game where one player thinks of a word and the other player(s) try to guess it by suggesting letters.

  • The player(s) have a limited number of guesses and for each incorrect guess, a part of a hanging man is drawn.

  • The game continues until the player(s) either guess the word correctly or the hanging man is fully drawn, in which case the game is lost.

Keep calm coding begins....

Hangman in Python

Puzzle hint and answer

This code sets up the puzzle answer and hint for the Hangman game, which will be used later in the game to generate the puzzle and provide hints to the user.

from getpass import getpass
import math, random

string = getpass("\nProvide Puzzle Answer (Player 1) : ").strip().replace(" ", "").casefold()
hint = input('Any Hint : ')
Enter fullscreen mode Exit fullscreen mode

Random and Custom Puzzle design

You can express the two ways of creating a puzzle for the Hangman game in your code

  • by providing the user with the option to either input their own word for the game

  • or have the game randomly select a word for them.

Random puzzle design

def auto_puzzle(puzzle, missing_words = ""):
    for i in range((len(puzzle)//2)):
        random_value = puzzle[math.floor(random.random()*len(puzzle))]
        if random_value not in missing_words:
            missing_words += random_value
    for a in range(len(puzzle)):
        if puzzle[a] in missing_words:
            puzzle = puzzle.replace(puzzle[a],'_')
    return puzzle, missing_words
Enter fullscreen mode Exit fullscreen mode

Custom puzzle design

This function allows the user to manually select characters to be blanked out in the puzzle, and returns the updated puzzle and missing words to be used in the Hangman game.

def custom_puzzle(puzzle, missing_words = ""):
    num_blanks = int(input('How many blanks you prefer? : '))
    while len(missing_words) < num_blanks:
        blank_char = input('which character you want to blanked : ')
        if blank_char in puzzle:
            puzzle = puzzle.replace(blank_char,'_')
            missing_words += blank_char
            print(puzzle)
        else:
            print('Element not exist in Puzzle')
    return puzzle, missing_words
Enter fullscreen mode Exit fullscreen mode

Validating Guesses

This function allows the user to make guesses for the missing characters in the puzzle and displays the updated puzzle string with correct guesses.

def check_for_guess(puzzle, string, missing_words):
    false_attempt = 0
    while false_attempt < len(missing_words):
        if puzzle == string.lower():
                break
        ask = 'Remain Attempt : {} | Guess a Word (unique) : '.format(len(missing_words)-(false_attempt))
        guess = input(ask).casefold()
        if guess in missing_words and len(guess) == 1:
            for a in range(len(puzzle)):
                if string[a].lower() == guess:
                    puzzle = puzzle[:a] + guess + puzzle[a+1:]
            print('Keep it on ',puzzle)
        else:
            false_attempt += 1
            print('Oops! Try again')
    return puzzle
Enter fullscreen mode Exit fullscreen mode

Understanding the driver code

It creates a puzzle for the game based on user input. The code first sets the variable puzzle equal to the input string that represents the answer to the puzzle.

puzzle = string
if len(string) < 6:
    print('Answer should be > 6 characters')
else:
    false_attempt = 0
    puzzle_type = input('\nDo you want system designed puzzle? y/n : ')
    puzzle, missing_words = auto_puzzle(puzzle) if puzzle_type == 'y' or puzzle_type == 'Y' else custom_puzzle(puzzle)
    print('\n\nYour Puzzle (Player 2):',puzzle)
    print('Given hint: ',hint)
    given_answer = check_for_guess(puzzle, string, missing_words)
    print('\nCongratulation you won, Player 1 lost!') if given_answer == string.lower() else print('\nYou lost, Player 1 Won')
Enter fullscreen mode Exit fullscreen mode

Let's play for fun

'hangman-player-1'


'hangman-player-2'

For complete explanation refers: speakpython.codes/hangman-word-game


This article is contributed by speakpython.codes

💖 💪 🙅 🚩
dev3058
Dev Anand

Posted on March 11, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

UV the game-changer package manager
programming UV the game-changer package manager

November 24, 2024

Deep Learning Essentials
deeplearning Deep Learning Essentials

November 11, 2024

Python - List Methods & Tasks II
programming Python - List Methods & Tasks II

August 1, 2024

Python - List Methods & Tasks
programming Python - List Methods & Tasks

July 30, 2024