-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
309 lines (255 loc) · 7.88 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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var net = require('net');
var JSONStream = require('JSONStream');
var es = require('event-stream');
var fs = require('fs');
var reference = require('./referenceClient');
app.use(express.static(__dirname + '/public'));
/////
// CLIENT CONNECTING LOGIC
// The connected clients that will increment the game together
var clients = {}; // id: socket
var clientWorlds = {}; // id, world
var clientStats = {
testsRun: 0,
testsFailed: 0,
testsIgnored: 0
};
var client_id = 0,
problem_id = 0,
generationId = 0;
var statsFile = 'stats.log';
var width = 100,
height = 100;
// TODO use buffer
var world = [];
var correctClientWorld = []; // Collect client response correctness here
resetWorld();
function resetWorld() {
console.log("Resetting world");
var tempWorld = new Array(width * height);
for (var x = 0; x < width; x++) {
for (var y = 0; y < height; y++) {
tempWorld[ x + (y*width)] = Math.random() > 0.5;
}
}
writeSquareFromArray(tempWorld, 0, 0, width, height);
}
function getKeyFromXY(x, y) {
return x + ':' + y;
}
function getXYFromKey(key) {
var coords = key.split(':');
return {
x: coords[0],
y: coords[1]
};
}
// read and write parts of the world
// world, w, h are set
function writeSquareFromArray(data, x, y, w, h) {
for(var i = 0; i < w; i++) {
for(var j = 0; j < h; j++) {
if (!! data[i + (j*w)]) {
world[getKeyFromXY(x+i, y+j)] = true;
}
}
}
}
function readWorldSquareToArray(x, y, w, h) {
var data = new Array(w * h);
for (var i = 0; i < w; i++) {
for (var j = 0; j < h; j++) {
data[i + (j * w)] = !!world[getKeyFromXY(x+i, y+j)];
}
}
return data;
}
function readSquareToArray(thisWorld, x, y, w, h) {
var data = new Array(w * h);
for (var i = 0; i < w; i++) {
for (var j = 0; j < h; j++) {
data[i + (j * w)] = thisWorld[getKeyFromXY(x+i, y+j)];
}
}
return data;
}
function toIndexOfKey(cell) {
return cell.x + ":" + cell.y;
}
function toBinaryString(arrayOfBooleans) {
return arrayOfBooleans.map(function (value) {
return value ? 1 : 0;
}).join('');
}
var server = net.createServer(function (c) {
var id = client_id++;
clients[id] = c;
clientWorlds[id] = readWorldSquareToArray(0,0, width, height);
console.log('client ' + id + ' connected');
var deleteClient = function (err) {
if (clients[id]) {
delete clients[id];
delete clientWorlds[id];
console.log('client ' + id + ' disconnected' + (err ? ' (errored)' : ''));
}
};
c.on('end', deleteClient);
c.on('error', deleteClient);
c.pipe(JSONStream.parse(true)).pipe(es.mapSync(function (data) {
process(id, data);
}));
});
server.listen(8787, function () {
console.log('listening for clients on *:8787');
});
// Process a message from the client
function process(clientId, data) {
try {
if (data.success === false) {
// We'll not worry and just ignore it for now
}
else if (data.respondingTo === 'tickBoard') {
var latestResult = data.payload[0].generation > data.payload[1].generation ? 0 : 1;
var generationId = data.payload[latestResult].generation;
var tickResult = data.payload[latestResult].result;
var lastTick = clientWorlds[clientId].slice(0);
var nextTick = reference.tickBoard(lastTick);
// Validate against reference
// FIXME do some validation
// update reference
clientWorlds[clientId] = nextTick;
}
else if (data.respondingTo === 'tickCell') {
var x = data.payload.x;
var y = data.payload.y;
var from = data.payload.from;
var lives = data.payload.lives;
var shouldLive = reference.tickCell(data.payload.from);
correctClientWorld[getKeyFromXY(x, y)] = (lives == shouldLive);
}
else if (data.action === 'consumeTestResults') {
clientStats.testsRun += data.payload.testsRun;
clientStats.testsFailed += data.payload.testsFailed;
clientStats.testsIgnored += data.payload.testsIgnored;
// Dump the stats to a file for later
var logMsg = new Date().getTime() + ': ' + JSON.stringify(data.payload) + '\n';
fs.exists(statsFile, function (exists) {
if (!exists) {
fs.writeFile(statsFile, '');
}
fs.appendFile(statsFile, logMsg, function (err) {
if (err) {
console.error("Writing to the stats log file failed. This isn't catastrophic, but stats are nice.");
}
});
});
} else {
console.error('Unknown message received:');
console.error(data);
}
} catch (e) {
// Something went wrong, it was probably the input from the client. Crack on!
console.error('Unknown message received:');
console.error(data);
}
}
function tickEverything(generationId) {
// First close off the previous generation (time out anything we haven't received yet)
// Update the UI
io.emit('state', {
correct: readSquareToArray(correctClientWorld, 0,0, width, height),
world: readWorldSquareToArray(0,0, width, height),
clientStats: clientStats
});
// Generate the next generation
var nextTick = [];
// FIXME replace with tickBoard from referenceClient
Object.keys(world).forEach(function (liveCell, index, array) {
var cell = getXYFromKey(liveCell);
// Calculate for every neighbour too
for (var x = -1; x <= 1; x++) {
for (var y = -1; y <= 1; y++) {
var cellX = cell.x-1 + x;
var cellY = cell.y-1 + y;
var binaryString = toBinaryString(readWorldSquareToArray(cellX-1, cellY-1, 3, 3));
if(reference.tickCell(binaryString)) {
nextTick[toIndexOfKey({x:cellX, y:cellY})] = true;
}
}
}
});
world = nextTick;
// The start a new generation
correctClientWorld = [];
var activeClients = Object.keys(clients).filter(function (clientId) { return clientId !== null; });
// Send out tick request for each client's board
activeClients.forEach(function (clientId) {
sendCommand(clientId, 'tickBoard', {
generation: generationId,
result: clientWorlds[clientId]
});
});
// Hash to prevent sending the same cell twice
var sentCells = {};
// Send out tick request for each cell
if(activeClients.length > 0) {
Object.keys(world).forEach(function (liveCell, index, array) {
var cell = getXYFromKey(liveCell);
// Calculate for every neighbour too
for (var x = -1; x <= 1; x++) {
for (var y = -1; y <= 1; y++) {
var cellX = cell.x-1 + x;
var cellY = cell.y-1 + y;
var key = toIndexOfKey({x:cellX, y:cellY});
if (!sentCells[key]) {
sentCells[key] = true;
var binaryString = toBinaryString(readWorldSquareToArray(cellX-1, cellY-1, 3, 3));
sendCommand(activeClients[index % activeClients.length], 'tickCell', {
generation: generationId,
x: cellX,
y: cellY,
result: binaryString
});
}
}
}
});
}
}
function sendCommand(clientId, action, payload) {
var request = {
action: action,
payload: payload
};
clients[clientId].write(JSON.stringify(request) + '\n');
}
io.on('connection', function (socket) {
socket.emit('state', {
correct: readSquareToArray(correctClientWorld, 0,0, width, height),
world: readWorldSquareToArray(0,0, width, height),
clientStats: clientStats
});
socket.on('on', function (data) {
var x = data[0],
y = data[1];
var i = x + (y * width);
if (world[i] !== undefined) {
world[i] = false;
}
});
socket.on('resetWorld', function (data) {
resetWorld();
});
});
// Repeatedly ask for the next generation
setInterval(function () {
generationId++;
tickEverything(generationId);
}, 1000);
http.listen(3000, function () {
console.log('listening on *:3000');
});