classdef TicTacToeBoard < handle
    properties
        squares % 3x3 cell array of TicTacToeSquare
        turn
        winner
    end
    methods
        function board=TicTacToeBoard()
          for index = 0:2
            for index2 = 0:2
              board.squares{index+1,index2+1} = TicTacToeSquare(index*100, index2*100, 100);
              set(board.squares{index+1,index2+1}.button,'Callback',@func_Callback);
            end
          end
          board.turn = 'x';
          board.winner = ' ';
          function func_Callback(source,eventdata)
            board.clickedButton(source);
          end
        end
        
        function []=clickedButton(board, button)
            if ((board.winner == ' ') && (get(button, 'String') == ' '))
                set(button, 'String', board.turn);
                board.checkForWinner();
                if (board.turn == 'x')
                    board.turn = 'o';
                else
                    board.turn = 'x';
                end
            end
            
        end
        
        function boardStrings=getBoardStrings(board)
           [rows cols] = size(board.squares);
            boardStrings = char(zeros(rows,cols));
            for row = 1:rows
                for col = 1:cols
                    boardStrings(row,col) = get(board.squares{row,col}.button,'String');
                end
            end 
        end
        
        function winner=isWinner(board, boardStrings, player)
            xmask = boardStrings == player;
            if (any(sum(xmask) == 3) || any(sum(xmask') == 3) ...
                || sum(xmask(logical(eye(3,3)))) == 3 ...
                || sum(xmask(flipud(logical(eye(3,3))))) == 3) 
              winner = true;
            else 
                winner = false;
            end
        end
        function []=checkForWinner(board)
            boardStrings = getBoardStrings(board);
            disp(boardStrings);
            
            if (isWinner(board, boardStrings, board.turn)) 
              board.winner = board.turn;
              fprintf('The winner is player %s\n',board.winner);
            elseif (sum(sum(boardStrings == ' ')) == 0)
                fprintf('Draw\n');
            end
        end
    end
end