Skip to content
Tutorials Center
My learning

Topics

Lesson 117 of 135 ยท Projects

Project: Hangman

Build Hangman in C in two stages: game state in a struct with a guessed-letters array, then a full game with a word list, ASCII gallows, lives and input validation.

Hangman is a game of hidden information, and that is exactly what makes it a good C exercise. The program knows a secret word, the player sees only a mask like _ a _ _ m a n, and every guess either reveals letters or costs a life. To build it you need to decide how to represent "which letters have been tried", how to show a word with some letters hidden, and how to draw a picture that changes as the game goes on. None of that needs more than strings, arrays and a struct.

The project uses strings, string functions, structures, arrays of strings and fgets-based input. There are two stages: the game logic with scripted guesses, then the complete game with a word list, a gallows drawing and player input from the Input box.

Stage 1: the state of one game

Everything a round of Hangman needs to remember fits in three values, so we group them in a struct:

C
typedef struct {
    const char *secret;       /* lowercase letters only */
    bool guessed[ALPHABET];   /* guessed[letter - 'a'] */
    int wrong;                /* wrong guesses so far */
} Game;

Remembering guesses with an array of flags. There are 26 possible letters, so a bool array with 26 slots can say, for each letter, whether it was tried. The index comes from character arithmetic: 'a' - 'a' is 0, 'b' - 'a' is 1, and so on up to 'z' - 'a' which is 25. This works on every platform whose letters a to z are contiguous in the character set, which is true for ASCII and UTF-8. (EBCDIC, an old mainframe encoding, is the exception.) Any lookup of the form "is this letter in a set?" can use the same idea, and it is much faster than searching a string each time.

A guess has three possible results. The letter might already have been tried (no penalty), it might be in the word (a hit), or it might not (a miss, and wrong goes up). An enum Result { ALREADY, HIT, MISS } returned from guess_letter makes the caller's code read naturally. The function uses strchr(secret, letter) to ask whether the letter occurs anywhere in the word; it returns a pointer to the first match, or NULL.

Winning. The word is solved when every letter in it has been guessed. is_solved walks over the secret and checks each letter's flag. It does not matter that a letter such as a appears twice: one guess marks both.

Showing the mask. print_mask walks over the secret again and prints either the letter itself or an underscore, depending on the flag. Printing a space after each character makes the blanks easy to count.

The test program below plays a scripted sequence of guesses for the word hangman and prints the state after each one. Look at the wrong column: the guess a is a hit even though a occurs twice in hangman, and e, i, o and u are all misses. Nothing reads the keyboard yet, so you can check the logic before there is a game loop to confuse things.

C Stage 1: game state and guess logic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

A note on the designated initializer in Game game = {.secret = "hangman"};: every member you do not name is set to zero, so guessed starts all false and wrong starts at 0. That is the cheapest way to get a clean start.

Stage 2: the whole game

Stage 2 adds four things: a word list, the gallows picture, a lives counter, and a loop that reads guesses.

Choosing a word. The list is an array of string literals, and rand() % WORD_COUNT picks one. WORD_COUNT is computed as sizeof WORDS / sizeof WORDS[0], so adding a word to the list needs no other change. The cast to size_t keeps the arithmetic unsigned. As in the rock paper scissors project, the seed is fixed here so the page is repeatable; use srand((unsigned)time(NULL)) for real games.

The gallows. Drawing the pictures with printf calls inside if statements would be tedious. Instead, store seven complete pictures, one for each number of wrong guesses from 0 to 6, in an array of strings. Then drawing is just puts(GALLOWS[game->wrong]): the data decides what to show, and the code has no special cases. In a C string literal, a backslash must be written twice (\\) to appear as one backslash, which the arms of the figure need.

Showing what went wrong. The show function prints the picture, the mask, and the wrong letters, found by scanning the 26 flags for letters that were tried but are not in the word. Players often want to see their misses to avoid repeating them.

Validating input. The loop reads a line with fgets. A valid guess is a single letter, in either case. The code accepts the line only when the first character is a letter (isalpha) and the second is the newline (or the end of the string). Digits, punctuation, and longer words get a polite message and cost nothing. A letter that was already guessed also costs nothing. If the input runs out before the game is over, fgets returns NULL and the program stops with a message instead of looping forever.

Ending. The loop runs while the player still has lives and the word is not solved. After it, one if decides between "You saved him" and "Game over", and both reveal the word.

C Stage 2: the full game

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

With this input the word is compiler. The uppercase E (a repeat of e), the digit 7 and the two-letter ab are all rejected without costing a life. Then t, z, x, q, w and y are six wrong letters in a row. The picture grows one step at a time until the last life is gone. Now type the letters o, e, c, m, p, i, l, r on separate lines instead and watch the word fill in instead.

Ideas for going further

  • Several rounds. Wrap the game in a loop that asks "play again?" and keeps a running score. You will need to reset the Game struct for each round: game = (Game){.secret = next_word}; does it in one line.
  • Words from a file. Read one word per line into a dynamic array (see dynamic arrays). Reject words with letters outside a to z, because the flag array cannot index them.
  • Difficulty levels. Choose the number of lives from the word's length: short words are harder to guess, so give more lives.
  • Hints. Reveal one unguessed letter at the cost of a life.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the guessed array use the index letter - 'a' ?

    Characters are small integers, so subtracting 'a' turns the letters a to z into the indexes 0 to 25. That makes "has this letter been guessed?" a single array lookup.
  2. 2. What does strchr(game->secret, letter) == NULL tell guess_letter?

    strchr returns a pointer to the first occurrence of the character, or NULL if there is none. NULL therefore means the letter is not in the word.
  3. 3. Why is the gallows stored as an array of seven strings instead of printed by if statements?

    With the pictures in an array, GALLOWS[wrong] is the whole drawing code. Adding a stage means adding data, not changing logic.
  4. 4. In a C string literal, how do you write a single backslash that should be printed?

    The backslash starts an escape sequence in a string literal, so a literal backslash is written as two in a row. That is how the gallows arms are drawn.

Summary

  • Group what one round of the game needs to remember (secret, guessed, wrong) in a struct, and pass a pointer to it to functions.
  • A bool array indexed by letter - 'a' is a fast, simple set of letters.
  • strchr answers "does this letter occur in the word?"; an enum such as ALREADY, HIT, MISS makes results readable.
  • Store pictures and messages as data (an array of strings) and index it by game state instead of writing a branch per state.
  • Validate input before acting on it: one letter, case-insensitive, no penalty for repeats, a clean exit at the end of input.
  • Designated initializers ({.secret = "hangman"}) zero everything you do not name.

Next: Project: Snake and Ladder, a board game for several players where a lookup table decides every snake and every ladder.