To implement a Tic-Tac-Toe game using the Minimax Algorithm, you will need to follow these steps:
function [score] = evaluate(board)
% Evaluate the board and return a score.
% +10 if computer wins, -10 if human wins, 0 if tie.
if check_win(board, 'O')
score = 10;
return;
elseif check_win(board, 'X')
score = -10;
return;
elseif all(all(board ~= ' '))
score = 0;
return;
end
score = 0;
end
function [winner] = check_win(board, player)
% Check if the given player has won.
% Return true if so, false otherwise.
winner = false;
for i = 1:3
if board(i, :) == repmat(player, 1, 3) || ...
board(:, i) == repmat(player, 3, 1) || ...
all(diag(board) == repmat(player, 3, 1)) || ...
all(diag(fliplr(board)) == repmat(player, 3, 1))
winner = true;
break;
end
end
end
function [score, move] = minimax(board, depth, is_max)
% Apply the Minimax Algorithm to the board and return the best move.
% Depth is the number of moves ahead to consider, and is_max is true if
% it's the computer's turn.
if check_win(board, 'O')
score = 10;
return;
elseif check_win(board, 'X')
score = -10;
return;
elseif all(all(board ~= ' '))
score = 0;
return;
end
if is_max
best_score = -Inf;
move = struct('x', 0, 'y', 0);
for i = 1:3
for j = 1:3
if board(i, j) == ' '
board(i, j) = 'O';
[score, ~] = minimax(board, depth+1, false);
board(i, j) = ' ';
if score > best_score
best_score = score;
move.x = i;
move.y = j;
end
end
end
end
score = best_score;
else
best_score = Inf;
for i = 1:3
for j = 1:3
if board(i, j) == ' '
board(i, j) = 'X';
[score, ~] = minimax(board, depth+1, true);
board(i, j) = ' ';
if score < best_score
best_score = score;
end
end
end
end
score = best_score;
end
end
board = repmat(' ', 3, 3);
while true
% User's turn
disp(board);
x = input('Enter row (1-3): ');
y = input('Enter column (1-3): ');
board(x, y) = 'X';
if check_win(board, 'X')
disp(board);
disp('You win!');
break;
elseif all(all(board ~= ' '))
disp(board);
disp('Tie!');
break;
end
% Computer's turn
[~, move] = minimax(board, 0, true);
board(move.x, move.y) = 'O';
if check_win(board, 'O')
disp(board);
disp('You lose!');
break;
elseif all(all(board ~= ' '))
disp(board);
disp('Tie!');
break;
end
end
Note: This implementation assumes that the user always plays first. To make the computer play first, simply swap the User's turn and Computer's turn sections.