classdef TicTacToeBoard < handle
    properties
        squares % 3x3 matrix 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 []=checkForWinner(board)
            [rows cols] = size(board.squares);
            boardStrings = char(zeros(3,3));
            for row = 1:rows
                for col = 1:cols
                    boardStrings(row,col) = get(board.squares{row,col}.button,'String');
                end
            end
            
            xmask = boardStrings == board.turn;
            if (any(sum(xmask) == 3) || any(sum(xmask') == 3) ...
                || sum(xmask(logical(eye(3,3)))) == 3 ...
                || sum(xmask(flipud(logical(eye(3,3))))) == 3)
              board.winner = board.turn;
              
              fprintf('The winner is player %s\n',board.winner);
            end
        end
    end
end