-
Notifications
You must be signed in to change notification settings - Fork 0
/
ttt.js
115 lines (107 loc) · 3.01 KB
/
ttt.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
const fs = require('fs');
// 0 = empty
// 1 = X
// 2 = O
const gameBoard = [
0, 0, 0,
0, 0, 0,
0, 0, 0
]
function checkWin(board){
// Check for draw or no moves
let empties = 0;
board.forEach(cell => {
if(cell == 0)
empties++;
});
// Not enough moves yet for a win
if(empties > 6)
return 0;
// Horizontal wins
if((board[0] == board[1] && board[1] == board[2]) && board[0] != 0)
return board[0];
if((board[3] == board[4] && board[4] == board[5]) && board[3] != 0)
return board[3];
if((board[6] == board[7] && board[7] == board[8]) && board[6] != 0)
return board[6];
// Vertical wins
if((board[0] == board[3] && board[3] == board[6]) && board[0] != 0)
return board[0];
if((board[1] == board[4] && board[4] == board[7]) && board[1] != 0)
return board[1];
if((board[2] == board[5] && board[5] == board[8]) && board[2] != 0)
return board[2];
// Diagonal wins
if((board[0] == board[4] && board[4] == board[8]) && board[0] != 0)
return board[0];
if((board[2] == board[4] && board[4] == board[6]) && board[2] != 0)
return board[2];
// Draw
if(empties == 0)
return 20;
// No wins
return 0;
}
function drawBoard(board){
let buffer = "";
let glyphs = [];
board.forEach(cell => {
if(cell == 0)
glyphs.push(" ");
else if(cell == 1)
glyphs.push("X");
else
glyphs.push("O");
});
buffer += `${glyphs[0]}|${glyphs[1]}|${glyphs[2]}\r\n`;
buffer += "-----\r\n";
buffer += `${glyphs[3]}|${glyphs[4]}|${glyphs[5]}\r\n`;
buffer += "-----\r\n";
buffer += `${glyphs[6]}|${glyphs[7]}|${glyphs[8]}\r\n`;
const win = checkWin(board);
if(win != 0){
if(win == 1)
buffer += "X Wins!";
else if(win == -1)
buffer += "Draw";
else
buffer += "O Wins!";
}
buffer += "\r\n"
return buffer;;
}
function moveX(game, tree){
for(let i = 0; i < game.length; i++) {
if (game[i] == 0) {
game[i] = 10;
if (checkWin(game) != 0) {
tree[i] = checkWin(game);
} else {
tree[i] = new Array(9);
moveO(game, tree[i]);
}
game[i] = 0;
} else {
tree[i] = [];
}
}
}
function moveO(game, tree){
for(let i = 0; i < game.length; i++){
if (game[i] == 0){
game[i] = 30;
if (checkWin(game) != 0){
tree[i] = checkWin(game);
} else {
tree[i] = new Array(9);
moveX(game, tree[i]);
}
game[i] = 0;
} else {
tree[i] = [];
}
}
}
const tree = new Array(9);
moveX([0,0,0,0,0,0,0,0,0], tree);
fs.writeFileSync("./tictactoe.json", JSON.stringify(tree));