Introduction
Hangman combines string handling, sets and a game loop. This version draws the gallows stage by stage, accepts whole-word guesses, refuses repeated or invalid guesses without penalty and can be seeded for repeatable tests.
Problem statement
Objectives
- Use sets to track guessed letters
- Build display strings with comprehensions and join
- Write a game loop with several end conditions
- Use seeded randomness for testing
Features
- Three word categories
- Seven-stage ASCII gallows
- Letter and whole-word guesses
- Repeated and invalid guesses don't cost lives
- Replays with a win/loss score
Concepts demonstrated
- Sets
- String building
- Game loops
- Seeded randomness
System architecture
WORDS maps categories to word lists and STAGES holds the seven drawings. play chooses a word with the shared random.Random, then loops while lives remain: it validates the guess, updates the guessed set or the wrong list and checks for a win. masked builds the display with underscores. main reads the seed and runs games until the player stops.
Folder structure
Complete source code
main.py
What each file does
- main.py
- Word lists, gallows drawings, the game loop and the replay loop.
How to run it
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
3 a e k 1 zebra a n g r o y x q x z w j k n
Testing
- Run
python main.py < tests/sample-input.txtand compare withtests/expected-output.txt. - Seed 3 chooses KANGAROO and then VARIABLE.
- In game 1, '1' is rejected, 'zebra' costs a life and the repeated 'a' is free; the word is solved with 4 lives left.
- In game 2, six wrong letters complete the gallows and the game is lost.
Common errors
Guessing the same letter twice costs a life
Check the guessed set and the wrong list before applying a penalty.
A whole-word guess with digits is accepted
Check guess.isalpha() before comparing with the word.
Possible improvements
- Load words from a text file
- Add difficulty levels by word length
- Show a hint after three wrong guesses
Additional challenges
- 1Add a two-player mode where one player enters the word secretly.
- 2Track statistics per category across games.
- 3Write an AI that guesses letters by frequency.
Built and tested it yourself? Mark it to update your dashboard.