Matchstick Game using C Programming

Write a 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.


-There are 21 matchsticks.
-Whoever is forced to pick up the last matchstick loses the game.
So the last one is special, so it's all about how to get rid of 20 matches in pairs of turns.

-The computer asks the player to pick 1, 2, 3 or 4 matchsticks.
So if we reduce the total by 5 each round, the sequence will go
21 16 11 6 1
In effect, whatever number the user picks (n), the computer picks 5-n



#include<stdio.h>
main()
{

int matchsticks=21, user, computer;

printf("Do not enter Invalid Numbers.\nNumbers above 4 are invalid.");

printf("\nIf you do so, the computer automatically wins.");

while (matchsticks>=1)
{

printf("\nNumber of matchsticks available right now is %d.", matchsticks);

printf("\n\nYour Turn...\n\n\n");

printf("\nPick up the matchstick(s)-- (1-4): ");
scanf ("%d", &user);

if (user>4)

{
printf("Invalid Selection");
break;
}

computer=5-user;

printf("\nComputer's Turn..\n" );
printf("\nComputer chooses:%d", computer);

matchsticks=matchsticks-user-computer;
continue;

if(matchsticks==1)

break;
}

matchsticks--;
printf("\nComputer Wins");

}



Comments

Anonymous said…
The logic behind your program is very impressive. Who'd have ever thought of this gem - "21 16 11 6 1"
As a MS student of BITS,pilani this program is really useful to me.Logic is really good.Thank you
maddy said…
Hi i hav a doubt in this code ..wher the case zero is handeled ?..what will happen if user chooses zero for his turn ? and how come C Compiler allows break statement as used in the code .. please help me on these doubts..
Anonymous said…
Hi.. Thanks for sharing your useful programs! And this one is pure genius. Just wanted to point out that the matchstick--; subtracts an extra matchstick.. Doesn't it? So at one point the computer picks up more matchsticks than available. 21 16 11 6 1 sequence occurs without that statement. And why is it outside the while loop??
Anonymous said…
Would elaborate it more in words. u see for beginners it may be difficult.Thanks!
arun arya said…
yes its good idea for implementing this game.
but this is given for only 21 matchsticks.

I got the mathematical logic for general use...


n2(square)+n+1=matchsticks(given by the user itself) .

here

positive root(let us say 'x') for given equation is the maximum number of sticks to be selected.

and

[(x+1)-user] gives the number selected by the computer

thats it and the logic is followed
Arjun Kumar said…
hey man you're a gem really........
the logic is wonderful, but how to put forth in a program
s u s h a n t said…
thanks a lot friend.
you're simply brilliant!
i tried this program for 4 days and couldn't find a solution...
thanks once again!
Anonymous said…
Thanks for this program...I agreed with others that logic is really good...
surya said…
become a follower for free C,C++ And vb code of my blog:
http://www.a2zhacks.blogspot.com to learn C,C++,VB programming.
sourabh said…
nice logic :)
thanks
i spent 1/2 day thinkin its logic...
gave up and finally searched this post ...
Cheers
Sourabh
Unknown said…
hey which heuristic is this program using..
shiva said…
what a great logical sense you have!
You are just great
Anonymous said…
great yaar.............
have a sharp mind.
Avinash said…
one more logic is to pick same number of matchstick as user picks up...I believe in this case too the computer will always win. It works for odd numbers.
Akash Gupta said…
the program logic is right but this is the better revised version of your program.try this......
#include
#include
void main()
{

int matchsticks=21, user, computer;
clrscr();
printf("Do not enter Invalid Numbers.\nNumbers above 4 are invalid.");

printf("\nIf you do so, the computer automatically wins.");

while (matchsticks>=1)
{

printf("\nNumber of matchsticks available right now is %d.", matchsticks);

printf("\n\nYour Turn...\n\n\n");

printf("\nPick up the matchstick(s)-- (1-4): ");
scanf ("%d", &user);

if (user>4)

{
printf("Invalid Selection");
break;
}

computer=5-user;

printf("\nComputer's Turn..\n" );


if(matchsticks==1)

break;
printf("\nComputer chooses:%d", computer);
matchsticks=matchsticks-user-computer;
continue;

}

matchsticks--;
printf("\nComputer Wins");
getch();
}
Syed Atif said…
#include
#include
#include
#include
int main()
{
int total=21,user,comp;


cout<<"\n\t\tWelcome to Matchsticks Game"<>user;

if(user==1)
comp=4;
else if(user==2)
comp=3;
else if(user==3)
comp=2;
else if(user==4)
comp=1;
else if(user>4)
{
cout<<"\n\tInvalid"<>user;

if(user==1)

cout<<"\n\n\t\tHurrah! You Lost"<<endl;


else
cout<<"\n\n\tInvaled Entry!! There is Only 1 Matchstick Left... YOU LOST!!!"<<endl;



}

else

continue; //To Go Back To Loop And Start Again

}














