tic-tac-toe in matlab

Here's a simple implementation of tic-tac-toe game using MATLAB:

main.m
%initialize the board
board = [' ' ' ' ' '; ' ' ' ' '; ' ' ' ' '];

% print the initial board
disp(board);

% initialize player
player = 'X';

% Loop through until there's a winner or a draw
while true
    
    % player enters move
    row = input('Enter row number:');
    col = input('Enter column number:');
    
    % check if the entered cell is empty
    if board(row,col) ~= ' '
        fprintf('Cell is not empty!\n\n');
        continue;
    end
    
    % enter player's move into the board
    board(row,col) = player;
    
    % print the updated board
    disp(board);
    
    % check if player wins
    if (board(1,:) == player) || ...
       (board(2,:) == player) || ...
       (board(3,:) == player) || ...
       (board(:,1)' == player) || ...
       (board(:,2)' == player) || ...
       (board(:,3)' == player) || ...
       (board(1,1) == player && board(2,2) == player && board(3,3) == player) || ...
       (board(1,3) == player && board(2,2) == player && board(3,1) == player)
        
        fprintf('Player %s wins!\n',player);
        break;
        
    end
    
    % check if it's a draw
    if all(board ~= ' ')
        fprintf('It is a draw!\n');
        break;
    end
    
    % switch player
    if player == 'X'
        player = 'O';
    else
        player = 'X';
    end
    
end
1320 chars
58 lines

The code creates a 3x3 tic-tac-toe board using 2D array. The players enter the row and column number to make their move. The program checks if the entered cell is empty, and if it is, the program updates the board and checks if the player has won or not. If there's no winner after all cells are filled, the game ends in a draw.

gistlibby LogSnag