Hangman Game In C: A Fun Programming Project
Hey guys! Today, we're diving into a super cool and classic project: creating a Hangman game using the C programming language. This project is perfect for beginners and intermediate programmers alike because it touches on various fundamental concepts such as string manipulation, loops, conditional statements, and basic input/output operations. Plus, it’s a whole lot of fun to build and play! So, grab your favorite code editor, and let's get started on making our very own Hangman game.
What is Hangman?
Before we jump into the code, let's quickly recap what Hangman is all about. In this game, one player thinks of a word, and the other player tries to guess it by suggesting letters. For every incorrect guess, a part of a hangman figure is drawn. If the hangman is completed before the word is guessed, the guessing player loses. If the player guesses the word before the hangman is fully drawn, they win. It's a simple yet engaging game that tests your vocabulary and guessing skills.
Project Overview
Our Hangman game in C will involve the following key components:
- Word Selection: A list of words from which the game randomly selects one for the player to guess.
- Displaying the Word: Showing the player the current state of the word, with unguessed letters represented by underscores.
- Input Handling: Receiving letter guesses from the player.
- Guess Validation: Checking if the guessed letter is in the word.
- Updating Game State: Revealing correctly guessed letters and drawing parts of the hangman for incorrect guesses.
- Win/Lose Condition: Determining when the game is won or lost.
Now that we have a clear idea of what we're building, let's dive into the coding part!
Setting Up the Development Environment
First things first, make sure you have a C compiler installed on your system. If you're on Windows, you can use MinGW or Cygwin. On macOS, you likely already have Xcode Command Line Tools installed. For Linux users, GCC is the go-to option. Once you have your compiler ready, you'll need a text editor or an Integrated Development Environment (IDE) to write your code. Popular choices include VSCode, Sublime Text, Code::Blocks, and Eclipse. Choose the one you're most comfortable with, create a new .c file (e.g., hangman.c), and let's start coding!
Basic Structure of the C Program
Every C program begins with including necessary header files and defining the main function. These headers provide access to functions that handle input/output, string manipulation, and other essential operations. The main function is where the execution of your program starts. Here's a basic skeleton to get you started:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
int main() {
// Game logic will go here
return 0;
}
We've included stdio.h for standard input/output functions like printf and scanf, stdlib.h for general utility functions like rand and srand, string.h for string manipulation functions like strlen and strcmp, time.h for generating a seed for the random number generator, and ctype.h for character-handling functions like toupper. Make sure you save this file with a .c extension.
Implementing the Hangman Game Logic
1. Word Selection
Let's start by creating a list of words that our game can choose from. We'll store these words in a string array. Then, we'll use a random number generator to select a word from this list. This ensures that the game is different each time you play.
const char *wordList[] = {
"apple", "banana", "cherry", "date", "elderberry",
"fig", "grape", "honeydew", "kiwi", "lemon",
"mango", "nectarine", "orange", "papaya", "quince"
};
int numWords = sizeof(wordList) / sizeof(wordList[0]);
// Function to select a random word from the list
const char *chooseWord() {
srand(time(NULL)); // Seed the random number generator
int index = rand() % numWords;
return wordList[index];
}
Here, wordList is an array of strings, each representing a word. numWords calculates the number of words in the array. The chooseWord function uses srand(time(NULL)) to seed the random number generator with the current time, ensuring that a different sequence of random numbers is generated each time the program runs. It then selects a random word from the wordList and returns it.
2. Displaying the Word
Next, we need a way to display the word to the player, hiding the letters that haven't been guessed yet. We'll use underscores to represent these hidden letters. For example, if the word is "apple" and the player hasn't guessed any letters yet, we'll display "[-----]" on the screen.
// Function to initialize the display word with underscores
void initializeDisplayWord(const char *word, char *displayWord) {
int wordLength = strlen(word);
for (int i = 0; i < wordLength; i++) {
displayWord[i] = '_';
}
displayWord[wordLength] = '\0'; // Null-terminate the string
}
This function takes the selected word and an empty displayWord array as input. It iterates through each character of the word and replaces it with an underscore in the displayWord array. Finally, it adds a null terminator to make it a valid C-string.
3. Input Handling
Now, let's handle the player's input. We need to prompt the player to guess a letter and read their input from the console. We'll use scanf to read the input, and toupper to convert the input to uppercase to handle both uppercase and lowercase guesses.
// Function to get a letter guess from the player
char getGuess() {
char guess;
printf("Guess a letter: ");
scanf(" %c", &guess); // Note the space before %c to consume any leading whitespace
return toupper(guess);
}
The getGuess function prompts the player to enter a letter. The scanf function reads the input, and the space before %c is important because it consumes any leading whitespace characters (like newline characters) that might be left in the input buffer from previous inputs. toupper converts the guessed letter to uppercase to simplify the comparison later.
4. Guess Validation
Once we have the player's guess, we need to check if the guessed letter is in the selected word. If it is, we'll reveal the letter in the displayWord. If not, we'll increment the number of incorrect guesses.
// Function to check if the guessed letter is in the word
bool checkGuess(const char *word, char guess, char *displayWord) {
bool correctGuess = false;
int wordLength = strlen(word);
for (int i = 0; i < wordLength; i++) {
if (toupper(word[i]) == guess) {
displayWord[i] = word[i];
correctGuess = true;
}
}
return correctGuess;
}
The checkGuess function iterates through each character of the word and compares it (in uppercase) to the guessed letter. If a match is found, it updates the corresponding position in the displayWord with the correct letter and sets correctGuess to true. Finally, it returns true if the guess was correct, and false otherwise.
5. Updating Game State
We need to keep track of the number of incorrect guesses and draw the hangman accordingly. We'll also update the displayWord with correctly guessed letters.
// Function to draw the hangman
void drawHangman(int incorrectGuesses) {
printf(" -------\n");
printf(" | |\n");
printf(" | %c\n", (incorrectGuesses > 0) ? 'O' : ' ');
printf(" | %c%c%c\n", (incorrectGuesses > 3) ? '/' : ' ', (incorrectGuesses > 1) ? '|' : ' ', (incorrectGuesses > 4) ? '\\' : ' ');
printf(" | %c %c\n", (incorrectGuesses > 2) ? '/' : ' ', (incorrectGuesses > 5) ? '\\' : ' ');
printf(" |\n");
printf("-----------\n");
}
The drawHangman function takes the number of incorrect guesses as input and prints the corresponding hangman figure to the console. Depending on the number of incorrect guesses, different parts of the hangman are drawn. This visual representation adds to the game's appeal.
6. Win/Lose Condition
Finally, we need to check if the player has won or lost the game. The player wins if they've correctly guessed all the letters in the word. They lose if they make too many incorrect guesses (e.g., 6).
// Function to check if the player has won
bool hasWon(const char *word, const char *displayWord) {
return strcmp(word, displayWord) == 0;
}
// Function to check if the player has lost
bool hasLost(int incorrectGuesses) {
return incorrectGuesses >= MAX_INCORRECT_GUESSES;
}
The hasWon function compares the original word with the displayWord. If they are identical, the player has won. The hasLost function checks if the number of incorrect guesses has reached the maximum allowed (defined by MAX_INCORRECT_GUESSES).
Putting It All Together
Now that we have all the individual components, let's put them together into the main function to create the complete Hangman game.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <ctype.h>
#include <stdbool.h>
#define MAX_WORD_LENGTH 50
#define MAX_INCORRECT_GUESSES 6
const char *wordList[] = {
"apple", "banana", "cherry", "date", "elderberry",
"fig", "grape", "honeydew", "kiwi", "lemon",
"mango", "nectarine", "orange", "papaya", "quince"
};
int numWords = sizeof(wordList) / sizeof(wordList[0]);
const char *chooseWord() {
srand(time(NULL));
int index = rand() % numWords;
return wordList[index];
}
void initializeDisplayWord(const char *word, char *displayWord) {
int wordLength = strlen(word);
for (int i = 0; i < wordLength; i++) {
displayWord[i] = '_';
}
displayWord[wordLength] = '\0';
}
char getGuess() {
char guess;
printf("Guess a letter: ");
scanf(" %c", &guess);
return toupper(guess);
}
bool checkGuess(const char *word, char guess, char *displayWord) {
bool correctGuess = false;
int wordLength = strlen(word);
for (int i = 0; i < wordLength; i++) {
if (toupper(word[i]) == guess) {
displayWord[i] = word[i];
correctGuess = true;
}
}
return correctGuess;
}
void drawHangman(int incorrectGuesses) {
printf(" -------\n");
printf(" | |\n");
printf(" | %c\n", (incorrectGuesses > 0) ? 'O' : ' ');
printf(" | %c%c%c\n", (incorrectGuesses > 3) ? '/' : ' ', (incorrectGuesses > 1) ? '|' : ' ', (incorrectGuesses > 4) ? '\\' : ' ');
printf(" | %c %c\n", (incorrectGuesses > 2) ? '/' : ' ', (incorrectGuesses > 5) ? '\\' : ' ');
printf(" |\n");
printf("-----------\n");
}
bool hasWon(const char *word, const char *displayWord) {
return strcmp(word, displayWord) == 0;
}
bool hasLost(int incorrectGuesses) {
return incorrectGuesses >= MAX_INCORRECT_GUESSES;
}
int main() {
const char *word = chooseWord();
int wordLength = strlen(word);
char displayWord[MAX_WORD_LENGTH];
initializeDisplayWord(word, displayWord);
int incorrectGuesses = 0;
char guess;
printf("Welcome to Hangman!\n");
while (!hasWon(word, displayWord) && !hasLost(incorrectGuesses)) {
printf("\nWord: %s\n", displayWord);
drawHangman(incorrectGuesses);
guess = getGuess();
if (!checkGuess(word, guess, displayWord)) {
incorrectGuesses++;
printf("Incorrect guess!\n");
} else {
printf("Correct guess!\n");
}
}
if (hasWon(word, displayWord)) {
printf("\nCongratulations! You guessed the word: %s\n", word);
} else {
printf("\nYou ran out of guesses! The word was: %s\n", word);
drawHangman(incorrectGuesses);
}
return 0;
}
Compiling and Running the Game
To compile your Hangman game, open your terminal or command prompt and navigate to the directory where you saved the hangman.c file. Then, use the following command:
gcc hangman.c -o hangman
This command tells the GCC compiler to compile the hangman.c file and create an executable file named hangman. Once the compilation is successful, you can run the game by typing:
./hangman
This will start the game, and you can start guessing letters to try and figure out the hidden word. Have fun!
Enhancements and Further Ideas
Our Hangman game is now functional, but there's always room for improvement and additional features. Here are a few ideas to take your project to the next level:
- Add a Word List from a File: Instead of hardcoding the word list in the program, read the words from a text file. This makes it easy to add or remove words without modifying the code.
- Implement a Score System: Keep track of the player's score and display it at the end of the game.
- Add Difficulty Levels: Allow the player to choose a difficulty level, which affects the length of the words used in the game and the number of allowed incorrect guesses.
- Create a Graphical Interface: Use a graphics library like SDL or OpenGL to create a more visually appealing game with buttons, images, and animations.
- Implement Error Handling: Add error handling to handle invalid input, such as non-letter characters or repeated guesses.
Conclusion
So, there you have it! We've successfully built a Hangman game using the C programming language. This project not only reinforces your understanding of fundamental programming concepts but also provides a fun and engaging way to practice your coding skills. Remember, the best way to learn is by doing, so don't hesitate to experiment with the code, add new features, and make it your own. Happy coding, and may your hangman always be spared!
This project is a fantastic stepping stone for anyone looking to improve their programming skills. Keep practicing, keep building, and most importantly, keep having fun! And who knows, maybe your Hangman game will be the next big hit!