Introduction
Hangman is a classic first game that exercises strings, sets and loops. Using a seeded java.util.Random makes every game repeatable, which is how the expected output can be tested exactly.
Problem statement
Objectives
- Use a Set to track guesses
- Build the masked word with StringBuilder
- Use a seeded Random for reproducible behaviour
- Structure a game into rounds with a method that returns the result
Features
- Seven-stage ASCII gallows
- Letter and whole-word guesses
- Duplicate and invalid guesses handled gracefully
- Multiple rounds with a final tally
Concepts demonstrated
- Sets
- String processing
- Pseudo-random numbers
- Game loops
- Methods returning results
System architecture
main reads the seed, creates the Random and loops over rounds. playRound keeps a LinkedHashSet<Character> of guesses (which remembers the order for display) and a wrong-guess counter. Each iteration prints the gallows stage, the masked word and the guesses, checks for a win or a loss, then reads a guess. mask builds the display string by checking each letter against the set.
Folder structure
Complete source code
src/Main.java
What each file does
- src/Main.java
- The word list and gallows art, the round loop in
playRound, and the masking helper.
How to run it
Compile
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.
7 e a e 3 c o t compilr m p i l r y z q x j w k v n
Testing
- Run with
tests/sample-input.txtand compare withtests/expected-output.txt. - Seed 7 chooses COMPILER first; a wrong word guess (compilr) costs two lives, and the player still wins.
- The second round (EXCEPTION) is lost after six wrong letters.
- The final line reads 'You won 1 of 2 round(s).'
Common errors
The same word appears every game
Enter 0 for the seed to use an unseeded Random.
Guessing 'E' doesn't reveal 'e'
Lower-case every guess before comparing.
Possible improvements
- Load words from a file and pick by difficulty
- Give a hint after four wrong guesses
- Add a two-player mode where one player types the word
Additional challenges
- 1Show the alphabet with used letters crossed out.
- 2Score rounds by remaining lives.
- 3Implement 'evil hangman', which changes the word to avoid the player's guesses.
Built and tested it yourself? Mark it to update your dashboard.