forked from BenjaminPoilve/TankWarz
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
540 lines (466 loc) · 16.1 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
'use strict';
var ws = require("ws")
var elo = require('elo-rank')();
var redis = require('redis');
var bodyParser = require('body-parser')
var async = require("async");
var express = require('express');
var http = require('http');
var app = express();
var uuid = require('node-uuid');
var quickGist = require('quick-gist');
var client = redis.createClient(6379, "127.0.0.1");
client.select(3, function() { /* ... */ });
var maxFrame=1000;
var currentFrame=0;
var port = process.env.PORT || 4242;
var origin = process.env.SERVER_ORIGIN || "http://localhost:${port}";
console.log("Origin", origin);
app.use('/', express.static('public'));
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', origin);
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'POST');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
next();
});
app.use( bodyParser.json() );
const BOTS_COUNT = 4
app.post('/newbot', function (req, res) {
console.log(req.body);
var name=req.body.name;
var code=req.body.value;
var uuidBot=uuid.v4();
var botDescriptor={
name:name,
code: code,
score:100
}
client.hset("botList", uuidBot, JSON.stringify(botDescriptor) , redis.print);
/*quickGist({
content: code,
description: 'This is the ai code for the bot '+ name+' and uuid '+uuidBot+'. Check its performances at www.tankwar.seed-up.orgs', // Optional
public: true, // Whether the gist should be public or unlisted. Defaults to false (unlisted).
enterpriseOnly: false, // Prohibit posting to GitHub.com. Defaults to false. Useful if you're posting company secrets.
fileExtension: 'js' // Optionally force a file extension if you don't want to rely on language-classifier.
}, function(err, resp, data) {
console.log(data);
});*/
});
var width=30;
var height=30;
var score=[];
var WebSocket = require('ws');
var server = http.createServer(app);
var wss = new WebSocket.Server({server});
// Broadcast to all.
wss.broadcast = function broadcast(data) {
wss.clients.forEach(function each(client) {
if (client.readyState === WebSocket.OPEN) {
client.send(data);
}
});
};
wss.on('connection', function connection(connection) {
console.log("ws: new client");
connection.on("close", function () {
console.log("ws: close client");
});
});
function compareBot(a, b) {
if (a.dead && b.dead) {
return 0;
} else {
if (a.dead)
return 1;
if (b.dead)
return -1;
return a.bullets < b.bullets
}
}
class Bot {
constructor(xpos, ypos, bullets, name, value,score,uuid) {
this.xpos = xpos;
this.ypos = ypos;
this.name = name;
this.history = [];
this.elo=score;
this.value=value;
console.log("bot uuid",uuid);
this.uuid=uuid;
this.process=require('child_process').fork('child.js');
this.process.send({ data: { action: "code", code: value } });
this.id = Math.random().toString(36).substr(2, 10);;
this.bullets = bullets;
this.dead = false;
this.orientation = "UP";
this.process.on('message', (obj) => {
if (this.dead)
return;
clearTimeout(this.timeout);
var data = obj.data;
if (data.action === "result") {
this.tickCB(null, data.argument);
}
if (data.action === "error") {
// TODO: Do something with error
this.dead = true;
this.tickCB(null, "NOP");
}
});
}
toJSON() {
return {
xpos: this.xpos,
ypos: this.ypos,
name: this.name,
orientation: this.orientation,
elo: this.elo,
dead: this.dead,
bullet: this.bullets
}
}
tick(arg, cb) {
//console.log("I'm ticking");
if (this.dead) {
return cb(null, "NOP");
}
this.tickCB = cb;
this.process.send({ data: { action: "execute", argument:arg } });
this.timeout = setTimeout(() => {
this.dead = true;
this.elo=0;
this.kill();
this.tickCB(null, "NOP");
}, 500);
}
remainingBullet() {
var value = this.bullets;
this.bullets -= 1;
return value;
}
getX() {
return this.xpos;
}
getY() {
return this.ypos;
}
getOrientation() {
return this.orientation;
}
move(direction, array) {
this.orientation = direction
if (direction == "UP") {
if (array.every((element, index, array) => {
return Math.abs(element.xpos - this.xpos) > 1 || Math.abs(element.ypos - this.ypos + 1) > 1 || element.id == this.id;
})) {
this.ypos -= 1;
}
}
if (direction == "DOWN") {
if (array.every((element, index, array) => {
return Math.abs(element.xpos - this.xpos) > 1 || Math.abs(element.ypos - this.ypos - 1) > 1 || element.id == this.id;
})) {
this.ypos += 1;
}
}
if (direction == "RIGHT") {
if (array.every((element, index, array) => {
return Math.abs(element.xpos - this.xpos - 1) > 1 || Math.abs(element.ypos - this.ypos) > 1 || element.id == this.id;
})) {
this.xpos += 1;
}
}
if (direction == "LEFT") {
if (array.every((element, index, array) => {
return Math.abs(element.xpos - this.xpos + 1) > 1 || Math.abs(element.ypos - this.ypos) > 1 || element.id == this.id;
})) {
this.xpos -= 1;
}
}
}
setPos(x, y) {
this.xpos = x;
this.ypos = y;
}
getPos() {
return [this.xpos, this.ypos];
}
kill() {
//https://nodejs.org/api/child_process.html#child_process_child_kill_signal
this.process.kill();
//window.URL.revokeObjectURL(this.url);
}
}
class Bullet {
constructor(xpos, ypos, direction, id) {
this.xpos = xpos;
this.ypos = ypos;
this.direction = direction;
this.id = id
}
getPos() {
return [this.xpos, this.ypos];
}
tick() {
if (this.direction == 'UP' && this.ypos > 0) {
this.ypos -= 1;
return true;
} else if (this.direction == 'DOWN' && this.ypos < height) {
this.ypos += 1;
return true;
} else if (this.direction == 'RIGHT' && this.xpos < width) {
this.xpos += 1;
return true;
} else if (this.direction == 'LEFT' && this.xpos > 0) {
this.xpos -= 1;
return true;
} else {
return false;
}
}
}
//RUN GAME
function initGame(bulletNum) {
score=[];
console.log("hey");
currentFrame=0;
client.hgetall("botList", function (err, obj) {
console.log("hey 2");
Object.keys(obj).forEach(function(key,index) {
var element=JSON.parse(obj[key]);
var object={
name:(element).name,
elo:(element).score
}
score.push(object)
});
console.log("hey 3");
score.sort(function(a,b) {return (a.elo < b.elo) ? 1 : ((b.elo < a.elo) ? -1 : 0);} );
client.hkeys("botList", function (err, replies) {
var arr = []
console.log("hey 4");
while(arr.length < BOTS_COUNT){
var randomnumber=Math.ceil(Math.random()*replies.length)-1
var found=false;
for(var i=0;i<arr.length;i++){
if(arr[i]==replies[randomnumber]){
found=true;break}
}
if(!found){
arr[arr.length]=replies[randomnumber];
}
}
console.log("hey 5");
console.log("selected")
async.map(arr, function(index, cb) {
client.hget("botList",index,cb)
}, function(err, array) {
console.log("return",array);
var game= [array.map((v, index) => new Bot((Math.floor(Math.random() * width)), (Math.floor(Math.random() * height)), bulletNum, JSON.parse(v).name, JSON.parse(v).code,JSON.parse(v).score,(arr[index]))), []];
wss.broadcast(JSON.stringify({status:"high-score", bot:score}))
setTimeout(function() {
runTick(game[0], game[1]);
}, 1000 );
});
});
});
}
function moveMissile(bulletArray) {
var returnArray = []
bulletArray.forEach(
function(element) {
if (element.tick()) {
returnArray.push(element)
}
}
)
return returnArray
}
function arraysEqual(a, b) {
if (a === b) return true;
if (a == null || b == null) return false;
if (a.length != b.length) return false;
for (var i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) return false;
}
return true;
}
function missileCollison(bulletArray, botArray) {
var returnBotArray = botArray.slice();
var returnBulletArray = bulletArray.slice();
for (var a = 0; a < bulletArray.length; a++) {
for (var b = 0; b < botArray.length; b++) {
if (arraysEqual(bulletArray[a].getPos(), botArray[b].getPos()) && bulletArray[a].id != botArray[b].id) {
returnBotArray[b].dead = true;
returnBotArray[b].kill();
returnBulletArray.splice(a, 1);
}
}
}
return [returnBotArray, returnBulletArray]
}
function constructArgs(element, botArrayUpdated, bulletArrayUpdated) {
var args = {
Missiles: [],
Ennemies: [],
Data: {
BULLETS: element.bullets,
X: element.xpos,
Y: element.ypos,
HISTORY: element.history
}
}
bulletArrayUpdated.forEach(
function(bullet) {
if (bullet.id != element.id) {
args.Missiles.push({
X: bullet.xpos,
Y: bullet.ypos,
DIR: bullet.direction
});
}
}
)
botArrayUpdated.forEach(
function(bot) {
if (bot.id != element.id) {
args.Ennemies.push({
X: bot.xpos,
Y: bot.ypos,
HISTORY: bot.history,
DEAD: bot.dead
});
}
});
return args;
}
function runTick(botArray, bulletArray) {
//console.log("Ticking")
//DO IT multiple time for speed
var bulletArrayUpdated, botArrayUpdated, positionArray;
if (bulletArray.length > 0) {
bulletArrayUpdated = moveMissile(bulletArray)
var data = missileCollison(bulletArrayUpdated, botArray)
bulletArrayUpdated = data[1];
botArrayUpdated = data[0];
} else {
bulletArrayUpdated = bulletArray;
botArrayUpdated = botArray;
}
positionArray = []
botArrayUpdated.forEach(
function(element) {
positionArray.push();
}
)
async.map(botArrayUpdated, function(v, cb) {
v.tick(constructArgs(v, botArrayUpdated, bulletArrayUpdated), cb);
}, function(err, arr) {
//console.log(arr)
//passer à travaers arr et updated si authorisé!
for (var i = 0; i < arr.length; i++) {
if (botArrayUpdated[i].dead == false) {
botArrayUpdated[i].history.unshift(arr[i])
var length = botArrayUpdated[i].history.length;
botArrayUpdated[i].history.splice(10, length - 10);
if (arr[i] == "SHOOT") {
if (botArrayUpdated[i].bullets >0) {
botArrayUpdated[i].bullets-=1;
bulletArrayUpdated.push(new Bullet(botArrayUpdated[i].getX(), botArrayUpdated[i].getY(), botArrayUpdated[i].getOrientation(), botArrayUpdated[i].id))
}
}
if (arr[i] == "DOWN") {
if (botArrayUpdated[i].ypos < height - 1) {
botArrayUpdated[i].move(arr[i], botArrayUpdated)
}
}
if (arr[i] == "UP") {
if (botArrayUpdated[i].ypos > 0) {
botArrayUpdated[i].move(arr[i], botArrayUpdated)
}
}
if (arr[i] == "RIGHT") {
if (botArrayUpdated[i].xpos < width - 1) {
botArrayUpdated[i].move(arr[i], botArrayUpdated)
}
}
if (arr[i] == "LEFT") {
if (botArrayUpdated[i].xpos > 0) {
botArrayUpdated[i].move(arr[i], botArrayUpdated)
}
}
}
}
data = missileCollison(bulletArrayUpdated, botArrayUpdated)
bulletArrayUpdated = data[1];
botArrayUpdated = data[0];
bulletArrayUpdated = moveMissile(bulletArrayUpdated)
data = missileCollison(bulletArrayUpdated, botArrayUpdated)
bulletArrayUpdated = data[1];
botArrayUpdated = data[0];
var BulletsLeft = 0;
var ContestantLeft = 0;
botArrayUpdated.sort(compareBot)
botArrayUpdated.forEach(
function(element) {
if(!element.dead){
BulletsLeft+=element.bullets
ContestantLeft+=1;
}
}
)
//console.log(botArrayUpdated);
currentFrame+=1;
wss.broadcast(JSON.stringify({status:"ongoing", botArray: botArrayUpdated.map(v => v.toJSON()), bulletArray: bulletArrayUpdated }));
if (BulletsLeft > 0 && ContestantLeft > 1 && currentFrame<maxFrame) {
setTimeout(function() {
runTick(botArrayUpdated, bulletArrayUpdated);
}, 1000 / 15);
}else{
console.log("game over");
wss.broadcast(JSON.stringify({status:"over"}));
if(botArrayUpdated[0].bullets!=botArrayUpdated[1].bullets){
var winnerElo=botArrayUpdated[0].elo;
var loserElo=Math.max.apply(Math,botArrayUpdated.slice(1).map(function(o){return o.elo;}))
var maxElo=Math.max.apply(Math,botArrayUpdated.map(function(o){return o.elo;}))
botArrayUpdated[0].elo=elo.updateRating(elo.getExpected(winnerElo, loserElo), 1, winnerElo);
var botDescriptor={
name:botArrayUpdated[0].name,
code: botArrayUpdated[0].value,
score:botArrayUpdated[0].elo
}
client.hset("botList", botArrayUpdated[0].uuid, JSON.stringify(botDescriptor) , redis.print);
for (var i=1;i<BOTS_COUNT;i++){
botArrayUpdated[i].elo=parseInt((elo.updateRating(elo.getExpected(botArrayUpdated[i].elo, maxElo), 0, botArrayUpdated[i].elo)-botArrayUpdated[i].elo)/(BOTS_COUNT - 1))+botArrayUpdated[i].elo;
var botDescriptor={
name:botArrayUpdated[i].name,
code: botArrayUpdated[i].value,
score:botArrayUpdated[i].elo
}
client.hset("botList", botArrayUpdated[i].uuid, JSON.stringify(botDescriptor) , redis.print);
}
score.push({name:botArrayUpdated[0].name,score:botArrayUpdated[0].bullets})
}
initGame( 100);
}
})
}
var x = `function main(arg){
console.log(arg);
action=["LEFT","RIGHT","UP","DOWN","SHOOT"];
var result=action[Math.floor(Math.random() *5)];
return result;
}`
//TEST
client.on("error", function (err) {
console.log("Redis: Error " + err);
});
client.on('connect', function() {
server.listen(port, function () {
console.log('Example app listening on port', port);
});
initGame(100);
});