You are on page 1of 2

Hangman game in C

This is a simple console-based Hangman game written in C. It prompts the user to enter a word,
and then allows them to guess letters until they either guess the word correctly or run out of
guesses.

Header Files

The following header files are included in the program:

#include <stdio.h>

#include <string.h>

#include <time.h>

#include <stdlib.h>

These headers are used for input/output operations, string handling, time functions, and
standard library functions.

Variables

The program declares the following variables:

cCopy code
char word[ 20 ], guess[ 20 ]; // the word to be guessed and the current guess int length, i, num_guesses = 0 ,
max_guesses, score = 100 ; // game variables time_t start, end; // variables to measure time taken to guess the
word double time_taken; // stores the difference between start and end times as a double int difficulty; // stores
the user's chosen difficulty level

The word variable stores the word to be guessed, while guess stores the current state of
the guessed word (with underscores for unguessed letters). The length variable stores the
length of the word, num_guesses tracks how many incorrect guesses have been made,
max_guesses is the maximum number of guesses allowed for the current difficulty level,
and score tracks the player's score. start and end store the start and end times for the
game, respectively, and time_taken stores the difference between these times as a
double. difficulty stores the user's chosen difficulty level.

Main Function
The main function is the entry point for the program. It first prompts the user to choose
a difficulty level, using a switch statement to set the max_guesses variable based on their
choice. It then prompts the user to enter a word to be guessed, and initializes the guess
variable with underscores for each letter of the word.

The game loop then begins, with the program prompting the user to enter a letter and
checking whether it is in the word. If the letter is not in the word, the program
increments the num_guesses variable and subtracts 10 from the score. The program also
provides a clue after the second and fourth incorrect guesses.

The game loop continues until the player either guesses the word correctly or runs out
of guesses. If the player guesses the word correctly, the program calculates the
bonus_score based on the length of the word and the difficulty level, and adds extra
points to the bonus_score based on how quickly the word was guessed. Finally, the
program prints out the player's total score. If the player runs out of guesses, the
program simply displays the word and a score of 0.

Conclusion

That's a high-level overview of the code you provided. I hope this helps you understand
what the code does and how it works!

You might also like