Here is a simple implementation of a Hangman game in C. This version will be text-based and will allow the user to guess letters one at a time.
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAX_WORD_LENGTH 20
#define MAX_GUESSES 10
void initializeGame(char word[], int guesses);
void displayGameState(char word[], int guesses, char guessedLetters[]);
int checkGuess(char guess, char guessedLetters[]);
int main() {
char word[MAX_WORD_LENGTH + 1];
int guesses = MAX_GUESSES;
// Initialize the game with a random word
initializeGame(word, guesses);
char guess;
printf("Welcome to Hangman!\n");
while (guesses > 0 && strcmp(word, guessedLetters) != 0) {
displayGameState(word, guesses, guessedLetters);
printf("Enter your guess (single letter): ");
scanf(" %c", &guess);
guess = tolower(guess); // Convert the guess to lowercase
if (checkGuess(guess, guessedLetters)) {
printf("Good guess!\n");
} else {
printf("Sorry, that letter is not in the word.\n");
guesses--;
}
}
if (strcmp(word, guessedLetters) == 0) {
printf("Congratulations! You guessed the word: %s\n", word);
} else {
printf("Sorry, you ran out of guesses. The word was: %s\n", word);
}
return 0;
}
void initializeGame(char word[], int guesses) {
// This is a placeholder for a function that would generate a random word
// For simplicity, we'll use a static word here
strcpy(word, "hangman");
int length = strlen(word);
char guessedLetters[MAX_WORD_LENGTH + 1] = {0};
for (int i = 0; i < length; i++) {
guessedLetters[i] = '_';
}
}
void displayGameState(char word[], int guesses, char guessedLetters[]) {
printf("Word: %s\n", guessedLetters);
printf("Guesses left: %d\n", guesses);
}
int checkGuess(char guess, char guessedLetters[]) {
for (int i = 0; i < strlen(word); i++) {
if (guessedLetters[i] == '_' && word[i] == guess) {
guessedLetters[i] = guess;
return 1;
}
}
return 0;
}
This code initializes a game with a static word "hangman" and allows the user to guess letters one at a time. The game continues until the user either guesses the word correctly or runs out of guesses. The initializeGame function is a placeholder for a function that would generate a random word. You can replace the static word with a function that generates a random word from a list of words.
Please note that this is a simple implementation and can be improved in various ways, such as adding a user interface, handling uppercase letters, and using a more sophisticated word generation algorithm.