Hangman - classic word game
Tags: programming, python, beginners
Published: 2023-03-11 07:13:22

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

!['Hangman'](https://www.rd.com/wp-content/uploads/2017/08/Here-Is-The-Hardest-Word-To-Guess-in-Hangman-According-To-Science-ft.jpg)

## 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.

<br/>

> Keep calm coding begins....

## Hangman in Python

<br />
### 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.

```python
from getpass import getpass
import math, random

string = getpass("\nProvide Puzzle Answer (Player 1) : ").strip().replace(" ", "").casefold()
hint = input('Any Hint : ')
```
<br />

### 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.

<br/>


### Random puzzle design

```python
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
```

<br/>

### 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.

```python
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
```
<br/>

### 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.

```python
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
```


<br/>

### 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.

```python
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')
```
<br/>

### Let's play for fun

!['hangman-player-1'](https://speakpython.codes/two-player-game/image/hangman-player-1.png)

<hr/>

!['hangman-player-2'](https://speakpython.codes/two-player-game/image/hangman-player-2.png)

<br/>



>_For complete explanation refers: [speakpython.codes/hangman-word-game](https://speakpython.codes/two-player-game/2023/03/07/hangman-word-game.html)_

---
_This article is contributed by [speakpython.codes](https://speakpython.codes)_