x and o game in matlab

Here's a sample code to create a Tic Tac Toe game (also known as X and O game) in MATLAB using a function which takes a 3x3 matrix as input and returns the winner (if there is one).

main.m
function winner = ticTacToe(board)
% This function takes a 3x3 matrix as input
% representing the Tic Tac Toe game board,
% and returns the winner (if there is one).

% Initialize the winner to be empty
winner = '';

% Check rows for a winner
for i = 1:3
    if all(board(i,:) == 'X')
        winner = 'X';
    elseif all(board(i,:) == 'O')
        winner = 'O';
    end
end

% Check columns for a winner
for i = 1:3
    if all(board(:,i) == 'X')
        winner = 'X';
    elseif all(board(:,i) == 'O')
        winner = 'O';
    end
end

% Check diagonals for a winner
if all(diag(board) == 'X') || all(diag(flip(board)) == 'X')
    winner = 'X';
elseif all(diag(board) == 'O') || all(diag(flip(board)) == 'O')
    winner = 'O';
end

% Check if the game is a draw
if isempty(winner) && all(board(:) ~= '.')
    winner = 'draw';
end
end
836 chars
39 lines

You can test this function by passing in a 3x3 matrix representing the board, where empty cells are represented by a period . like so:

main.m
board = ['X' '.' 'O';
         'X' 'O' '.';
         'X' '.' '.'];
ticTacToe(board)
84 chars
5 lines

Output:

main.m
ans = X
8 chars
2 lines

gistlibby LogSnag