-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtictactoe.js
185 lines (156 loc) · 4.75 KB
/
tictactoe.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
function rowSame(row) {
return row[0] === row[1] && row[1] === row[2] && row[2] !== null;
}
function transpose(table) {
return table[0].map((_, i) => table.map((row) => row[i]));
}
function moveToStr(column, row) {
return String.fromCodePoint("A".codePointAt() + column) +
String.fromCodePoint("1".codePointAt() + (2 - row));
}
function strToMove(str) {
const column = str[0].codePointAt() - "A".codePointAt();
const row = 2 - (str[1].codePointAt() - "1".codePointAt());
return [column, row];
}
export class Game {
constructor(game) {
this.board = [
[null, null, null],
[null, null, null],
[null, null, null],
];
if(game !== undefined) {
for(let i = 0; i < this.board.length; i++) {
for(let j = 0; j < this.board[i].length; j++) {
this.board[i][j] = game.board[i][j];
}
}
}
}
findPossibleMoves() {
const possibleMoves = [];
for(let i = 0; i < this.board.length; i++) {
for(let j = 0; j < this.board[i].length; j++) {
if(this.board[i][j] == null) {
possibleMoves.push(moveToStr(j, i));
}
}
}
return possibleMoves;
}
scorePossibleMoves(depth) {
const scoredMoves = [];
for(const move of this.findPossibleMoves()) {
const next = new Game(this);
next.makeMove(move);
let score = 0;
if(next.isGameOver()) {
if(next.hasWinner()) {
if(this.isTurnOfX()) {
score = 10 - depth;
} else {
score = -10 + depth;
}
} else {
score = 0;
}
} else {
const nextScores = next.scorePossibleMoves(depth + 1);
// next player will move against this player: if current is X, next
// will minimize score and if current is O, next will maximize score
if(this.isTurnOfX()) {
score = nextScores[0].score;
} else {
score = nextScores[nextScores.length - 1].score;
}
}
scoredMoves.push({ move: move, score: score });
}
scoredMoves.sort((a, b) => a.score < b.score ? -1 : 1);
return scoredMoves;
}
/**
* Given the current board, calculate the best move for the current player.
*/
calculateBestMove() {
if(this.isGameOver()) {
throw new Error("Game over");
}
const moveScores = this.scorePossibleMoves(0);
if(this.isTurnOfX()) {
return moveScores[moveScores.length - 1].move;
} else {
return moveScores[0].move;
}
}
/**
* Mutate the current game with a move coded with a letter followed by a
* number. The letter denotes the column of the move, while the letter
* denotes the row. A1 is the bottom left corner and C3 the top right.
*/
makeMove(moveStr) {
const [column, row] = strToMove(moveStr);
if(this.isGameOver()) {
throw new Error("Game over");
}
if(column < 0 || column >= 3 || row < 0 || row >= 3) {
throw new Error("Invalid move");
}
if(this.board[row][column] !== null) {
throw new Error("Illegal move");
}
this.board[row][column] = this.numMoves() % 2 == 0 ? "X" : "O";
}
/**
* Returns the number of moves made in the game. This can be used to
* determine the current player. Even means X, odd means O.
*/
numMoves() {
return this.board.reduce((tableAcc, row) => {
return tableAcc + row.reduce((rowAcc, x) => {
return rowAcc + (x !== null ? 1 : 0);
}, 0);
}, 0);
}
/**
* Returns whether the game is over. The game is over when there is a winner
* or if the board is full.
*/
isGameOver() {
const isFull = !this.board.some((row) => row.some((c) => c === null));
return this.hasWinner() || isFull;
}
/**
* Returns whether X should make a move
*/
isTurnOfX() {
return this.numMoves() % 2 == 0;
}
/**
* Returns whether the game has a winner. If any row, column or diagonal is
* filled with the same pieces, the game is won by that player. When there is
* a winner, an even number of moves means that O won, while an odd number of
* moves means that X won.
*/
hasWinner() {
const rows = this.board.some(rowSame);
const columns = transpose(this.board).some(rowSame);
const diagonals = (
rowSame([this.board[0][0], this.board[1][1], this.board[2][2]]) ||
rowSame([this.board[0][2], this.board[1][1], this.board[2][0]]));
return rows || columns || diagonals;
}
/**
* Returns a string representation of the current game, including the board
* and the placed pieces.
*/
toString() {
return [
"_____",
"3:" + this.board[0].map((x) => x ? x : " ").join(""),
"2:" + this.board[1].map((x) => x ? x : " ").join(""),
"1:" + this.board[2].map((x) => x ? x : " ").join(""),
"__ABC"].join("\n");
}
}