Below is a simple puzzle game written in C using the standard library. The game is a basic number puzzle where the player has to guess a randomly generated number within a certain range.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MIN_NUMBER 1
#define MAX_NUMBER 100
#define MAX_ATTEMPTS 10
void playGame() {
int secretNumber, guess, attempts = 0;
// Seed the random number generator
srand(time(NULL));
secretNumber = (rand() % (MAX_NUMBER - MIN_NUMBER + 1)) + MIN_NUMBER;
printf("Welcome to the Number Guessing Game!\n");
printf("I have selected a number between %d and %d. You have %d attempts to guess it.\n", MIN_NUMBER, MAX_NUMBER, MAX_ATTEMPTS);
while (attempts < MAX_ATTEMPTS) {
printf("Attempt %d/%d: Enter your guess: ", attempts + 1, MAX_ATTEMPTS);
scanf("%d", &guess);
attempts++;
if (guess < secretNumber) {
printf("Too low!\n");
} else if (guess > secretNumber) {
printf("Too high!\n");
} else {
printf("Congratulations! You've guessed the number %d in %d attempts.\n", secretNumber, attempts);
return;
}
}
printf("Sorry, you've used all your attempts. The secret number was %d.\n", secretNumber);
}
int main() {
char playAgain;
do {
playGame();
printf("Do you want to play again? (y/n): ");
scanf(" %c", &playAgain); // Note the space before %c to consume the newline character
} while (playAgain == 'y' || playAgain == 'Y');
printf("Thanks for playing!\n");
return 0;
}
How the Game Works:
- Random Number Generation: The program generates a random number between
MIN_NUMBER (1) and MAX_NUMBER (100) using the rand() function.
- User Input: The player is prompted to guess the number. The program reads the input using
scanf().
- Feedback: After each guess, the program provides feedback ("Too low!", "Too high!", or "Congratulations!").
- Attempts Limit: The player has a limited number of attempts (
MAX_ATTEMPTS, set to 10). If the player runs out of attempts, the game reveals the secret number.
- Play Again: After each game, the player is asked if they want to play again.
Compilation and Execution:
To compile and run this program, save it to a file named guess_game.c and use a C compiler like gcc:
gcc -o guess_game guess_game.c
./guess_game
This simple game demonstrates basic C concepts like input/output, random number generation, loops, and conditional statements. Enjoy coding and playing!