function [game_over, winner] = tictactoe_game_status (board) % [game_over, winner] = tictactoe_game_status (board) % This function is used by tictactoe.m and may be used by your own % function as it contemplates the outcome of possible moves. % We analyze the board to see if anyone has won or if we have % ended in a tie. Return the winner ID (or 0 for a draw) and % set game_over to TRUE or FALSE game_over = 1; % We must set this to TRUE initially since we will % return immediately if we find a winner. n_empty = 0; % How many unoccupied slots on the board p = 1; % A counter that will go from 1 to 9 for winner = -1:2:1 % Check both player's status for j=1:3 % Check each of the 3 rows and then each of the 3 columns if board(j,1) == winner & board(j,2) == winner & board(j,3) == winner; return; end if board(1,j) == winner & board(2,j) == winner & board(3,j) == winner; return; end if board(p) == 0; n_empty = n_empty + 1; end % 1-D index p into board p = p + 1; % Goto next board slot in a 1-D way end % Check the two diagonals if board(1,1) == winner & board(2,2) == winner & board(3,3) == winner; return; end if board(1,3) == winner & board(2,2) == winner & board(3,1) == winner; return; end if board(p) == 0; n_empty = n_empty + 1; end % Checking the 4th or 8th slot p = p + 1; end if board(9) == 0; n_empty = n_empty + 1; end % Must check the 9th slot winner = 0; % Nobody has won the game so it is a draw or we are not done if n_empty > 0 % Game is not over yet as there are empty spaces game_over = 0; end