import javax.swing.*;
import java.awt.*;

/** Coordinate the TicTacToe board with the TTTWindow gui interface to
 *  play Tic Tac Toe.
 */
public class TicTacToeGame {
  
  /** Play the game.  The main method is always called when you
   *  invoke a class using "java classname".  In this case,
   *  we invoke the game by entering "java TicTacToeGame".  If
   *  we want player O to go first, we invoke the game using
   *  "java TicTacToeGame O" and the O is passed into the 
   *  String array args parameter for main as the first item in that
   *  array.
   */
  public static void main(String[] args) {
    TicTacToe t = new TicTacToe();
    TTTWindow w = new TTTWindow(t);
    char currPlayer;
    
    //if statement to determine first player
    if (args.length != 0) {
      if (t.getWho() != args[0].charAt(0)) {
        t.switchTurn();
      }
    }
    /* You want to switch turn right at the beginning of the loop,
     * so you prepare by flipping the current player.  That way, 
     * you always start on the right player. */
    t.switchTurn();
    while (!t.runOfThree() && !t.checkDraw() ){
      t.switchTurn();
      boolean moved = false;
      while (!moved) { // added this to catch when move was unsuccessful.
        String move = 
          JOptionPane.showInputDialog(null,
                                      "Player " + t.getWho() + " make your move:");
        int row = move.charAt(0) - '0'; // convert character to numerical equivalent
        int col = move.charAt(2) - '0'; // convert character to numerical equivalent
      
      //make a move
        moved = t.setMark(row, col);
      }
      w.update();
    }
           
    if (t.runOfThree()) { 
      JOptionPane.showMessageDialog(null,"Congratulations " + t.getWho() + "! You won!");
    } else {
      JOptionPane.showMessageDialog(null,"Sorry no winner this time :(");
    }
  }
}
      
