Matchstick Game
C program for a matchstick game being played between the computer and a user. Your program should ensure that the computer always wins. Rules for the game are as follows:
There are 21 matchsticks.
The computer asks the player to pick 1, 2, 3, or 4 matchsticks.
After the person picks, the computer does its picking.
Whoever is forced to pick up the last matchstick loses the game.
Program
#include<stdio.h>
#include<conio.h>
void main()
{
int matchsticks=21, user, computer;
printf("Rules of the game \n\n");
printf("1. There are 21 matchsticks \n");
printf("2. The computer asks the player to pick 1,2,3 or 4 matchsticks \n");
printf("3. After you picks, the computer does its picking.\n");
printf("4. Whoever is forced to pick the last matchstick loses the game\n");
printf("\n\t\tLET THE GAME BEGINS");
while (matchsticks>1)
{
printf("\n\nMatchsticks left %d.", matchsticks);
printf("\nPick up the matchstick(s)-- (1-4): ");
scanf ("%d", &user);
if((user != 1) && (user != 2) && (user != 3) && (user != 4))
{
printf("Invalid Selection...");
break;
}
if (user>4)
{
printf("Invalid Selection");
break;
}
computer=5-user;
printf("Computer chooses:%d", computer);
matchsticks=matchsticks-user-computer;
}
if(matchsticks == 1)
{
printf("\n\nmatchsticks left 1");
printf("\nYou have to pick the last matchstick so....");
printf("\nComputer Wins");
}
getch();
}
Output
Rules of the game
1. There are 21 matchsticks
2. The computer asks the player to pick 1,2,3 or 4 matchsticks
3. After you picks, the computer does its picking.
4. Whoever is forced to pick the last matchstick loses the game
LET THE GAME BEGINS
Matchsticks left 21.
Pick up the matchstick(s)-- (1-4): 3
Computer chooses:2
Matchsticks left 16.
Pick up the matchstick(s)-- (1-4): 2
Computer chooses:3
Matchsticks left 11.
Pick up the matchstick(s)-- (1-4): 4
Computer chooses:1
Matchsticks left 6.
Pick up the matchstick(s)-- (1-4): 3
Computer chooses:2
matchsticks left 1
You have to pick the last matchstick so....
Computer Wins