/*
 * Solution to Problem 1 (C++)
 * 14th Annual CS Programming Contest
 * WCU Dept of Math and CS
 * Copyright 2003 , All Rights Reserved
 *
 * Problem Statement:
 * Game of Nim
 * 
 * This program engages a player in the classic game of Nim.  The game
 * begins with 21 markers on the floor.  Each player (the user and the
 * computer) takes a turn removing between 1 and 3 markers.  Whoever
 * leaves 1 marker is declared the winner.
 * 
 * 
 */

#include <iostream.h>
#include <stdlib.h>
int compChoose(int markers);
int userChoose(int markers);

main()
{
  bool winner = false;  //Variable indicates when we have a winner
  int computeChoose; //Variable represents the computer's choice
  int markers = 21;  //Varriable represents the number of markers left
  //Welcome player to game
  cout << "Welcome to the game of Nim.  There are 21 markers."<< endl;;

  while (!winner)
  {

    cout <<"Enter your choice: "<< endl;
    //User makes a choice
    markers -= userChoose(markers);
    cout <<"The number of markers left is " << markers << "." << endl;
    if (markers == 1) 
    {
      winner = true;
      cout << "You win!" << endl;
    }
    else
    {
      //Computer's turn
      computeChoose = compChoose(markers);
      markers -= computeChoose;
      cout << "Computer chooses " << computeChoose << endl;
      cout << "The number of markers left is " << markers << "." << endl;
      if (markers == 1)
      {
	winner = true;
        cout << "Computer wins" << endl;
      }
    }
  }
}



int compChoose(int markers)
  //Returns a random number between 1 and 3 representing the computer's choice
{
  int choice; //Represents computer's choice
  do {
    choice = (random() % 3) + 1;
  } while (markers - choice < 1);
  return choice;
}    

int userChoose(int markers)
{
  //Interacts with the user, allowing a choice for the game of Nim
  int choice;
  cin >> choice;
  //Loop until a proper choice is made
  while (choice <1 || choice > 3 || markers - choice <= 0)
  {
    if (choice < 1 || choice > 3) //Can only choose between 1 and 3
    {
      cout << "Your choice must be between 1 and 3" << endl;
      cout << "Enter another choice: " << endl;
      cin >> choice;
    }
    else if (markers - choice <= 0) //User has taken too many markers
      {
	cout << "You must leave at least one marker" << endl;
        cout << "Enter another choice: " << endl;
        cin >>  choice;
      }
  }
  return choice;
}

