-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
625 lines (581 loc) · 14.5 KB
/
app.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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
if(process.env.NODETIME_ACCOUNT_KEY) {
require('nodetime').profile({
accountKey: process.env.NODETIME_ACCOUNT_KEY,
appName: 'sk-node-snake' // optional
})
}
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server)
, fs = require('fs')
, url = require('url')
, path = require('path')
, port = process.env.PORT || 5000
, S = require('string')
, _ = require('underscore')
server.listen(port)
console.log('listening on port ' + port)
io.set('log level', 1)
function serveFile(req, res, filename) {
var rs = fs.createReadStream(path.join(__dirname, filename))
rs.on('error', function (err) {
res.writeHead(500)
res.end('Error loading ' + filename)
})
rs.pipe(res)
}
function index(req, res) {
return serveFile(req, res, 'index.html')
}
app.get('/', index)
app.get('/index.html', index)
app.get('/index.htm', index)
app.get('/jquery/jquery.min.js', function (req, res) {
return serveFile(req, res, path.join('node_modules', 'jquery', 'dist', 'jquery.min.js'))
})
app.get('/jquery/jquery.min.map', function (req, res) {
return serveFile(req, res, path.join('node_modules', 'jquery', 'dist', 'jquery.min.map'))
})
app.get('/style.css', function (req, res) {
return serveFile(req, res, 'style.css')
})
app.get('/jquery/jquery.caret.js', function (req, res) {
return serveFile(req, res, 'jquery.caret.js')
})
Number.prototype.mod = function(n) {
return ((this%n)+n)%n
}
function pointIsEqual(a, b) {
return (a.y == b.y && a.x == b.x)
}
function getRandomInt(max) {
return Math.floor(Math.random() * max)
}
_.extend(Snake.prototype, {
d: 0,
pieces: [],
_newDir: 0,
changed: true,
elongating: 3,
growing: true,
player: null,
board: null,
update: function() {
this.d = this.newDir()
// grow this's head
this.grow()
this.growing = (this.elongating > 0)
// shorten this's tail
if (this.growing) {
this.elongating--
}
else {
this.pieces.pop()
}
},
nearHead: function() {
var head = this.pieces[0]
return [
{ y: (head.y + 1).mod(this.board.height), x: head.x },
{ y: (head.y - 1).mod(this.board.height), x: head.x },
{ y: head.y, x: (head.x + 1).mod(this.board.width) },
{ y: head.y, x: (head.x - 1).mod(this.board.width) }
]
},
died: function() {
this.player.snakeDied()
},
forUpdate: function() {
return {
head: this.pieces[0],
grow: this.growing
}
},
forCreate: function() {
return {
pieces: this.pieces,
}
},
roundDirection: function(dir) {
return (Math.round(dir / 90) * 90).mod(360)
},
newDir: function(dir) {
if (dir != undefined) {
var newDir = this.roundDirection(dir)
// either 0, 90, 180, or 270
if([0, 90, 180, 270].indexOf(newDir) == -1) return
// not a reversal
if(newDir == (this.d + 180).mod(360)) return
this._newDir = newDir
}
return this._newDir
},
grow: function() {
var next = this.nextPiece(this.d)
if (next) {
this.pieces.unshift(next)
next.changed = true
}
},
nextPiece: function(dir) {
dir = this.roundDirection(dir)
var head = this.pieces[0]
if (dir === 0)
return {x: (head.x + 1).mod(this.board.width), y: head.y}
else if(dir === 90)
return {x: head.x, y: (head.y - 1).mod(this.board.height)}
else if(dir === 180)
return {x: (head.x - 1).mod(this.board.width), y: head.y}
else if(dir === 270)
return {x: head.x, y: (head.y + 1).mod(this.board.height)}
}
})
function Snake(board, player, pos) {
if (player.snake) return
var snake = this
var snakeTail = pos
this.pieces = [{
x: snakeTail.x,
y: snakeTail.y,
changed: true
}]
this.player = player
this.board = board
player.snake = this
board.numSnakes++
this.d = snakeTail.d
this.newDir(snakeTail.d)
}
_.extend(Player.prototype, {
name: null,
id: null,
board: null,
kills: null,
deaths: null,
afterUpdate: function() {
/* do nothing */
},
name: function() {
if (arguments[0]) {
this._name = arguments[0]
io.sockets.emit('renamed', {
id: this.id,
name: this._name
})
}
return this._name
},
spawnSnake: function() {
this.snake = new Snake(this.board, this, this.board.newTail())
var newSnakes = {}
newSnakes[this.id] = this.snake.forCreate()
io.sockets.emit('create', {
snakes: newSnakes
})
},
snakeDied: function() {
if(!this.snake) {
return
}
var message
var kid = this.snake.killer
killer = this.board.players[kid]
if (kid != undefined && kid != this.id) {
message = {id: this.id, killer: kid}
killer.kills++
if (killer.snake) {
killer.snake.elongating += 1
}
}
else {
message = {id: this.id}
}
this.snake.deaths++
io.sockets.emit('die', message)
delete this.board.players[this.id].snake
delete this.snake
this.board.numSnakes--
return message
},
connect: function() {
this.name(this._name)
io.sockets.emit('joined', {id: this.id})
this.spawnSnake()
return this
},
disconnected: function () {
io.sockets.emit('left', {id: this.id})
if (this.snake) {
this.board.numSnakes--
}
delete this.board.players[this.id]
}
})
function Player (board) {
this.board = board
this.id = this.board.maxID++
this.kills = 0
this._name = 'Bot ' + this.id
this.board.players[this.id] = this
}
_.extend(AIPlayer.prototype, Player.prototype, {
afterUpdate: function() {
this._unsafe = null
if (!this.snake) {
this.spawnSnake()
return
}
// pick a random direction
var prospect = this.newDir || 0
if (!getRandomInt(3)) {
prospect = this.snake.roundDirection(getRandomInt(360))
}
// get fruit if it's adjacent
var change = 0
while (change < 360 &&
!this.board.hasFruit(this.snake.nextPiece(prospect + change))) {
change += 90
}
prospect += change
// keep turning until safe or back at the start
change = 0
while (change < 360 &&
!this.isSafe(this.snake.nextPiece(prospect + change))) {
change += 90
}
prospect += change
// go in the chosen direction
this.snake.newDir(prospect)
},
isSafe: function(piece) {
this._unsafe = this._unsafe || this.board.headAreasOfOtherSnakes(this.id)
return this.board.isSafe(piece) && _.some(this._unsafe, function(other_piece) {
if (!other_piece) {
return false
}
return pointIsEqual(piece, other_piece)
})
}
})
function AIPlayer (board) {
Player.apply(this, arguments)
}
_.extend(AUPlayer.prototype, Player.prototype, {
afterUpdate: function() {
if (!this.snake) {
this.spawnSnake()
return
}
if (getRandomInt(2)) {
this.snake.newDir(getRandomInt(360))
}
}
})
function AUPlayer (board) {
Player.apply(this, arguments)
}
_.extend(HumanPlayer.prototype, Player.prototype, {
socket: null,
spawnSnake: function() {
Player.prototype.spawnSnake.apply(this, arguments)
this.socket.emit('spawn', {
id: this.id
})
},
connect: function() {
this.socket.emit('accept', {
id: this.id,
width: this.board.width,
height: this.board.height
})
this.socket.emit('create', {
snakes: this.board.snakesForCreate(),
fruit: this.board.fruit,
names: this.board.allNames()
})
var that = this
this.socket.on('name', function(params) {
that._name = params['name']
Player.prototype.connect.apply(that, arguments)
})
this
}
})
function HumanPlayer (board, socket) {
Player.apply(this, arguments)
this.socket = socket
this._name = 'Player ' + this.id
// register player to receive messages
var player = this
this.socket.on('turn', function (params) {
if (!player.snake) {
return
}
player.snake.newDir(Number(params['d']))
})
this.socket.on('respawn', function (params) {
if(player.snake || player.name() === undefined) return
player.spawnSnake()
})
this.socket.on('disconnect', function (params) {
player.disconnected()
console.log(player.socket.handshake.address.address + ' disconnected')
})
this.socket.on('rename', function (params) {
player.name(params['name'])
})
this.socket.on('msg', function (params) {
io.sockets.emit('msged', { id: player.id, m: S(params['m']).escapeHTML().s })
})
}
function Board(w, h) {
// properties
var board = this
this.players = {}
this.width = w
this.height = h
this.maxID = 0
this.numSnakes = 0
this.fruit = []
// methods
this.hasFruit = function(piece) {
return _.some(board.fruit, function(fruit) {
return pointIsEqual(piece, fruit)
})
}
this.headAreasOfOtherSnakes = function(skip_id) {
var unsafe = []
for (pid in board.players) {
var snake = board.players[pid].snake
if (!snake || pid === skip_id) {
continue
}
unsafe = unsafe.concat(snake.nearHead())
}
return unsafe
}
this.invalidateSafety = function() {
board._safeSpaces = null
board._safeGrid = null
}
this._safeSpaces
this.safeSpaces = function() {
if (board._safeSpaces) {
return board._safeSpaces
}
var grid = board.safeGrid()
board._safeSpaces = []
// retrieve safe spaces
for (var x = 0; x < board.width; x++) {
for (var y = 0; y < board.height; y++) {
if (grid[x][y]) {
board._safeSpaces.push({
x: x,
y: y
})
}
}
}
return board._safeSpaces
}
this._safeGrid
this.safeGrid = function() {
if (board._safeGrid) {
return board._safeGrid
}
// find unsafe spaces
var unsafe = []
for (pid in board.players) {
var snake = board.players[pid].snake
if (!snake) {
continue
}
unsafe = unsafe.concat(snake.pieces)
}
// init board._safeGrid
board._safeGrid = new Array(board.width)
for (var x = 0; x < board.width; x++) {
board._safeGrid[x] = new Array(board.height)
for (var y = 0; y < board.height; y++) {
board._safeGrid[x][y] = true
}
}
// mark unsafe spaces in board._safeGrid
for (var i = 0; i < unsafe.length; i++) {
var u = unsafe[i]
board._safeGrid[u.x][u.y] = false
}
return board._safeGrid
}
this.getSafeSpace = function() {
var safeSpaces = board.safeSpaces()
if (!safeSpaces || safeSpaces.length == 0) {
return {
x: getRandomInt(board.width),
y: getRandomInt(board.height),
}
}
else {
return safeSpaces[getRandomInt(safeSpaces.length)]
}
}
this.isSafe = function(point) {
if (!point ||
point.x >= board.width || point.x < 0 ||
point.y >= board.height || point.y < 0 ||
!board.safeGrid()[point.x][point.y]) {
return false
}
return true
}
this.allNames = function() {
var names = {}
for (var pid in board.players) {
names[pid] = board.players[pid].name()
}
return names
}
this.snakesForCreate = function() {
var snakes = {}
for (var pid in board.players) {
var snake = board.players[pid].snake
if(snake) {
snakes[pid] = snake.forCreate()
}
}
return snakes
}
this.snakesForUpdate = function() {
var changed = {}
for (var pid in board.players) {
var snake = board.players[pid].snake
if(snake) {
changed[pid] = snake.forUpdate()
}
}
return changed
}
this.newTail = function() {
var safe = board.getSafeSpace()
var ret =
{
x: safe.x,
y: safe.y,
d: 0
}
return ret
}
this.newHumanPlayer = function(socket) {
return new HumanPlayer(board, socket)
}
this.newAIPlayer = function() {
return new AIPlayer(board)
}
this.newAUPlayer = function() {
return new AUPlayer(board)
}
this.beforeUpdate = function() {}
this.update = function() {
// invalidate safe spawning spaces
board.invalidateSafety()
board.updatePosition()
board.collision()
io.sockets.emit('update', {
snakes: board.snakesForUpdate(),
fruit: board.fruit
})
}
this.afterUpdate = function() {
for (var pid in board.players) {
board.players[pid].afterUpdate()
}
}
// fruit spawning
this.spawnFruitInterval = function() { return 4000 / Math.sqrt(board.numSnakes + 1) }
this.spawnFruit = function() {
if (board.fruit.length < 2 * board.numSnakes) {
board.fruit.push(board.getSafeSpace())
}
board.setFruitTimeout()
}
this.setFruitTimeout = function() {
setTimeout(function() {
board.spawnFruit()
}, board.spawnFruitInterval())
}
// logic
this.updatePosition = function() {
for (var pid in board.players) {
var snake = board.players[pid].snake
if (snake) {
snake.update()
}
}
}
this.collision = function() {
// collision
for (var pid1 in board.players) {
var snake1 = board.players[pid1].snake
if (!snake1) {
continue
}
// collide fruit with heads
for (var i = 0; i < board.fruit.length; i++) {
if (pointIsEqual(snake1.pieces[0], board.fruit[i])) {
snake1.elongating += 1
board.fruit.splice(i, 1)
}
}
for (var pid2 in board.players) {
var snake2 = board.players[pid2].snake
if (!snake2) {
continue
}
// collide bodies with heads
pieces2 = snake2.pieces.slice(1)
for (var i = 0; i < pieces2.length; i++) {
if (pointIsEqual(snake1.pieces[0], pieces2[i])) {
snake1.dead = true
snake1.killer = pid2
}
}
// stop a snake colliding with its own head
if (pid1 == pid2) {
continue
}
// collide heads with heads
if (pointIsEqual(snake1.pieces[0], snake2.pieces[0])) {
snake1.dead = true
snake1.killer = pid2
}
}
}
// postcollision
for (var pid in board.players) {
var snake = board.players[pid].snake
if (snake && snake.dead) {
snake.died()
}
}
}
// fruit loop
this.setFruitTimeout()
// main loop
var tick = 300
setInterval(function () {
board.beforeUpdate()
board.update()
board.afterUpdate()
}, tick)
}
var board = new Board(40, 40)
io.sockets.on('connection', function (socket) {
console.log(socket.handshake.address.address + ' connected')
board.newHumanPlayer(socket).connect()
})
for(var i = 0; i < 6; i++) {
board.newAIPlayer().connect()
}
for(var i = 0; i < 2; i++) {
board.newAUPlayer().connect()
}