getch();

return 0;

}
Mandar said…
Thanx man......
very nice logic..
really I was banging my head for 1 day.....
ujjal said…
why is this equation
"computer=5-user"...whay you always use 5 . pls explain
Krish said…
i have doubt...here y shud comp choose 5-user no of matchsticks only...is it the game rule ?? i dont know abt the game so had the doubt :P
pls help me out
Krish said…
i have one more doubt....what will be the logic if the game is a 2-4 player game....and pls tell me the rules for the match stick game
chirag said…
Check out dis wid some cool formatting......!!!!!



#include
#include
#include
#define EASY 5

void main()
{
int matchstick=21,user,comp;
clrscr();
textcolor(YELLOW);
cprintf("************WelcOme To MatChSticK GamE**************");
textcolor(RED);
cprintf("\r\nRules:\r\n");
textcolor(GREEN);
cprintf("->Enter the numbers between 1 to 4\r\n");
cprintf("->If U enter the numbers greater dan 4 computer will win.. ;)");
cprintf(" \r\nSo Be Aware ...!!!\r\n");

textcolor(5);
cprintf("\r\nEnter no. of matchstick-");
scanf("%d",&user);

while(matchstick>=1)
{
if(user>4)
{
textcolor(6);
cprintf("Hahaha....!!! You stupid............!!!!!!!! Computer wins...!!");
break;
}
else
textcolor(2);
cprintf("\r\nNow computer's turn\r\n");
comp=EASY-user;
cprintf("Computer chooses %d ...\r\n",comp);

if(matchstick==1 && comp==1)
{
textcolor(YELLOW);
cprintf("\nwowwwwww.........\r\n");
cprintf("congrts....!!! You win........!!! hurrayyy....!!!");
break;
}
else if(matchstick==1 && comp!=1)
{
textcolor(CYAN);
cprintf("haha........You LosT.....!!!!");
break;
}
matchstick=matchstick-user-comp;

textcolor(5);
cprintf("\r\n\r\nNow Ur Turn\n Enter-");
scanf("%d",&user);

}
getch();
}
sumathi said…
here's the same program using for loop
#include=1;)/*the decrement operator is left blank,otherwise it will cause the calculation of the no of matches to go wrong*/
{
printf("Please enter a no 1,2,3 or 4\n");
scanf("%d",&user);
if (user>4)
printf("Invalid no entered\n");
comp=5-user;
matches=matches-(user+comp);
printf("computer chooses %d\n",comp);
printf("no of matches remaining =%d\n",matches);
if (matches==1)
{
printf("computer wins!\n"):
break;
}
}
}
Anonymous said…
Thanks man! I tried it the whole of the last night but the problem was that the sequence that I thought would get me the solution was multiples of 4 but not 5.
Noman Riffat said…
my logic was :)

#include
#include
int main()
{
int cp,up,m=21;
while(1)
{
printf("Match Stick= %d \n",m);
printf("Pick number of matchsticks(You can only pick 1,2,3 or 4 matchsticks at a time = ");
scanf("%d",&up);
if((up<1)||(up>4)||(up>m))
{
printf("You have picked invalid matchsticks, try again \n");
continue;
}
m=m-up;
if(m==0)
{
printf("You lose");
break;
}
cp=5-up;
printf("Computer's pick is %d \n",cp);
m=m-cp;
if(m==0)
{
printf("You won");
break;
}
}
getch();
return 0;
}
xyz said…
how user wins? In dis game always computer wins?
Unknown said…
#include
#include
main()
{

int matchsticks, user, computer;
sos:
matchsticks=21;
printf("Do not enter Invalid Numbers.\nNumbers above 4 are invalid.");

printf("\nIf you do so, the computer automatically wins.");

while (matchsticks>=1)
{

printf("\nNumber of matchsticks available right now is %d.", matchsticks);

printf("\n\nYour Turn...\n\n\n");

printf("\nPick up the matchstick(s)-- (1-4): ");
scanf ("%d", &user);

if(matchsticks==1)
break;

if(user>4 || user<1)
{
printf("Invalid Selection");
break;
}



computer=5-user;

printf("\nComputer's Turn..\n" );
printf("\nComputer chooses:%d", computer);

matchsticks=matchsticks-user-computer;


continue;
}



printf("\nComputer Wins\n\n\n");
goto sos;
getch();
}

