-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
279 lines (236 loc) · 6.71 KB
/
index.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
271
272
273
274
275
276
277
278
279
let easyGamePlay;
const State = function (old) {
this.turn = '';
this.oMovesCount = 0;
this.result = 'still running';
this.board = [];
// create new state
if (typeof old !== 'undefined') {
const length = old.board.length;
this.board = new Array(length);
for (let i = 0; i < length; i++) {
this.board[i] = old.board[i];
}
this.oMovesCount = old.oMovesCount;
this.result = old.result;
this.turn = old.turn;
}
this.advanceTurn = function () {
this.turn = (this.turn === 'X')
? 'O'
: 'X';
};
this.emptyCells = function () {
const cells = [];
for (let i = 0; i < 9; i++) {
if (this.board[i] === 'E') {
cells.push(i);
}
}
return cells;
};
this.isWinner = function () {
const B = this.board;
// check rows
for (let i = 0; i <= 6; i += 3) {
if (B[i] !== 'E' && B[i] === B[i + 1] && B[i + 1] == B[i + 2]) {
this.result = `${B[i]}-won`;
return true;
}
}
// check columns
for (let i = 0; i <= 2; i++) {
if (B[i] !== 'E' && B[i] === B[i + 3] && B[i + 3] === B[i + 6]) {
this.result = `${B[i]}-won`;
return true;
}
}
// check diagonals
for (let i = 0, j = 4; i <= 2; i += 2, j -= 2) {
if (B[i] !== 'E' && B[i] == B[i + j] && B[i + j] === B[i + 2 * j]) {
this.result = `${B[i]}-won`;
return true;
}
}
const available = this.emptyCells();
if (available.length === 0) {
this.result = 'draw';
return true;
}
return false;
};
};
const playerMove = function (pos) {
this.movePosition = pos;
this.minimaxVal = 0;
this.applyTo = function (state) {
const next = new State(state);
// put the letter on the board
next.board[this.movePosition] = state.turn;
if (state.turn === 'O') {
next.oMovesCount++;
}
next.advanceTurn();
return next;
};
};
const Game = function (autoPlayer) {
// public : initialize the ai player for this game
this.ai = autoPlayer;
this.currentState = new State();
this.currentState.board = [
'E',
'E',
'E',
'E',
'E',
'E',
'E',
'E',
'E',
];
this.currentState.turn = 'X';
this.status = 'beginning';
this.advanceTo = function (_state) {
this.currentState = _state;
if (_state.isWinner()) {
this.status = 'ended';
}
};
this.start = function () {
if (this.status = 'beginning') {
this.advanceTo(this.currentState);
this.status = 'running';
}
};
};
Game.score = function (_state) {
if (_state.result === 'X-won') {
// the x player won
return 10 - _state.oMovesCount;
} else if (_state.result === 'O-won') {
// the x player lost
return -10 + _state.oMovesCount;
}
// it's a draw
return 0;
};
function minimaxValue(state) {
if (state.isWinner()) {
return Game.score(state);
}
let stateScore;
if (state.turn === 'X')
// X wants to maximize --> initialize to a value smaller than any possible score
{
stateScore = -1000;
} else
// O wants to minimize --> initialize to a value larger than any possible score
{
stateScore = 1000;
}
const availablePositions = state.emptyCells();
// enumerate next available states using the info form available positions
const availableNextStates = availablePositions.map((pos) => {
const action = new AIAction(pos);
const nextState = action.applyTo(state);
return nextState;
});
availableNextStates.forEach((nextState) => {
const nextScore = minimaxValue(nextState);
if (state.turn === 'X') {
if (nextScore > stateScore) {
stateScore = nextScore;
}
} else if (nextScore < stateScore) {
stateScore = nextScore;
}
});
return stateScore;
}
const AIAction = function (pos) {
this.movePosition = pos;
this.minimaxVal = 0;
this.applyTo = function (state) {
const next = new State(state);
// put the letter on the board
next.board[this.movePosition] = state.turn;
if (state.turn === 'O') {
next.oMovesCount++;
}
next.advanceTurn();
return next;
};
};
AIAction.ASCENDING = function (firstAction, secondAction) {
if (firstAction.minimaxVal < secondAction.minimaxVal) {
return; // indicates that firstAction goes before secondAction
-1;
} else if (firstAction.minimaxVal > secondAction.minimaxVal) {
return 1;
} // indicates that secondAction goes before firstAction
return 0; // indicates a tie
};
AIAction.DESCENDING = function (firstAction, secondAction) {
if (firstAction.minimaxVal > secondAction.minimaxVal) {
return; // indicates that firstAction goes before secondAction
-1;
} else if (firstAction.minimaxVal < secondAction.minimaxVal) {
return 1;
} // indicates that secondAction goes before firstAction
return 0; // indicates a tie
};
function calcBest(turn) {
let chosenAction;
const available = game.currentState.emptyCells();
const availableActions = available.map((pos) => {
const action = new AIAction(pos); // create the action object
const next = action.applyTo(game.currentState); // get next state by applying the action
action.minimaxVal = minimaxValue(next); // calculate and set the action's minmax value
return action;
});
if (turn === 'X') {
availableActions.sort(AIAction.DESCENDING);
} else {
availableActions.sort(AIAction.ASCENDING);
}
if (easyGamePlay) {
const rando = Math.floor(Math.random() * 2);
chosenAction = availableActions[rando];
} else {
chosenAction = availableActions[0];
}
const next = chosenAction.applyTo(game.currentState);
game.advanceTo(next);
return chosenAction;
}
const game = new Game();
game.start();
// console.log(game.currentState, 'game start');
// calcBest('X');
// console.log('best first move!!!!', game.currentState);
// console.log('first move state', game.currentState);
// let move = calcBest('O');
// game.currentState.isWinner();
// console.log('new game state:', game.currentState);
// let Xmove = calcBest('X');
// game.currentState.isWinner();
// console.log('new game state:', game.currentState);
// move = calcBest('O');
// game.currentState.isWinner();
// console.log('new game state:', game.currentState);
// Xmove = calcBest('X');
// game.currentState.isWinner();
// console.log('new game state:', game.currentState);
// move = calcBest('O');
// game.currentState.isWinner();
// console.log('new game state:', game.currentState);
// Xmove = calcBest('X');
// game.currentState.isWinner();
// console.log('new game state:', game.currentState);
// move = calcBest('O');
// game.currentState.isWinner();
// console.log('new game state:', game.currentState);
// Xmove = calcBest('X');
// game.currentState.isWinner();
// console.log('new game state:', game.currentState);