Sure, I'd be happy to help you with that! Here's a simple implementation of a Hangman game in C language:
c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define MAX_GUESSES 6
#define MAX_WORD_LENGTH 20
void generate_word(char *word) {
const char *word_list[] = {
"apple", "banana", "cherry", "date", "elderberry", "fig", "grape",
"honeydew", "kiwi", "lemon", "mango", "nectarine", "orange", "pear",
"pineapple", "quince", "raspberry", "strawberry", "tangerine", "watermelon"
};
int num_words = sizeof(word_list) / sizeof(word_list[0]);
srand(time(NULL));
strcpy(word, word_list[rand() % num_words]);
}
void print_hangman(int guesses_left) {
printf(" +---+\n");
printf(" | |\n");
if (guesses_left < 6) {
printf(" O |\n");
} else {
printf(" |\n");
}
if (guesses_left < 5) {
printf(" /");
if (guesses_left < 4) {
printf("|");
}
printf(" |\n");
} else {
printf(" |\n");
}
if (guesses_left < 3) {
printf(" /");
if (guesses_left < 2) {
printf(" \\");
}
printf(" |\n");
} else {
printf(" |\n");
}
if (guesses_left < 1) {
printf(" |\n");
printf(" =|\n");
printf(" |\n");
printf(" / \\ \n");
} else {
printf(" |\n");
printf(" |\n");
printf(" |\n");
printf(" |\n");
}
printf("=======\n");
}
int main() {
char word[MAX_WORD_LENGTH];
char guessed_letters[26];
int guesses_left = MAX_GUESSES;
int correct_guesses = 0;
generate_word(word);
while (guesses_left > 0 && correct_guesses < strlen(word)) {
print_hangman(guesses_left);
printf("Guess a letter: ");
char guess;
scanf(" %c", &guess);
if (strchr(guessed_letters, guess) != NULL) {
printf("You already guessed that letter.\n");
continue;
}
guessed_letters[guess - 'a'] = guess;
if (strchr(word, guess) == NULL) {
printf("Sorry, that letter is not in the word.\n");
guesses_left--;
} else {
printf("Good job! That letter is in the word.\n");
correct_guesses++;
}
}
if (correct_guesses == strlen(word)) {
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;
}
This program generates a random word from a list of fruits and allows the user to guess letters until they either guess the word correctly or run out of guesses. The program also displays a simple ASCII art representation of the hangman based on the number of guesses left.