"""Implements the logic of the game of tic tac toe."""

from graphics import GraphWin
from tttboard import TTTBoard
from tttletter import TTTLetter

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

  def __init__(self, win):
    self._board = TTTBoard(win)
    self._numMoves = 0
    self._player = "X"

  def doOneClick(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.inExit(point):
      # game over
      return False

    # step 2: check for reset button and reset game
    elif self._board.inReset(point):
      self._board.reset()
      self._board.clearUpperText()
      self._numMoves = 0
      self._player = "X"

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

      # get the letter at the point the user clicked
      tlet = self._board.getTTTLetterAtPoint(point)

      # make sure this square is vacant
      if tlet.getLetter() == "":
          tlet.setLetter(self._player)

          # valid move, so increment numMoves
          self._numMoves += 1

          # check for win or draw
          winFlag = self._board.checkForWin(self._player)
          if winFlag:
              self._board.setStringToUpperText(self._player + " WINS!")
          elif self._numMoves == 9:
              self._board.setStringToUpperText("DRAW!")
          # not a win or draw, swap players
          else:
            # set player to X or O
            if self._player == "X":
                self._player = "O"
            else:
                self._player = "X"

    # keep going!
    return True

if __name__ == '__main__':
  win = GraphWin("Tic Tac Toe", 400, 400)
  game = TTTGame(win)
  keepGoing = True
  while keepGoing:
    point = win.getMouse()
    keepGoing = game.doOneClick(point)
