/****************************************************************
 **  File: nim.c
 **  Author: Marie desJardins
 **  Date: 8/27/06
 **  Section: 0101
 **  E-mail: mariedj@cs.umbc.edu
 **
 **  This file contains a game player for the game of Nim.
 **  This program asks the user how many sticks, then takes
 **  turns taking 1 or 2 sticks.  This player hates to lose.
 ****************************************************************/

#include <stdio.h>

/****************************************************************
 ** Main -- This is the main function to play Nim.
 **    It is probably too long and should be subdivided into
 **    subfunctions.  Maybe we'll do that in Lecture 3.
 ** Inputs: None
 ** Outputs: None
 ** Side effects: Interacts with the user to play Nim.
 ****************************************************************/

int main() {
   int sticks;            /* The number of sticks remaining */
   int theirSticks;       /* # sticks the other player takes on a turn */

   /* First find out how many sticks, and quit if I can't win */
   printf ("Let's play Nim!\n");
   printf ("How many sticks should we play with? ");
   scanf ("%d", &sticks);
   if ( sticks%3 == 1 ) {
      printf ("Never mind -- I don't want to play!!\n");
      printf ("Bye!\n");
      return (0);
   }

   /* Start playing! */
   while ( sticks >= 0 ) {
      /* If the number of sticks remaining is divisible by 3,
	 take 2 sticks, leaving the other player in a hopeless
	 situation. */
      if ( sticks%3 == 0 ) {
	sticks -= 2;  /* not particularly readable but illustrates -= */
	 printf ("I'll take 2 sticks.  Now there are %d sticks.\n", sticks);
      /* If the number of sticks remaining is 2 modulo 3,
	 take 1 stick, leaving the other player in a hopeless
	 situation. */
      } else if ( sticks%3 == 2 ) {
	sticks--;   /* decrement sticks (by one)! */
	printf ("I'll take 1 stick.  Now there are %d sticks.\n", sticks);
      }

      /* Let the other player take a turn, and remove their
	 sticks from the pile. */
      printf ("Your turn!  How many sticks will you take? ");
      scanf ("%d", &theirSticks);
      sticks = sticks - theirSticks;   /* more readable than -= */

      /* Quit if they took too many or too few sticks. */
      if ( ((theirSticks != 1) && (theirSticks != 2)) ||
	   (sticks < 0) ) {
	 printf ("Cheater!  I'm not playing with you any more!\n");
	 return (0);
      }

      /* If there are no sticks left, I win!  (I always do...) */
      if ( sticks == 0 ) {
	 printf ("I win!\n");
	 return (1);
      }
   }

   /* We should never reach this point... */
   printf ("How did we get here?  Must be a bug!!\n");
   return (0);
}
