Saturday, January 30, 2010

CHAP 3[B]f Playing with matchsticks

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.


void main()
{
char x;
int d=21,a,p;

printf("\nThere are 21 matchsticks.\nThe player will start first.\nThe Player and Computer is allowed to pick 1,2,3 or 4 matchsticks.\nWhoever picks up the last matchstick loses the game");

while(1)
{
if(d==1)
{
printf("\nThere is only %d matchstick left.\nInput the number of matchstick to withdraw",d);
scanf("%d",&a);

if(a!=1)
{
printf("\nYou entered an invalid value");
continue;
}

d-=a;
printf("\nThere are 0 matchsticks left");
}


if(d>1)
{
printf("\nThere are %d matchsticks.\nInput the number of matchsticks to withdraw",d);
scanf("%d",&a);

if(a<1||a>4)
{
printf("\nYou entered an invalid value");
continue;
}

d-=a;
printf("\nThere are %d matchsticks left",d);

}

if(d>16)
{
p=d-16;
d=16;
printf("\nThe computer picks %d matchsticks, there are 16 matchsticks left",p);
}

else if(d>11)
{
p=d-11;
d=11;
printf("\nThe computer picks %d matchsticks, there are 11 matchsticks left",p);
}

else if(d>6)
{
p=d-6;
d=6;
printf("\nThe computer picks %d matchsticks, there are 6 matchsticks left",p);
}

else if(d>1)
{
p=d-1;
d=1;
printf("\nThe computer picks %d matchsticks, there is only 1 matchstick left",p);
}

else if(d==0)
{
printf("\nYou picked the last matchstick, you lost! HAHAHA!!!");
printf("\nPress Q to quit");
scanf("%c",&x);

}

if(x==113)
break;

}
}

No comments:

Post a Comment