-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
238 lines (202 loc) · 6.1 KB
/
main.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
const { app, BrowserWindow, Menu, ipcMain } = require('electron');
const url = require('url');
const path = require('path');
const brain = require('brain.js');
const fs = require('fs');
const net = new brain.NeuralNetwork();
let mainWindow;
var keepTraining = false;
// Saves the past boards and the computers decisions for future trainings
const moves = [];
// Listen for app to be ready
app.on('ready', () => {
// Create new window
mainWindow = new BrowserWindow({
title: "Tic-Tac-Toe Master",
webPreferences: {
nodeIntegration: true
}
});
// Prevents the user from changing the window size
mainWindow.setResizable(false);
//Load HTML into window
mainWindow.loadURL(url.format({
pathname: path.join(__dirname, 'mainWindow.html'),
protocol: 'file:',
slashes: true
}));
// Build menu from template
const mainMenu = Menu.buildFromTemplate(mainMenuTemplate);
// Quit app when closed
mainWindow.on('closed', () => app.quit());
// Insert the menu onto the window
Menu.setApplicationMenu(mainMenu);
});
checkBoard = unformated => {
var board = [];
unformated = unformated.map(cell => !cell ? 0 : cell === 'X' ? 1 : -1);
while(unformated.length)
board.push(unformated.splice(0, 3));
// Checks each row and column for victories
for(var i = 2; i >= 0; i--) {
var rowSum = 0,
colSum = 0;
for(var j = 2; j >= 0; j--) {
rowSum += board[i][j];
colSum += board[j][i];
}
if(rowSum === 3 || colSum === 3) {
mainWindow.send('Winner', "CROSSES");
return true;
}
else if(rowSum === -3 || colSum === -3) {
mainWindow.send('Winner', "CIRCLES");
return true;
}
}
// Checks diagnols
var points = board[0][0] + board[1][1] + board[2][2];
if(points === 3) {
mainWindow.send('Winner', "CROSSES");
return true;
}
else if(points === -3) {
mainWindow.send('Winner', "CIRCLES");
return true;
}
points = board[2][0] + board[1][1] + board[0][2];
if(points === 3) {
mainWindow.send('Winner', "CROSSES");
return true;
}
else if(points === -3) {
mainWindow.send('Winner', "CIRCLES");
return true;
}
return false;
}
// Checks the board to see if there's a winner
ipcMain.on('board:check', (e, unformated, auto) => {
var aiBoard = [...unformated.map(cell => !cell ? 0.5 : cell === "X" ? 1 : 0)];
// Check if the player won, if so inverse the moves for the future
if(checkBoard(unformated)) {
moves.map(move => {
for(var i = 0; i < 8; i++) {
// Checks against the input to ensure the moves the computer didn't make were impossible
if(move.output[i]){
move.output[i] = 0;
continue;
}
if(move.input[i] === 0.5)
move.output[i] = 1;
}
});
saveData();
return;
}
// No winner - allow AI to determine the next move and save that decision incase of a win later
var output = net.run(aiBoard);
var result = null;
for(var i = aiBoard.length - 1; i >= 0; i--) {
if(aiBoard[i] !== 0.5)
continue;
if(!result || output[i] > output[result])
result = i
}
// Update the board with the AIs turn and save the decision
mainWindow.send('npcTurn', result);
unformated[result] = "O";
moves.push({input: aiBoard, output: [...output.map((o, i) => i === result ? 1 : 0)]});
// Check if the computer won, if so save these moves for the future
if(checkBoard(unformated)) {
saveData();
return;
}
});
// Saves the moves to the training data for future training
saveData = () => {
var data = JSON.parse(fs.readFileSync('./train.json'));
data.push(...moves);
fs.writeFile("./train.json", JSON.stringify(data), err => {
if(err)
throw err;
retrain();
});
}
// This removes all the data from the train.js
clearData = () => {
var freshData = [{
"input": [0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5, 0.5],
"output": [0, 0, 0, 0, 1, 0, 0, 0, 0],
}]
fs.writeFile('./train.json', JSON.stringify(freshData), err => {
if(err)
throw err;
console.log('I.... forgot...');
retrain();
});
}
// Retrains the network
retrain = () => {
if(!keepTraining)
return;
console.log("Training");
net.train(JSON.parse(fs.readFileSync('./train.json')));
console.log("I'M READY!");
}
// Trains the network with the past moves
retrain();
// Create menu template
const mainMenuTemplate = [
{
label: "File",
submenu: [
{
label: 'Restart',
click() {
mainWindow.send('Reset');
}
},
{
label: "Train each game",
click() {
keepTraining = !keepTraining;
}
},
{
label: 'Quit',
accelerator: process.platform == 'darwin' ? "Command+Q" : "Ctrl+Q",
click() {
app.quit();
}
}
]
}
];
// If mac, add empty object to menu
if(process.platform == 'darwin')
mainMenuTemplate.unshift({});
// Add developer tools item if not in production
if(process.env.NODE_ENV !== 'production') {
mainMenuTemplate.push({
label: 'Developer Tools',
submenu: [
{
label: 'Toggle DevTools',
accelerator: process.platform == 'darwin' ? "Command+I" : "Ctrl+I",
click(item, focusWindow) {
focusWindow.toggleDevTools();
}
},
{
role: 'reload'
},
{
label: "Clear Data",
click() {
clearData();
}
},
]
})
}