Sure! Here's a simple implementation of a basic Hangman game in C. This version uses a fixed word and allows the user to guess letters until they either guess the word or run out of attempts.
Basic Hangman Game in C
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX_TRIES 6
#define WORD_LENGTH 100
int main() {
char word[] = "computer"; // The word to guess
char guessed[strlen(word) + 1];
int tries = 0;
int correct = 0;
int wordLength = strlen(word);
int i;
char guess;
// Initialize guessed word with underscores
for (i = 0; i < wordLength; i++) {
guessed[i] = '_';
}
guessed[wordLength] = '\0';
printf("Welcome to Hangman!\n");
while (tries < MAX_TRIES && correct < wordLength) {
printf("\nWord: ");
for (i = 0; i < wordLength; i++) {
printf("%c ", guessed[i]);
}
printf("\nGuess a letter: ");
scanf(" %c", &guess);
guess = tolower(guess);
int found = 0;
for (i = 0; i < wordLength; i++) {
if (word[i] == guess && guessed[i] == '_') {
guessed[i] = guess;
correct++;
found = 1;
}
}
if (!found) {
tries++;
printf("Wrong guess! Tries left: %d\n", MAX_TRIES - tries);
} else {
printf("Good guess!\n");
}
}
if (correct == wordLength) {
printf("\nCongratulations! You guessed the word: %s\n", word);
} else {
printf("\nGame over! The word was: %s\n", word);
}
return 0;
}
How It Works:
- The word to guess is hardcoded as
"computer".
- The player has 6 tries to guess the word.
- The program displays the word with underscores for unguessed letters.
- The player inputs one letter at a time.
- If the letter is in the word, it is revealed in the correct position(s).
- If the letter is not in the word, the number of remaining tries decreases.
- The game ends when the player guesses the word or runs out of tries.
To Compile and Run:
gcc hangman.c -o hangman
./hangman
Enhancements You Can Add:
- Randomly select a word from a list.
- Keep track of already guessed letters.
- Add ASCII art for the hangman.
- Allow full word guesses.
Let me know if you'd like help adding any of these features!