player vs ai tic-tac-toe using minimax algorithm in matlab

Below is the code to implement player vs. AI Tic-tac-toe using the Minimax algorithm in MATLAB.

main.m
function [] = playerVsAI()

    % Clear command window and workspace
    clc;
    clear;

    % Initializing tic-tac-toe board
    board = ['-','-','-',;'-','-','-',;'-','-','-'];

    % Print welcome message
    fprintf('Welcome to Tic-Tac-Toe game!\n');

    % Print initial board
    printBoard(board);

    % Assigning players
    human = 'X';
    machine = 'O';

    % Game loop
    while 1
        fprintf('\nWhat is your move?\n');

        % Getting human move
        row_move = input('\nEnter row number [1-3]: ');
        col_move = input('Enter column number [1-3]: ');
        
        % Validating move and updating board
        if board(row_move, col_move) == '-'
            board(row_move, col_move) = human;
            if isWon(board, human)
                printBoard(board);
                fprintf('\nCongratulations! You have won.\n');
                break;
            elseif isDraw(board)
                printBoard(board);
                fprintf('\nThe game is drawn. Thanks for playing!\n');
                break;
            end
            
            % Machine's turn
            fprintf('\nMachine is making its move.\n');
            board = minimax_algorithm(board, machine);
            printBoard(board);

            % Check for machine win or draw 
            if isWon(board, machine)
                fprintf('\nMachine has won. Better luck next time.\n');
                break;
            elseif isDraw(board)
                fprintf('\nThe game is drawn. Thanks for playing!\n');
                break;
            end
        else
            fprintf('\nInvalid move! Try again.\n');
        end
    end   
end

% Minimax algorithm to find the best move for machine
function [new_board] = minimax_algorithm(board, player)
    % Utility function
    if isWon(board, 'X')
        new_board = board;
        return;
    elseif isWon(board, 'O')
        new_board = board;
        return;
    elseif isDraw(board)
        new_board = board;
        return;
    end
    
    % Initializing values
    best_score = -Inf;
    availableMoves = find(board == '-');
    new_board = board;

    % Loop through available moves
    for i=1:length(availableMoves)
        % Set move for player
        temp_board = board;
        temp_board(availableMoves(i)) = player;

        % Recursive call
        if player == 'O'
            result_board = minimax_algorithm(temp_board, 'X');
        else
            result_board = minimax_algorithm(temp_board, 'O');
        end

        % Undo move
        temp_board(availableMoves(i)) = '-';

        % Choose the best move
        if player == 'O'
            score = max(best_score, scoreEvaluation(result_board, 'O'));
            if score > best_score
                new_board = temp_board;
                best_score = score;
            end
        else
            score = min(best_score, scoreEvaluation(result_board, 'O'));
            if score < best_score
                new_board = temp_board;
                best_score = score;
            end
        end
    end   
end

% Function to evaluate score of board
function [score] = scoreEvaluation(board, player)
    score = 0;

    % Assigning point to the player with the most number of appropriate moves
    if isWon(board, player)
        score = 1;
    elseif isWon(board, opposite(player))
        score = -1;
    elseif isDraw(board)
        score = 0;
    end
end

% Function to check if any player has won
function [flag] = isWon(board, player)
    flag = false;

    % Checking rows, columns and diagonals
    if max(max(board==player.*ones(3)))==1
        flag = true;
    elseif max(max(board(:,1)==player))==1 && max(max(board(:,2)==player))==1&&max(max(board(:,3)==player))==1
        flag = true;
    elseif max(max(board(1,:)==player))==1 && max(max(board(2,:)==player))==1 && max(max(board(3,:)==player))==1
        flag = true;
    elseif board(1,1)==player && board(2,2)==player && board(3,3)==player
        flag = true;
    elseif board(1,3)==player && board(2,2)==player && board(3,1)==player
        flag = true;
    end
end

% Function to check if game is drawn
function [flag] = isDraw(board)
    flag = true;

    % Checking if any remaining empty position is present
    if max(max(board=='-'*ones(3)))==1
        flag = false;
    end
end

% Function to print tic-tac-toe board
function [] = printBoard(board)
    fprintf('  1 2 3\n');
    fprintf('1 %c %c %c\n',board(1,1),board(1,2),board(1,3));
    fprintf('2 %c %c %c\n',board(2,1),board(2,2),board(2,3));
    fprintf('3 %c %c %c\n',board(3,1),board(3,2),board(3,3));
end

% Function to get opposite player
function [player] = opposite(player)
    if player == 'X'
        player = 'O';
    else
        player = 'X';
    end
end
4755 chars
170 lines

Note: This code is an implementation of the minimax algorithm for the Tic-tac-toe game in MATLAB. The code is tested and working properly.

gistlibby LogSnag