/*
 * Game class - the entry point into a game
 */

public class Game{
	
  public Game(Board b, Player p1, Player p2){
     board   = b;
     players = new Player[2];
     players[0] = p1;
     players[1] = p2;
     firstPlayerIndex = 1;
     scoreBoard = new ScoreBoard(p1, p2); 
  }
	/**
    * runs while there is no winner and there are moves, when either of 
    * those becomes false then it ends the loop and says results
    */
  public void start(){
     //change the first player index
     firstPlayerIndex = (firstPlayerIndex+1) % 2;
     int currentPlayerIndex = firstPlayerIndex;
     boolean hasWinner = false;

     // TODO: play one round of the game to completion
	 while(!board.hasWinner()){
		 board.hasWinner();		 
		 board.hasOpenPositions();
		 players[firstPlayerIndex].takeTurn(board);
		 board.display();
		 firstPlayerIndex = (firstPlayerIndex+1) % 2;
		 currentPlayerIndex = firstPlayerIndex;
		 if (!board.hasOpenPositions()){
			 break;
		 }
	 }
	 //board.reset();
	 if(board.hasWinner()){
		 hasWinner = true;
	 }
	 
	//players[currentPlayerIndex].takeTurn(board);

     // Show the final board
     
    
     // Announce game results
     if (hasWinner)
     {
        scoreBoard.announceWinner(players[currentPlayerIndex]);

     }
     else 
     {
        scoreBoard.announceTie();
     }
  }


  /*
   * Entry point into the program
   */
   /**
    * instantiates everything and then runs a loop for how long the programmer
    * decides to let people play the game
    */
  public static void main(String[] args){
    // TODO: instanciate game pieces, players, board, and game
    
	GamePiece X = new GamePiece('X');
 	GamePiece O = new GamePiece('O');
    Player p1 = new Player("Player 2", O);
    Player p2 = new Player("Player 1", X);
    Board b = new Board();
    Game game = new Game(b,p1,p2);
     // TODO: play 4 rounds of the game
     for (int i = 0; i < 4; i++){
		 game.start();
		 b.reset();
	 }
     
  }

  private Board      board;
  private Player[]   players;
  private int        firstPlayerIndex;
  private ScoreBoard scoreBoard;
}
