-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
270 lines (236 loc) · 6.13 KB
/
script.js
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
const X = -1; // represent player
const O = 1; // represent agent
const EMPTY = 0;
let state = emptyState();
let round = 0;
let filledBoxs = new Set()
let isGameFinished = false;
agentMinimax()
// put x or o
function play(id) {
id = parseInt(id) // to store in set
// box already filled
if (filledBoxs.has(id) || isGameFinished || round % 2 == 0) {
return;
}
// player players move
state[id] = X;
filledBoxs.add(id)
draw(id, X);
round++;
// check is game over
let winner = check(state);
// finish game if there is winner
if (winner != null)
finishGame(winner)
if (isGameFinished)
return;
// minimax agent plays
agentMinimax()
// check is game over
winner = check(state)
// finish game if there is winner
if (winner != null)
finishGame(winner)
if (round == 9 && !isGameFinished) {
isGameFinished = true;
display("Tie", "text-white")
}
}
// finish game and display winner
function finishGame(winner) {
isGameFinished = true;
let message;
let textColor;
if (winner == X) {
message = "X won"
textColor = "text-success";
}
else if (winner == O) {
message = "O won"
textColor = "text-danger";
}
display(message, textColor)
}
// display pop-up message
function display(message, textColor) {
let display = document.getElementById("display");
display.classList.remove("text-danger", "text-success", "text-white")
display.classList.add(textColor)
setTimeout(function() {
display.innerHTML = message;
}, 1000)
}
// return winner if game is finished
function check(state) {
//check row
for (let i = 0; i < 3; i++) {
let sum = state[0 + (i * 3)] + state[1 + (i * 3)] + state[2 + (i * 3)];
if (sum == 3)
return O;
if (sum == -3)
return X;
}
// check column
for (let i = 0; i < 3; i++) {
let sum = state[0 + i] + state[3 + i] + state[6 + i];
if (sum == 3)
return O;
if (sum == -3)
return X;
}
// check diagonals
let diagonal1 = state[0] + state[4] + state[8];
if (diagonal1 == 3)
return O;
if (diagonal1 == -3)
return X;
let diagonal2 = state[2] + state[4] + state[6];
if (diagonal2 == 3)
return O;
if (diagonal2 == -3)
return X;
// no winner
return null;
}
// reset the game
function reset() {
// resest game parameters
isGameFinished = false;
round = 0;
// reset game array
for (let i = 0; i < state.length; i++) {
state[i] = 0;
}
// reset clicked boxes
filledBoxs = new Set()
// reset ui
for (let i = 0; i < 9; i++) {
document.getElementById(i).innerHTML = null;
}
// agent start other play
agentMinimax()
// clear screen
let display = document.getElementById("display");
display.innerHTML = null;
}
function emptyState() {
let state = []
for (let i = 0; i < 9; i++)
state.push(0)
return state;
}
// find all empty spots
function getValidMoves(state) {
let moves = []
for (let i = 0; i < state.length; i++) {
if (state[i] == EMPTY)
moves.push(i)
}
return moves;
}
// draw move to ui
function draw(id, player) {
let element = document.getElementById(id);
// player plays
let sign;
if (player == -1)
sign = 'X';
else
sign = 'O';
element.innerHTML = sign;
// update datas
}
/****************random*******************/
// select move randomly
function agentRandom() {
let validMoves = getValidMoves(state);
let id = validMoves[Math.floor(Math.random() * validMoves.length)]
state[id] = O;
filledBoxs.add(id)
round++;
// player plays
setTimeout(function() {
draw(id, O);
}, 400)
}
/******************************************/
/*******************minimax****************/
//minimax agent
function agentMinimax() {
let moves = getValidMoves(state);
// play for computer to see scores
let scores = [];
for (let i = 0; i < moves.length; i++) {
let originalState = [...state]
state[moves[i]] = O;
let score = minimax(state, false, 1);
scores.push(score);
state = originalState;
}
let id = moves[bestScoreIndex(scores)]
state[id] = O
filledBoxs.add(id)
round++;
setTimeout(function() {
draw(id, O);
}, 400)
}
// minimax algorithm: return best score of given state
function minimax(futureState, isMax, depth) {
// check for winner
let result = check(futureState)
if (result != null)
return result / depth;
// check is game ended
if (isDraw(futureState)) {
return 0;
}
// inital score
let score = -Infinity;
if (!isMax) {
score = Infinity;
}
let futureMoves = getValidMoves(futureState);
for (let i = 0; i < futureMoves.length; i++) {
let originalState = [...futureState]
if (isMax) {
futureState[futureMoves[i]] = O;
score = Math.max(score, minimax(futureState, !isMax, depth + 1));
}
else {
futureState[futureMoves[i]] = X;
score = Math.min(score, minimax(futureState, !isMax, depth + 1));
}
futureState = originalState;
}
return score / depth;
}
// return one of the max element index
function bestScoreIndex(scores) {
let bestScore = getBestScore(scores);
let optimalIndexes = [];
for (let i = 0; i < scores.length; i++) {
if (scores[i] == bestScore) {
optimalIndexes.push(i)
}
}
return optimalIndexes[Math.floor(Math.random() * optimalIndexes.length)];
}
// find best score
function getBestScore(scores) {
let max = scores[0];
for (let i = 1; i < scores.length; i++)
max = Math.max(max, scores[i]);
return max;
}
// return if game is drawn
function isDraw(state) {
let count = 0;
for (let i = 0; i < state.length; i++) {
if (state[i] == 0)
count++;
}
return count == 0;
}
/******************************************/