player vs ai tictactoe game where player can never win in matlab

To create an AI-controlled Tic Tac Toe game in MATLAB where the player can never win, we can use the minimax algorithm. This algorithm chooses the best possible move for the AI to make, assuming that the player will also make their best possible move.

Here is an example of how the minimax algorithm can be used to build an unbeatable AI for a 3x3 Tic Tac Toe game in MATLAB:

main.m
% Initialize the game board:
board = ["-" "-" "-";
         "-" "-" "-";
         "-" "-" "-"];

% The AI makes the first move
player = "O"; % AI marks with "O"
    
% Play the game until it is over
gameOver = false;
while ~gameOver   
    % AI's turn
    if player == "O"
        % Choose the best move using the minimax algorithm
        [row, col] = findBestMove(board);
        board(row, col) = player;
        disp("AI's move:");
        disp(board);        
    % Player's turn
    else
        % Get player's move
        [row, col] = getPlayerMove(board);
        board(row, col) = player;
        disp("Player's move:");
        disp(board);
    end
    
    % Check if game is over
    [gameOver, winner] = checkGameOver(board);
    
    % Switch player
    player = switchPlayer(player);
end

% Display the winner of the game
if winner == "-"
    disp("Game is a tie");
else
    disp("Winner is " + winner);
end
924 chars
41 lines

The findBestMove() function uses the minimax algorithm to calculate and return the best possible move for the AI. The getPlayerMove() function prompts the user to input their move and returns the row and column values.

main.m
function [row, col] = findBestMove(board)
    bestScore = -Inf;
    moveRow = 0;
    moveCol = 0;
    
    % Check each possible move
    for i = 1:3
        for j = 1:3
            % Check if the cell is empty
            if board(i,j) == "-"
                % Make the move
                board(i,j) = "O";
                
                % Calculate the score for this move
                score = minimax(board, false);
                
                % Undo the move
                board(i,j) = "-";
                
                % Update best score and move
                if score > bestScore
                    bestScore = score;
                    moveRow = i;
                    moveCol = j;
                end
            end
        end
    end
    
    % Return the best move
    row = moveRow;
    col = moveCol;
end

function score = minimax(board, isMaximizing)
    % Check if game is over
    [gameOver, winner] = checkGameOver(board);
    if gameOver
        % Return score based on winner
        if winner == "O"
            score = 1;
        elseif winner == "X"
            score = -1;
        else
            score = 0;
        end
        return
    end
    
    % Get the scores of all possible moves
    if isMaximizing
        bestScore = -Inf;
        for i = 1:3
            for j = 1:3
                % Check if the cell is empty
                if board(i,j) == "-"
                    % Make the move
                    board(i,j) = "O";
                    
                    % Calculate the score for this move
                    score = minimax(board, false);
                    
                    % Undo the move
                    board(i,j) = "-";
                    
                    % Update best score
                    bestScore = max(bestScore, score);
                end
            end
        end
        score = bestScore;
    else
        bestScore = Inf;
        for i = 1:3
            for j = 1:3
                % Check if the cell is empty
                if board(i,j) == "-"
                    % Make the move
                    board(i,j) = "X";
                    
                    % Calculate the score for this move
                    score = minimax(board, true);
                    
                    % Undo the move
                    board(i,j) = "-";
                    
                    % Update best score
                    bestScore = min(bestScore, score);
                end
            end
        end
        score = bestScore;
    end
end

function [gameOver, winner] = checkGameOver(board)
    % Check rows
    for i = 1:3
        if board(i,1) == board(i,2) && board(i,2) == board(i,3) && board(i,1) ~= "-"
            gameOver = true;
            winner = board(i,1);
            return
        end
    end
    
    % Check columns
    for j = 1:3
        if board(1,j) == board(2,j) && board(2,j) == board(3,j) && board(1,j) ~= "-"
            gameOver = true;
            winner = board(1,j);
            return
        end
    end
    
    % Check diagonals
    if board(1,1) == board(2,2) && board(2,2) == board(3,3) && board(1,1) ~= "-"
        gameOver = true;
        winner = board(1,1);
        return
    end
    if board(1,3) == board(2,2) && board(2,2) == board(3,1) && board(1,3) ~= "-"
        gameOver = true;
        winner = board(1,3);
        return
    end
    
    % Check if board is full
    if any(board == "-")
        gameOver = false;
        winner = "-";
    else
        gameOver = true;
        winner = "-";
    end
end

function player = switchPlayer(player)
    if player == "O"
        player = "X";
    else
        player = "O";
    end
end

function [row, col] = getPlayerMove(board)
    validMove = false;
    while ~validMove
        % Prompt user for move
        row = input("Enter the row index:");
        col = input("Enter the column index:");
        
        % Check if move is valid
        if board(row, col) == "-"
            validMove = true;
        else
            disp("Invalid move. Try again.");
        end
    end
end
4102 chars
160 lines

Overall, this implementation should result in an unbeatable AI-controlled Tic Tac Toe game in MATLAB.

gistlibby LogSnag