Sanjay Machadath said…
// program to play match stick game::check this one and find something diff :)

//#include
#include
void main()
{
int plyr,sys,mstk,i,ttl;
//clrscr();
printf("\nMatch stick Game\n");
for(mstk=21;mstk>1;mstk=mstk-ttl)
{
for(i=mstk;i>0;i--)
printf("---------*\n");
printf("mstk=%d\n",mstk);
printf("Enter the no of matchsticks to pick up:\n");
scanf("%d",&plyr);
if(plyr>4 || plyr<1)
{
printf("Enter a Valid input\n");
continue;
}
sys=5-plyr;//ensure the ttl must be 5
printf("computer Selects %d Matchsticks\n",sys);
ttl=sys+plyr;
printf("\nremaining matchsticks are\n");
}
printf("---------*\n");
printf("only 1 matchstick remaining,You Loose The GAME");

//getch();
}
Unknown said…
/ program to play match stick game::check this one and find something diff :)

//#include
#include
void main()
{
int plyr,sys,mstk,i,ttl;
//clrscr();
printf("\nMatch stick Game\n");
for(mstk=21;mstk>1;mstk=mstk-ttl)
{
for(i=mstk;i>0;i--)
printf("---------*\n");
printf("mstk=%d\n",mstk);
printf("Enter the no of matchsticks to pick up:\n");
scanf("%d",&plyr);
if(plyr>4 || plyr<1)
{
printf("Enter a Valid input\n");
continue;
}
sys=5-plyr;//ensure the ttl must be 5
printf("computer Selects %d Matchsticks\n",sys);
ttl=sys+plyr;
printf("\nremaining matchsticks are\n");
}
printf("---------*\n");
printf("only 1 matchstick remaining,You Loose The GAME");

//getch();
}
malathi said…
pls clearly explain the game's rules
Zhukov said…
This comment has been removed by the author.
Zhukov said…
For those of you wondering:

You start with 21 matchsticks. 2 players (in this case there is one player playing against the program) take turns picking up the matchsticks.
Each player may only pick up up to 4 matchsticks per turn or at least 1.

This program emulates the play with one twist: The player should always lose and the program should always win.

Starting out with 21 matchsticks, no matter what the player picks up, the program picks up just enough to equal the number of matchsticks picked up to 5.
If player picks 1, prog picks 4(1+4=5)

If player picks 2, prog picks 3(2+3=5)

If player picks 3, prog picks 2(3+2=5)

If player picks 4, prog picks 1(4+1=5).

After 4 turns each, the number of matches picked up will always be 20.
Since we start out with 21 matchsticks, we will be left with 1 matchstick. So the person who goes first always loses.

The condition is that the player always goes first and not the program, else it may turn out to be quite a hassle. lol.
Unknown said…
Am B.Tech(cs),1st yr student of amity university..
ur logic is remarkable...it's help me a lot
Unknown said…
This comment has been removed by the author.
Unknown said…

#include

int main()
{
int i,u_input,c_input,rem=0,matchstick=21;

for(i=1; i<=matchstick; i++)
{

if(rem == 1)
{
printf("\nlast matchstick to select\nYou loose!!!!");
break;
}

printf("\nuser's turn : ");
scanf("%d",&u_input);
matchstick -= 1;
printf("\nuser selected : %d",u_input);
printf("\ncomputer's turn : ");
scanf("%d",&c_input);
rem = matchstick - 1;
matchstick -= 1;
printf("\ncomputerer selected : %d",c_input);
rem = u_input-c_input;
continue;
}

return 0;
}
Unknown said…
#include

