tic-tac-toe game in matlab in matlab

Here's an example of how to create a simple tic-tac-toe game in Matlab using a loop and conditional statements:

main.m
% initialize the game board
board = ['1', '2', '3'; '4', '5', '6'; '7', '8', '9'];

% print the initial board
disp(board);

% game loop
while true
    % player 1 move
    disp('Player 1 (X), enter a number from 1 to 9:');
    move = input('>> ');
    [row, col] = find(board == num2str(move));
    board(row, col) = 'X';
    disp(board);
    
    % check for winner
    if checkWin(board, 'X')
        disp('Player 1 wins!');
        break;
    end
    
    % check for tie game
    if checkTie(board)
        disp('Tie game!');
        break;
    end
    
    % player 2 move
    disp('Player 2 (O), enter a number from 1 to 9:');
    move = input('>> ');
    [row, col] = find(board == num2str(move));
    board(row, col) = 'O';
    disp(board);
    
    % check for winner
    if checkWin(board, 'O')
        disp('Player 2 wins!');
        break;
    end
    
    % check for tie game
    if checkTie(board)
        disp('Tie game!');
        break;
    end
end

% function to check for a win
function result = checkWin(board, move)
    result = false; 
    % check rows
    for i = 1:3
        if board(i, :) == move
            result = true;
            return;
        end
    end
    
    % check columns
    for i = 1:3
        if board(:, i) == move
            result = true;
            return;
        end
    end
    
    % check diagonals
    if all(board(diag(true(size(board)))) == move)
        result = true;
        return;
    end
    if all(board(diag(true(size(board))))) == move)
        result = true;
        return;
    end
end

% function to check for a tie game
function result = checkTie(board)
    result = all(isstrprop(board(:), 'alpha'));
end
1678 chars
82 lines

The game initializes with an empty board, and proceeds to prompt each player for their moves in turn. After each move, the board is displayed again and checked for a win or tie game. If a win or tie is detected, the game loop is broken and the result is displayed.

The checkWin() and checkTie() functions are used to determine if the game has been won or tied. The checkWin() function loops over each row, column, and diagonal of the board to check for a match with the specified move (X or O). If a match is found in any direction, the function returns true. The checkTie() function checks if every square of the board has been filled with either an X or an O (i.e. there are no remaining numeric squares), and returns true if this is the case.

gistlibby LogSnag