How to Create Hangman Game in C Programming

Faraz

By Faraz -

Learn how to create a Hangman game in C programming with an eye-catching menu interface. Follow our step-by-step guide to develop a fun and interactive game.


how-to-create-hangman-game-in-c-programming.webp

Creating a Hangman game in C programming is a great way to practice coding and design a user-friendly interface. In this tutorial, we will build a Hangman game that includes a visual representation of the "hanged man" and limits the user to 6 incorrect attempts. Follow along to create a fun and interactive game!

Introduction

Hangman is a word-guessing game where players try to guess a hidden word by suggesting letters. If they fail to guess the word within a limited number of attempts, they lose the game. This project will teach you how to code the Hangman game in C, design a simple menu interface, and implement a visual "hanged man" to enhance the user experience.

Step-by-Step Guide

1. Setting Up the Environment

First, ensure you have a C compiler installed on your system. You can use popular IDEs like Code::Blocks, Dev-C++, or any text editor with a command-line compiler.

2. Creating the Basic Structure

Create a new C file (e.g., hangman.c) and start with the basic structure of the program. Include the necessary header files:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <time.h>

3. Designing the Menu Interface

Design a simple and eye-catching menu interface to help users navigate the game:

void displayMenu() {
    printf("*********************************\n");
    printf("*        Hangman Game Menu       *\n");
    printf("*********************************\n");
    printf("* 1. Start New Game              *\n");
    printf("* 2. Exit                        *\n");
    printf("*********************************\n");
    printf("Choose an option: ");
}

4. Implementing the Game Logic

Next, implement the core game logic. We'll create a function to start a new game, show the current state of the word, handle user guesses, and display the hanged man.

void displayHangman(int attempts) {
    switch (attempts) {
        case 6:
            printf("  +---+\n  |   |\n      |\n      |\n      |\n      |\n=========\n");
            break;
        case 5:
            printf("  +---+\n  |   |\n  O   |\n      |\n      |\n      |\n=========\n");
            break;
        case 4:
            printf("  +---+\n  |   |\n  O   |\n  |   |\n      |\n      |\n=========\n");
            break;
        case 3:
            printf("  +---+\n  |   |\n  O   |\n /|   |\n      |\n      |\n=========\n");
            break;
        case 2:
            printf("  +---+\n  |   |\n  O   |\n /|\\  |\n      |\n      |\n=========\n");
            break;
        case 1:
            printf("  +---+\n  |   |\n  O   |\n /|\\  |\n /    |\n      |\n=========\n");
            break;
        case 0:
            printf("  +---+\n  |   |\n  O   |\n /|\\  |\n / \\  |\n      |\n=========\n");
            break;
    }
}

void startNewGame() {
    char* words[] = {"programming", "gadget", "syntax", "keyboard", "function"};
    int numWords = sizeof(words) / sizeof(words[0]);
    srand(time(NULL));
    int wordIndex = rand() % numWords;
    char* word = words[wordIndex];
    char guess;
    int i;
    int correctGuesses = 0;
    int wordLength = strlen(word);
    char guessed[wordLength + 1];
    int attempts = 6;
    int alreadyGuessed[256] = {0}; // Array to keep track of guessed letters

    // Initialize guessed array with underscores
    for (i = 0; i < wordLength; i++) {
        guessed[i] = '_';
    }
    guessed[wordLength] = '\0';  // Null-terminate the string

    printf("\nWelcome to Hangman!\n");

    while (attempts > 0 && correctGuesses < wordLength) {
        printf("\nWord: %s\n", guessed);
        printf("Attempts remaining: %d\n", attempts);
        displayHangman(attempts);
        printf("Enter your guess: ");
        scanf(" %c", &guess);
        guess = tolower(guess);

        // Check if the letter has already been guessed
        if (alreadyGuessed[(int)guess]) {
            printf("You've already guessed '%c'. Try a different letter.\n", guess);
            continue;
        }

        alreadyGuessed[(int)guess] = 1; // Mark this letter as guessed

        int found = 0;
        for (i = 0; i < wordLength; i++) {
            if (tolower(word[i]) == guess) {
                if (guessed[i] == '_') {
                    guessed[i] = word[i];
                    correctGuesses++;
                    found = 1;
                }
            }
        }

        if (!found) {
            attempts--;
            printf("Wrong guess!\n");
        }
    }

    if (correctGuesses == wordLength) {
        printf("\nCongratulations! You've guessed the word: %s\n", word);
    } else {
        displayHangman(attempts);
        printf("\nGame Over! The word was: %s\n", word);
    }
}

5. Handling User Input

Handle user input to navigate between the menu and the game:

int main() {
    int option;

    while (1) {
        displayMenu();
        scanf("%d", &option);

        switch (option) {
            case 1:
                startNewGame();
                break;
            case 2:
                printf("Exiting game. Goodbye!\n");
                exit(0);
            default:
                printf("Invalid option. Please try again.\n");
                break;
        }
    }

    return 0;
}

Compiling and Running the Program

Once you've written the code, it's time to compile and run it.

  1. Compile the Code: If you're using GCC, open your terminal and navigate to the directory containing your code file. Run the following command:
    gcc hangman.c -o hangman
    This will compile the code and create an executable file named hangman.
  2. Run the Program: After compiling, In the same Command Prompt window, type:
    hangman
    Running this executable will start the game.

Conclusion

In this tutorial, you learned how to create a Hangman game in C programming with an eye-catching menu interface and a visual representation of the "hanged man." We covered the basics of setting up the environment, designing the menu, implementing game logic with a limited number of attempts, and handling user input. This project provides a fun and interactive way to enhance your programming skills.

Feel free to build upon this project by adding more features or improving the user interface.

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