% Evaluation function for tic tac toe board
function score = evaluate_tictactoe(board, player)
% check rows for victory
score = evaluate_rows(board, player);
% check columns for victory
score = max(score, evaluate_cols(board, player));
% check diagonal for victory
score = max(score, evaluate_diag(board, player));
end
% Helper function to evaluate rows
function score = evaluate_rows(board, player)
score = max([sum(board == player, 2); 0]);
end
% Helper function to evaluate columns
function score = evaluate_cols(board, player)
score = max([sum(board == player, 1), 0]);
end
% Helper function to evaluate diagonal
function score = evaluate_diag(board, player)
diag1 = board(1,1) == player && board(2,2) == player && board(3,3) == player;
diag2 = board(1,3) == player && board(2,2) == player && board(3,1) == player;
score = diag1 || diag2;
end
% Minimax function to choose the best move
function best_move = minimax(board, player)
% Available moves on the board
free_indices = find(board == 0);
% Evaluating leaf nodes & returning leaf score
if isempty(free_indices)
score = evaluate_tictactoe(board, player);
best_move = [score, -1];
return;
end
% Check for victory by AI
score = evaluate_tictactoe(board, player);
if score > 0
best_move = [score, -1];
return;
end
% Check for victory by opponent
other_player = 3 - player;
score = evaluate_tictactoe(board, other_player);
if score > 0
best_move = [-score, -1];
return;
end
% Recursively calling minimax for each available move
minmax_scores = zeros(length(free_indices), 2);
for i=1:length(free_indices)
[r, c] = ind2sub(size(board), free_indices(i));
board_copy = board;
board_copy(r, c) = player;
minmax_scores(i, :) = [minimax(board_copy, other_player)(1)*-1, free_indices(i)];
end
% Choosing optimal move as per current player
if player == 1
best_move = max(minmax_scores);
else
best_move = min(minmax_scores);
end
end
% Wrapper function to use in interactive games
function board = play_tictactoe()
board = zeros(3);
player = 1;
while true
print_board(board);
if player == 1
% AI player's turn
[~, move] = minimax(board, player);
[r, c] = ind2sub(size(board), move);
board(r, c) = player;
else
% Human player's turn
[r, c] = input('player 2 move: ');
board(r, c) = player;
end
score = evaluate_tictactoe(board, player);
if score > 0
fprintf('Player %d wins!\n', player);
print_board(board);
break;
end
if all(board(:))
fprintf('Game over, no winner.\n');
print_board(board);
break;
end
player = 3 - player;
end
end
% Function to print the current board configuration
function print_board(board)
for i=1:size(board, 1)
for j=1:size(board, 2)
if board(i, j) == 0
fprintf('-');
else
fprintf('%d', board(i, j));
end
end
fprintf('\n');
end
fprintf('\n');
end
You can run the code in Matlab environment and play against the AI to see it in action.