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

public class Game{

  public Game(Board b, IScoreBoard s, Player p1, Player p2){
     board   = b;
     players = new Player[2];
     players[0] = p1;
     players[1] = p2;
     firstPlayerIndex = 1;
     scoreBoard = s;
  }

  public void start(){
     //change the first player index
     firstPlayerIndex = (firstPlayerIndex+1) % 2;
     int currentPlayerIndex = firstPlayerIndex;
     boolean hasWinner = false;
     while (board.hasOpenPositions())
     {
        board.display();
        players[currentPlayerIndex].takeTurn(board);
        hasWinner = board.hasWinner();
        if (hasWinner)
        {
           // player at currentPlayerIndex is the winner
           break;
        }
        // switch the player
        currentPlayerIndex = (currentPlayerIndex+1) % 2; 
     }

     board.display();
    
     if (hasWinner)
     {
        scoreBoard.announceWinner(players[currentPlayerIndex]);

     }
     else 
     {
        scoreBoard.announceTie();
     }
  }


  /*
   * Entry point into the program
   */
  public static void main(String[] args){
     GamePiece sym1 = new GamePiece('x');
     GamePiece sym2 = new GamePiece('0'); 
     Player p1 = new Player("Kate", sym1);
     Player p2 = new Player("Alice", sym2);
     Board board = new Board();
     // will not work
     // IScoreBoard score = new IScoreBoard();
     ScoreBoard score = new ScoreBoard(p1, p2);
     Game ticTacToe = new Game(board, score, p1, p2);
     ticTacToe.start();
  }

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