int main()
{
int i,u_input,c_input,rem=0,matchstick=21;

for(i=1; i<=matchstick; i++)
{

if(rem == 1)
{
printf("\nlast matchstick to select\nYou loose!!!!");
break;
}

printf("\nuser's turn : ");
scanf("%d",&u_input);
matchstick -= 1;
printf("\nuser selected : %d",u_input);
printf("\ncomputer's turn : ");
scanf("%d",&c_input);
rem = matchstick - 1;
matchstick -= 1;
printf("\ncomputerer selected : %d",c_input);
rem = u_input-c_input;
continue;
}

return 0;
}
Unknown said…
#include
#include

main()
{
int mat=21,x,y,i;
for(i=1;i<=4;i++)
{

printf("\n\n");
printf("\n\npick matchsticks [1-4]\n\n");
scanf("%d" , &x);
printf(" \n\nu picked %d", x);
printf("\n\nnow i will pick");
y=5-x;
printf("\n \n i picked %d" , y);
mat=mat-(x+y);
printf("\n\nremaining matchsticks are %d" , mat);
if(mat==1||x>4)
break;
}
if(mat==1)
{
printf("\n\nyou loose u picked last one");

printf("\n\nmummy ko bolo complan pilaye" );
}
else
{
printf("\n\nu loose by abiding rules");
}
getch();
}



Unknown said…
This comment has been removed by the author.
saikiran mannem said…
This comment has been removed by the author.
saikiran mannem said…
This comment has been removed by the author.
saikiran mannem said…
code not currect to the logic comparing to qution for example

in missing logics comparing to quotion the user should not be able to choose zero if he chooses computer automatically should win . at end the computer choosing more macthicks then available somtimes user end total macthiks . then computer wins, l.ast choosen macthick should win.thats the main logic please impliment cod according to the quotion
Sohail Saha said…
This comment has been removed by the author.
Sohail Saha said…
This is the best code-->

#include
#include
#include
void main()
{
int mymove,yourmove,match=21,a;
/*RULES*/
printf(" MATCHSTICKS GAME\n");
printf(" BY SOHAIL SAHA (theinfopark.blogspot.com)\n");
printf("--------------------------------------------------------------------------------------");
printf("The rule is simple. There are 21 matchsticks.\n");
printf("At first, you will pickup 1,2,3 or 4 matchstics.\n");
printf("Then the computer will do its picking.\n");
printf("Whoever will be forced to pickup the last matchstick will lose.\n");
printf("Also, if you cheat, you lose.\n");
printf("\n Are you READY?? (PRESS ANY KEY TO CONTINUE)\n");
getch();
system("cls");
/*GAME STARTS FROM HERE*/
while(match>=0)
{
system("cls");
for(a=1;a<=match;a++)
{
printf(" I "); /* I is a matchstick*/
}
printf("\n\nHow many matchsticks do you want to pickup: ");
scanf("%d",&yourmove);
if((yourmove>4)||(yourmove<1))
{
printf("\nYou have cheated. So...");
break;
}
else if ((match-yourmove)==0)
break;

mymove=5-yourmove;

printf("\nThe computer picks up %d matchstick/s.",mymove);
match=match-yourmove-mymove;
printf("\nTHIS ROUND IS OVER. PRESS ANY KEY TO CONTINUE...");
getch();
}

printf("\nThe Computer wins!! %c and you lose!!",1);
getch();

}
Anonymous said…
Shortest and best method for this problem.
Prashant Ravi said…
Are u sure this code work alryt? When we are left with just one matchstick in last we can choose only that matchstick. And computer is left with no matchsticks to choose. Still output screen shows computer choose 4 matchstick.
Anonymous said…
Really Amazing Work Buddy!I liked your Logic.
Unknown said…
This program does not tell how much matchsticks computer can pick at a time.
Then if user picks his matchstick/s,the computer picks 1 less than the no.of matchsticks left, and thus the user always loses. 😉😉😉
Anonymous said…
#include
int main()
{
int c = 0, u = 0, t = 0;
while(1)
{
printf("Pick no. of matchsticks");
scanf("%d",&u);
printf("You picked %d matchstick(s)\n",u);
c = 5 - u;
printf("Computer picks %d matchstick\n",c);
t = t + u + c;
printf("Total matchsticks picked= %d\n",t);
if(t == 20)
break;
}
printf("You get to pick the last matchstick!! You lose!");
return 0;
}
Unknown said…
This comment has been removed by the author.
Unknown said…
This comment has been removed by the author.
Unknown said…
I modified my code after seeing Sohail Saha's Code output (matchstick(s) display method), thanks for that Sohail Saha.

