// Arup Guha
// 7/31/02
// This program allows several users to play the marble game. The game 
// involves each player, taking in turn, one two or three marbles. The
// winner is the one who takes the last marble.
#include <iostream.h>

void play(int numplayers, int nummarbles);
void printstatus(int* marbles, int numplayers);
int getmove(int player, int &nummarbles);

void main() {

  int numplayers, nummarbles;
  bool done = false;

  while (!done) {

    // Get number of players and marbles for the game.
    cout << "How many players are there?" << endl;
    cin >> numplayers;
    cout << "How many marbles are you playing with?" << endl;
    cin >> nummarbles;

    // Play the game.
    play(numplayers, nummarbles);

    // See if they want to play again.
    char ans;
    cout << "Would you like to play again?" << endl;
    cin >> ans;
    if ((ans != 'y') && (ans !='Y'))
      done = true;
  }
}

// Executes playing a game with numplayers players and nummarbles marbles.
void play(int numplayers, int nummarbles) {

  // Initialize array storing number of marbles taken by each player.
  int* marbles = new int[numplayers];
  for (int i=0; i<numplayers; i++)
    marbles[i] = 0;

  // Play game until no marbles are left.
  int curplayer = 1;
  while (nummarbles > 0) {

    // Get the next player's move and update their total marbles taken.
    marbles[curplayer-1] +=getmove(curplayer, nummarbles);

    // Stop loop if the game is over.
    if (nummarbles == 0)
      break;
    curplayer = 1 + (curplayer%numplayers);
  }

  // Print out end game information.
  cout << "Player " << curplayer << ", you are the winner!" << endl;
  printstatus(marbles, numplayers);
}

// Prints out how many marbles everyone has taken.
void printstatus(int* marbles, int numplayers) {

  cout << "Player\tTotal Marbles Taken" << endl;
  for (int i=0; i< numplayers; i++)
    cout << i+1 << "\t" << marbles[i] << endl;
}

// Executes a move and returns the number of marbles taken by player.
int getmove(int player, int &nummarbles) {

  int num;
  bool done = false;
  // Continue until a valid choice is entered.
  while (!done) {

    // Read in the player's choice.
    cout << "Player " << player << ", how many marbles would you like?\n";
    cin >> num;

    // Check if it's valid.
    if ((num > 0) && (num < 4) && (num <= nummarbles))
      done = true;
    else 
      cout << "That is not a valid number of marbles. Try again." << endl;
  }

  nummarbles -= num; // Adjust number of marbles.

  // Print out turn information.
  cout << "Player " << player << ", you have taken " << num;
  cout << " marbles, leaving " << nummarbles << " marbles left." << endl;
  return num;
}
