construct a cli game of tic-tac-toe in matlab

Here is a simple way to construct a CLI game of Tic-Tac-Toe in Matlab:

main.m
% Initialize the game board as a 3x3 matrix of zeros
board = zeros(3);

% Initialize game variables
player = 1;
gameOver = false;
winner = 0;

% Loop until game is over
while ~gameOver
    % Print the current game board
    disp(board);
    
    % Get the current player's move
    validMove = false;
    while ~validMove
        % Prompt for row and column of move
        row = input(sprintf('Player %d: enter row (1-3): ', player));
        col = input(sprintf('Player %d: enter column (1-3): ', player));
        
        % Check if move is valid
        if row >= 1 && row <= 3 && col >= 1 && col <= 3 && board(row, col) == 0
            validMove = true;
        else
            disp('Invalid move, try again.');
        end
    end
    
    % Update the game board
    board(row, col) = player;
    
    % Check if the game is over
    if any(all(board == player, 1)) || ... % Check rows
            any(all(board == player, 2)) || ... % Check columns
            all(diag(board) == player) || ... % Check diagonal
            all(diag(flip(board, 2)) == player) % Check other diagonal
        % The current player won
        gameOver = true;
        winner = player;
    elseif all(board(:) ~= 0)
        % The game ended in a draw
        gameOver = true;
    else
        % Switch to the other player
        player = 3 - player;
    end
end

% Print the final game board
disp(board);

% Print the winner or the draw message
if winner ~= 0
    disp(sprintf('Player %d wins!', winner));
else
    disp('The game ended in a draw.');
end
1546 chars
58 lines

This code initializes the game board as a 3x3 matrix of zeros, and then loops until the game is over. For each iteration, it prints the current game board, prompts the current player for a move, updates the game board, and then checks if the game is over. If the game is not over, it switches to the other player and repeats. Once the game is over, it prints the final game board and announces the winner (if there is one) or the draw message.

Note that this code assumes that the players are represented as 1 and 2 in the game board matrix, and that a value of 0 in the game board matrix represents an empty cell.

related categories

gistlibby LogSnag