Code with limitation, "while" loop only


Header files (#include )

stdio.h
conio.h //for getch()
stdlib.h //for system(cls)

int main()
{
int mStk = 21, pStk, w = 0, i = 1;
char pAgn = 'y';

printf("\n\t**** Matchstick(s) Game ***\n");
printf("\n\n Rules:\n . We have total 21 Matchsticks\n");
printf(" . We can pick 1, 2, 3 or 4 at a time\n");
printf(" . Whoever is forced to pick up the last matchstick loses the game\n");
printf("\n\n\tPress any key to start\n");

getch();

system("cls");

while ((pAgn == 'y') || (pAgn == 'Y'))
{
mStk = 21;

printf("\n Total Matchstick(s) = %d\n\n", mStk);

while (mStk != 1)
{
printf("\n\n");

while (i <= mStk)
{
printf(" I ");
i++;
}

i = 1;

printf("\n\n\tPlayer - Pick Matchstick(s) => ");
scanf("%d", &pStk);
printf("\n");

while ((pStk > 4) || (pStk == 0))
{
printf("\tPlayer - Pick Matchstick(s) between 1 to 4 => ");
scanf("%d", &pStk);
printf("\n");
}

mStk -= pStk;

while (i <= mStk)
{
printf(" I ");
i++;
}

i = 1;

printf("\n\n\tCPU - Pick Matchstick(s) => ");

pStk = (5 - pStk);

printf("%d", pStk);

mStk -= pStk;
}

if (mStk == 1)
{
printf("\n\n");
printf(" I ");

printf("\n\n\t### Checkmate ###\n\t CPU Won\n");
printf("\n\n\t$$$ Total Score $$$\n");
printf("\n\tPlayer = 0\n\tCPU = %d\n", ++w);

printf("\n\n\t*** You want to play again? Y/N ***\n\t");
scanf("%c", &pAgn);
scanf("%c", &pAgn);

printf("\n\n ### ### ### *** *** *** ### *** *** *** *** ### ### ###\n\n");

if ((pAgn == 'y') || (pAgn == 'Y'))
{
printf("\n\n\tPress any key to start\n");

getch();

system("cls");
}
}
}

return 0;
}
Anonymous said…
Really helpful. just got challenge from my friend and was literally suffering, but after going through your coding helps me alot. stay blessed
Anonymous said…
#include
void main(){
int x=21,n,c;

while(x>0){
printf("enter a number : 1 or 2 or 3 or 4 \t");
scanf("%d",&n);
c=5-n;
printf("computer choose %d",c);
x=x-(c+n);
printf("\n x is %d\n",x);
if(x==1){
if(c==1){
printf("you win");
break;}
else{
printf("computer win");
break;
}
}
}


}
Anonymous said…
Can someone make it a two player game? THANK YOUUU
Unknown said…
Thanks sir truly too good
Unknown said…
without using the "continue" statement and "matchsticks--".
this program still working.
because of matchstick-- statement is the outside of the while loop So, it is useless
So why you use these statements. please explain
Anonymous said…
User will win if his chance is not first.
Unknown said…
This comment has been removed by the author.
Harsh Yadav said…
//This would be easy for beginners if they do not know about loop control statements like
//break;,continue;

#include

int main(void) {
int a,b,c,ms=21;
while(ms>1)
{
printf("Enter your choice between 1,2,3 or 4\t: ");
scanf("%d\n",&a);
if(a>4)
printf("Invalid, Choice is between 1,2,3 or 4!\n");
else
{
b = 5 - a;
ms = ms - a - b;
printf("\nComputer chooses %d\n",b);
printf("Remaining matchsticks are = %d\n",ms);
if(ms == 1)
printf("You lose computer wins!");
}
}
return 0;
}
Anonymous said…
what to do when given matchsticks are 15
Anonymous said…
Amazing logic, I was trying this but didn't worked with my code, thank you so much for posting amazing code and logic.
Unknown said…
Can anyone do this in recursion?

Popular posts from this blog

C Program - Calculation of Area and Circumference of a Circle using Pointers

C Program to Calculate Factorial of a number using Recursion