function Ticktacktoe()
%---------------------------------------------------------------
%       USAGE: Tictacktoe()
%
%      AUTHOR: Dr. Wayne Brown           DATE: 23 Aug 05
%
% DESCRIPTION: Play Tic-Tack-Toe on any size board
%
%      INPUTS: None
%
%     OUTPUTS: None
%
%  REFERENCES: None
%---------------------------------------------------------------

clc();

% The board size must be square, but it can be any size > 1
Board_size = 3;

% Allocate a character array for the board description.
% The board contains the square boundaries and a blank space
% for the X's and O's to be played into.
Board = char(2*Board_size + 1, 2*Board_size + 1);

% Initialize the board.
Row = 1;
for j = 1:Board_size
  Board(Row,  1) = '+';
  Board(Row+1,1) = '|';
  
  Column = 2;
  for k = 1:Board_size
    Board(Row,Column  ) = '-';
    Board(Row,Column+1) = '+';
    
    Board(Row+1,Column  ) = ' ';
    Board(Row+1,Column+1) = '|';
    
    Column = Column + 2;
  end
  
  Row = Row + 2;
end

% Fill in the bottom row of the board
Board(Row,  1) = '+';
  
Column = 2;
for k = 1:Board_size
  Board(Row,Column  ) = '-';
  Board(Row,Column+1) = '+';

  Column = Column + 2;
end

% Begin playing the game until someone wins or the board is full
Whose_turn = 'X';
Winner     = ' ';
while Winner == ' '

  % Display the current tic-tac-toe board
  disp(Board);

  % Get the location to put the next X or O
  fprintf('Enter %c''s row   : ', Whose_turn); 
  Row = input('');
  fprintf('Enter %c''s column: ', Whose_turn); 
  Column = input('');
  
  % Place the X or O on the Board; the times 2 skips over the borders
  Board(Row*2,Column*2) = Whose_turn;
  
  % Check to see if this created a sequence -- i.e., is there a winner?
  if sum( sum( Board == Whose_turn ) == Board_size) > 0 % a column is full of the same symbols
    Winner = Whose_turn;
  elseif sum( sum( Board' == Whose_turn ) == Board_size) > 0 % a row is full of the same symbols 
    Winner = Whose_turn;
  elseif sum( diag(Board,0) == Whose_turn ) == Board_size % the diagonal has all the same symbols
    Winner = Whose_turn;
  else % check the upper-right to lower left diagonal for all of the same symbols
    Total_Xs = 0;
    for row = 2:2:Board_size*2
      if Board(row,(Board_size*2-row+2) ) == Whose_turn
        Total_Xs = Total_Xs + 1;
      end
    end
    if Total_Xs == Board_size
      Winner = Whose_turn;
    end
  end
  
  % Check to see if all the blanks are gone and the game is over
  if sum( sum( Board == ' ') ) == 0
    Winner = 'C'; % "Cat" got the game
  end
  
  % Switch players turn
  if Whose_turn == 'X'
    Whose_turn = 'O';
  else
    Whose_turn = 'X';
  end
  
end % while Winner == ' '

% Display the final board layout so we can see the last move
disp(Board);

% Display who won
if Winner == 'X'
  fprintf('X won - congratulations!\n');
elseif Winner == 'O'
  fprintf('O won - congratulations!\n');
else % it must be a 'cat' game
  fprintf('Cat won - sorry.\n');
end
  
end % function tictacktoe
    
