forked from sinhas/TicTacToe
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathminimax.m
96 lines (82 loc) · 2.21 KB
/
minimax.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
%% Minimax algorithm for Tic Tac Toe game implementation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% Start of minimax algorithm implementation
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [bestScore, bestChild] = minimax(state, maximizingPlayer, depth)
bestChild = [];
if ( isGameOver(state) || depth == 0 )
bestScore = evaluate(state,maximizingPlayer, depth);
else
if (maximizingPlayer)
bestScore = -inf;
else
bestScore = inf;
end
childrenBoard = getChildren(state,maximizingPlayer) ;
i = 1;
size = size(childrenBoard ,2)/3;
while i <= size
childBoard = childrenBoard(:,3*i-2:3*i);
score = minimax(childBoard, !maximizingPlayer, depth-1);
if (maximizingPlayer)
if (bestScore < score)
bestScore = score;
bestChild = childBoard ;
end
else
if (bestScore > score)
bestScore = score;
bestChild = childBoard;
end
end
i++;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% evaluate score from player perspective %%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function score = evaluate(state, player, depth)
global b;
global x;
winner = gameStat(state);
if (winner == b)
score = 0;
elseif (winner == x)
score = 10 + depth ;
else
score = -10 - depth;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% Get all children board %%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function childrenBoard = getChildren(state, player)
global b;
maxRow = 3;
maxCol = 3;
rowCur = 1;
childrenBoard =[];
while rowCur <= maxRow
colCur = 1;
while colCur <= maxCol
if (state(rowCur,colCur) == b)
dummyBoard = state;
dummyBoard(rowCur,colCur) = player;
childrenBoard = [childrenBoard,dummyBoard];
end
colCur++;
end
rowCur++;
end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% Check for game over %%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function gameOver = isGameOver(state)
global b;
winner = gameStat(state);
if (ismember([b],state) && winner == b)
gameOver = false;
else
gameOver = true;
end