Thursday, August 2, 2012

21 Matchstick Game in C


21 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.

Code :
=======

#include <stdio.h>


int main(void)
{
    int i,total = 0,choice,matches = 21,left = 0,k = 0;
    while (  total < 20 )
        
    {
        
        printf("\nEnter your choice of match-sticks between 1-4 :");
        scanf("%d",&i);
        if ( i > 4 || i <= 0 )
            {
             printf("Pl.Enter a valid no between 1,2,3 or 4 :");
             continue;
            }
        total = total + i ;
        left = left - total ;
        
        if( total >= 21)
            break;
            
        choice = 5 - i ;
        printf("\nComputer chooses %d",choice);
        total = total+choice ;
        left = left - choice ;
        printf("\n \nNow total match sticks are %d",total);
        
                
  if (total == 20)
   {
       
      while (k != 1)
      {
          printf("\nEnter your choice of M-sticks you have just one left :");
          scanf("%d",&k);
          if ( k != 1)
              printf("\nPl.enter valid choice : 1 ");
          continue;
      }
          
       
       if(k == 1)
       {
           total = total + k;
           printf("\nComputer wins as you are last to choose match-stick");
           printf("\n \nNow total match sticks are %d",total);
       }
       
  
  
   }   
 
   
}
     return 0;
}
    
   

No comments: