Hangman is a little game often played by pupils during math lessons without the teacher knowing. The rules are quite simple: The game master thinks of a word or phrase. The players try to guess the solution in a letter-by-letter fashion. For any bad guess, the game master adds another piece to a drawn gallows, complete with unfortunate hangman and other accessoires. When the gallows is fully constructed, the players lose. Obviously, players win if they are able to correctly solve the puzzle before.
Because of its simplicity, hangman is ideally suited for learning test-driven development or as a task for code dojos. Try to write classes and functions to handle the game logic. These features should be designed to be easily usable in an actual game application.
Basic hangman rules
For a start, program a basic version of hangman. The following set of rules may guide your implementation.
- The solution is an arbitrary, non-empty word or phrase.
- Players can guess the entire solution. The game reports whether this is the correct solution.
- Players can guess a single character. The game reports whether this character is contained in the solution.
- The game informs players about the progress which has already been made. The progress is the same as the solution except that characters which have not been guessed before are replaced by underscores. The initial progress of “hello” would be “_____”. After guessing the characters ‘a’, ‘l’, and ‘h’, the progress would be “h_ll_”.
- The game knows when it has been solved, i.e., either if the player has guessed the entire solution or has guessed all characters contained in the solution.
If you are interested in a more sophisticated game, you should consider implementing the following additional requirements.
- The correctness of a guess should be evaluated case insensitively for both individual characters and entire solutions.
- Besides being non-empty, a valid solution should only consist of letters, spaces, and dashes.
- A custom exception should be thrown in case of an invalid solution.
- Players should not be allowed to guess an invalid solution.
- The game keeps track of bad guesses.
- The game sets a limit on bad guesses.
- Dashes and spaces in the solution should be considered known from the start. The initial progress of “Hello world” should be “_____ _____”.
- For solo-play, the game should be able to choose a random solution from a file.
- The game draws an actual gallows as failed guesses accumulate.
- Write an actual executable which interacts with players. Do not forget to implement corresponding integration tests.
There! That should keep you busy for a while…