Open In App

Hangman Game in C

Last Updated : 11 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Hangman game is a popular and simple game in which the player has to guess the word based on the given hint. In this article, we will write a program for the hangman game using C programming language.

What is the Hangman Game?

Hangman is a word puzzle game that involves:

  • A secret word: A word is selected and its number of characters is displayed to the user. The player then has to guess each letter of the word.
  • Limited attempts: The guessing player has a fixed number of tries (usually six) to guess the word.
  • Display: The game displays the partially guessed word with blanks for unguessed letters.
  • Winning/Losing: The guessing player wins if they think is the word within the allowed attempts; otherwise, they lose.

There is a graphical representation of a person who keeps getting closer to hanging whenever a wrong guess is made hence the name “Hangman”

hangman game in c

 

The game challenges players’ word-guessing skills and deductive reasoning.

Logic Behind the Game

The logic of the Hangman program is to take a secret word and guess it letter by letter. The player has a limited number of wrong guesses before they lose the game. If the player guesses all of the letters in the word correctly before running out of guesses, they win the game.

The program works by keeping track of the following information:

  • The secret word
  • The letters that have been guessed
  • The number of wrong guesses

In each iteration of the game loop, the program displays the current state of the guessed word and asks the player to guess a letter. The program then checks if the guessed letter has already been guessed. If it has, the program prompts the player to guess again. If the guessed letter has not already been guessed, the program checks if it is in the secret word. If it is, the program updates the guessed word to include the letter. If the guessed letter is not in the secret word, the program increments the number of wrong guesses.

The game loop continues until the player either guesses the secret word correctly or runs out of guesses. If the player guesses the secret word correctly, the program displays a message congratulating them and the game ends. If the player runs out of guesses, the program displays a message revealing the secret word and the game ends.

Here is a more concise explanation of the logic:

while (not guessed and not out of guesses):
    display word to be guessed
    get player guess
    if guess is not already guessed:
        check if guess is in secret word
        if guess is in secret word:
            update guessed word
       else:
           increment number of wrong guesses

This logic can be implemented in any programming language. Here we use the C programming language.

C Program for Hangman Game

C




// C program to implement hangman game
#include <ctype.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
 
#define MAX_WORD_LENGTH 50
#define MAX_TRIES 6
 
// Struct to hold a word and its hint
struct WordWithHint {
    char word[MAX_WORD_LENGTH];
    char hint[MAX_WORD_LENGTH];
};
 
// Function to display the current state of the word
void displayWord(const char word[], const bool guessed[]);
 
// Function to draw the hangman
void drawHangman(int tries);
 
// driver code
int main()
{
    // Seed the random number generator with the current
    // time
    srand(time(NULL));
    // Array of words with hints
    struct WordWithHint wordList[] = {
        { "geeksforgeeks", "Computer coding" },
        { "elephant", "A large mammal with a trunk" },
        { "pizza", "A popular Italian dish" },
        { "beach", "Sandy shore by the sea" },
        // Add more words and hints here
    };
 
    // Select a random word from the list
    int wordIndex = rand() % 4;
 
    const char* secretWord = wordList[wordIndex].word;
    const char* hint = wordList[wordIndex].hint;
 
    int wordLength = strlen(secretWord);
    char guessedWord[MAX_WORD_LENGTH] = { 0 };
    bool guessedLetters[26] = { false };
 
    printf("Welcome to Hangman!\n");
    printf("Hint: %s\n", hint);
 
    int tries = 0;
 
    while (tries < MAX_TRIES) {
        printf("\n");
        displayWord(guessedWord, guessedLetters);
        drawHangman(tries);
 
        char guess;
        printf("Enter a letter: ");
        scanf(" %c", &guess);
        guess = tolower(guess);
 
        if (guessedLetters[guess - 'a']) {
            printf("You've already guessed that letter. "
                   "Try again.\n");
            continue;
        }
 
        guessedLetters[guess - 'a'] = true;
 
        bool found = false;
        for (int i = 0; i < wordLength; i++) {
            if (secretWord[i] == guess) {
                found = true;
                guessedWord[i] = guess;
            }
        }
 
        if (found) {
            printf("Good guess!\n");
        }
        else {
            printf("Sorry, the letter '%c' is not in the "
                   "word.\n",
                   guess);
            tries++;
        }
 
        if (strcmp(secretWord, guessedWord) == 0) {
            printf("\nCongratulations! You've guessed the "
                   "word: %s\n",
                   secretWord);
            break;
        }
    }
 
    if (tries >= MAX_TRIES) {
        printf("\nSorry, you've run out of tries. The word "
               "was: %s\n",
               secretWord);
    }
 
    return 0;
}
 
void displayWord(const char word[], const bool guessed[])
{
    printf("Word: ");
    for (int i = 0; word[i] != '\0'; i++) {
        if (guessed[word[i] - 'a']) {
            printf("%c ", word[i]);
        }
        else {
            printf("_ ");
        }
    }
    printf("\n");
}
 
void drawHangman(int tries)
{
    const char* hangmanParts[]
        = { "     _________",    "    |         |",
            "    |         O",   "    |        /|\\",
            "    |        / \\", "    |" };
 
    printf("\n");
    for (int i = 0; i <= tries; i++) {
        printf("%s\n", hangmanParts[i]);
    }
}


Output 1

Welcome to Hangman!
Hint: Computer coding

Word: 

     _________
Enter a letter: g
Good guess!

Word: g 

     _________
Enter a letter: e
Good guess!

Word: g e e 

     _________
Enter a letter: f
Good guess!

Word: g e e 

     _________
Enter a letter: o
Good guess!

Word: g e e 

     _________
Enter a letter: r
Good guess!

Word: g e e 

     _________
Enter a letter: s
Good guess!

Word: g e e 

     _________
Enter a letter: k
Good guess!

Congratulations! You've guessed the word: geeksforgeeks

Output 2

Welcome to Hangman!
Hint: A large mammal with a trunk

Word: 

     _________
Enter a letter: g
Sorry, the letter 'g' is not in the word.

Word: 

     _________
    |         |
Enter a letter: r
Sorry, the letter 'r' is not in the word.

Word: 

     _________
    |         |
    |         O
Enter a letter: a
Good guess!

Word: 

     _________
    |         |
    |         O
Enter a letter: i
Sorry, the letter 'i' is not in the word.

Word: 

     _________
    |         |
    |         O
    |        /|\
Enter a letter: f
Sorry, the letter 'f' is not in the word.

Word: 

     _________
    |         |
    |         O
    |        /|\
    |        / \
Enter a letter: v
Sorry, the letter 'v' is not in the word.

Word: 

     _________
    |         |
    |         O
    |        /|\
    |        / \
    |
Enter a letter: x
Sorry, the letter 'x' is not in the word.

Sorry, you've run out of tries. The word was: elephant


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads