"""Implements the logic of the game of tic tac toe."""
from random import randint
from graphics import GraphWin
from tttboard import TTTBoard
from tttcube import TTTCube

class TTTGame:
    __slots__ = [ "_board", "_num_moves", "_player" ]

    def __init__(self, win):
        self._board = TTTBoard(win)
        self._board.draw_board()
        self._num_moves = 0
        # initial player is randomly chosen from "X" or "O"
        self._player = ["X", "O"][randint(0, 1)]  

    def do_one_click(self, point):
        """
        Implements the logic for processing one click. Returns True if play
        should continue, and False if the game is over.
        """
        # step 1: check for exit button and exit (return False)
        if self._board.in_exit(point):
            print("Exiting...")
            # game over
            return False

        # step 2: check for reset button and reset game
        elif self._board.in_reset(point):
            print("Reset button clicked")
            self._board.reset()
            self._board.set_string_to_upper_text("")
            self._num_moves = 0
            self._player = "X"

        # step 3: check if click is on a cell in the grid
        elif self._board.in_grid(point):

            # get the cube at the point the user clicked
            tcube = self._board.get_ttt_cube_at_point(point)

            # make sure this square is vacant
            if tcube.get_letter() == "":
                # set letter to be current player
                tcube.set_letter(self._player)
                # update cube cell to display
                self._board.place_cubes_on_board()

                # valid move, so increment num_moves
                self._num_moves += 1

                # check for win or draw
                win_flag = self._board.check_for_win(self._player)
                if win_flag:
                    self._board.set_string_to_upper_text(self._player + " WINS!")
                elif self._num_moves == self._board.get_rows() * self._board.get_cols():
                    self._board.set_string_to_upper_text("DRAW!")
                # not a win or draw, swap players
                else:
                    # toggle player!
                    self._player = "O" if self._player == "X" else "X"

	# keep going!
        return True

if __name__ == '__main__':
    win = GraphWin("Tic Tac Toe", 400, 400)
    game = TTTGame(win)

    # as long as the game isn't over, keep playing one click at a time
    keep_going = True
    while keep_going:
        point = win.getMouse()
        keep_going = game.do_one_click(point)

    # close the graphical window to end the game
    win.close()
