-
Notifications
You must be signed in to change notification settings - Fork 4
/
game.js
executable file
·654 lines (592 loc) · 20.8 KB
/
game.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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
#!/usr/bin/env node
/*
Copyright (C) 2012 Juan Lasheras (http://www.juanl.org).
This file is part of Quirky.
Quirky is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Quirky is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Quirky. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @fileoverview Quirky node server
* @author [email protected] (Juan Lasheras)
*/
(function () {
"use strict";
}());
var http = require('http');
var url = require('url');
var querystring = require('querystring');
var fs = require('fs');
var cookies = require('./node_modules/cookies');
var static_files = {
'index.html': fs.readFileSync('index.html'),
'game-client.js': fs.readFileSync('game-client.js'),
'layout.css': fs.readFileSync('layout.css'),
'color.css': fs.readFileSync('color.css'),
'typography.css': fs.readFileSync('typography.css'),
'normalize.css': fs.readFileSync('thirdparty/normalize.css'),
'jquery.min.js': fs.readFileSync('thirdparty/jquery.min.js'),
'jquery-ui.min.js': fs.readFileSync('thirdparty/jquery-ui.min.js'),
'jquery.cookie.js': fs.readFileSync('thirdparty/jquery.cookie.js'),
'light_noise_diagonal.png': fs.readFileSync("media/light_noise_diagonal.png"),
'wood.png': fs.readFileSync("media/dark_wood.png")
};
var CHATLINES = 1000; // number of lines to store from chats
function Game(name) {
this.name = name;
this.board = []; // list representation
this.boardmat = []; // matrix representation
for (var i=0; i<181; i++) {
this.boardmat[i] = new Array(181);
}
this.players = {};
this.turn_pieces = []; // pieces played this turn
this.chat = []; // chat log
// board dimensions
this.dimensions = {'top': 90, 'right': 90, 'bottom': 90, 'left': 90};
/* Keep track of the pieces by having a list of piece objects each with a
* count attribute that tracks how many of that piece are left. When this
* reaches 0, we remove the piece object from the list.
*/
this.pieces = [];
var colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'];
var shapes = ['circle', 'star', 'diamond', 'square', 'triangle', 'clover'];
for (var c in colors) {
if (!colors.hasOwnProperty(c)) {
continue;
}
for (var s in shapes) {
if (!shapes.hasOwnProperty(s)) {
continue;
}
this.pieces.push({'piece': new Piece(shapes[s], colors[c]), 'count': 3});
}
}
}
Game.prototype.toJSON = function() {
return {'name': this.name, 'players': this.players};
};
/**
* Draw some number of random pieces from the game stash.
* @param num: {number} number of pieces to draw
*/
Game.prototype.drawPieces = function(num) {
// draw num pieces from the pile
var draw = [];
while (draw.length < num && this.pieces.length > 0) {
var r = Math.floor(Math.random() * this.pieces.length);
var p = this.pieces[r].piece;
draw.push(new Piece(p.shape, p.color));
if ((this.pieces[r].count -= 1) < 1) {
this.pieces.splice(r, 1);
}
}
return draw;
};
/**
* Return a list of pieces to the game.
* @param pieces: {array} of Piece objects
*/
Game.prototype.returnPieces = function(pieces) {
for (var p in pieces) {
if (!pieces.hasOwnProperty(p)) {
continue;
}
var piece = pieces[p];
var found = this.pieces.some(function(x) {
if (piece.equals(x.piece)) {
x.count += 1;
return true;
}
});
if (!found) { // first piece of its kind
this.pieces.push({'piece': new Piece(piece.shape, piece.color),
'count': 1});
}
}
};
function Player (name) {
this.name = name;
this.pieces = [];
this.points = 0;
this.has_turn = false;
}
function Piece (shape, color) {
this.shape = shape;
this.color = color;
this.equals = function(x) {
return (this.shape === x.shape && this.color === x.color);
};
}
function GamePiece (piece, row, column) {
this.piece = piece;
this.row = row;
this.column = column;
this.equals = function(x) {
return (this.column === x.column && this.row === x.row &&
this.piece.equals(x.piece));
};
}
// typical response helper
function respOk (response, data, type) {
if (type) {
headers = {'Content-Type': type};
}
response.writeHead(200, headers);
if (data) {
response.write(data, 'utf-8');
}
response.end();
}
/**
* Add a game piece to the board, check that:
* 1. game piece doesn't already exist
* 2. game piece is not adjacent to non-compatible piece
* return: integer of points if Success, otherwise return an error string
*/
function addGamePiece(game, gamepiece) {
var row = gamepiece.row;
var col = gamepiece.column;
var points = 0;
if (game.boardmat[row][col] !== undefined) {
return "GamePiece already exists.";
}
/**
* Helper function, to check whether it is valid to place a piece
* param piece: the piece object being placed
* param getAdjacent: a function that returns an adjacent GamePiece
* return: false if valid placement, otherwise return the offending GamePiece
*/
function _adjacentPieces(piece, getAdjacent) {
for (var i=1; i<=6; i++) {
adjacent = getAdjacent(i);
if (typeof adjacent === 'undefined') {
return false;
} else if (i === 6) { // can't have more than 6 pieces in a valid line
return adjacent;
}
var samecolor = (adjacent.piece.color === piece.color);
var sameshape = (adjacent.piece.shape === piece.shape);
// console.log('piece: ' + piece.color + ' ' + piece.shape +
// ', adjacent: ' + adjacent.piece.color + ' ' +
// adjacent.piece.shape);
// either samecolor or sameshape, not both
if ((samecolor || sameshape) && !(samecolor && sameshape)) {
// add a point for adjacent piece, if not been played this turn
if (!game.turn_pieces.some(function(x) {
return x.equals(adjacent);})) {
points += 1;
}
continue;
}
return adjacent;
}
return false;
}
// check if adjacent pieces are compatible
var checkLeft = _adjacentPieces(gamepiece.piece, function(offset) {
var _row = row-offset;
var piece = game.boardmat[_row][col];
return piece && new GamePiece(piece, _row, col);
});
var checkRight =_adjacentPieces(gamepiece.piece, function(offset) {
var _row = row+offset;
var piece = game.boardmat[_row][col];
return piece && new GamePiece(piece, _row, col);
});
var checkUp =_adjacentPieces(gamepiece.piece, function(offset) {
var _col = col-offset;
var piece = game.boardmat[row][_col];
return piece && new GamePiece(piece, row, _col);
});
var checkDown =_adjacentPieces(gamepiece.piece, function(offset) {
var _col = col+offset;
var piece = game.boardmat[row][_col];
return piece && new GamePiece(piece, row, _col);
});
var badPiece = (checkLeft || checkRight || checkUp || checkDown);
if (badPiece !== false) {
return ("GamePiece adjacent to incompatible piece: " +
badPiece.piece.color + " " + badPiece.piece.shape);
}
// check if piece played in same row or column as past pieces this turn}
function sameRowOrCol(otherpiece) {
return (otherpiece.row === row || otherpiece.column === col);
}
if (game.turn_pieces) {
if (!game.turn_pieces.every(sameRowOrCol)) {
return ("GamePiece must be in same row or column as others " +
"placed this turn.");
}
}
game.turn_pieces.push(gamepiece);
game.boardmat[row][col] = gamepiece.piece;
game.board.push(gamepiece);
// update board dimensions
var dim = game.dimensions;
if (col < dim.left) {
dim.left = col;
} else if (col > dim.right) {
dim.right = col;
}
if (row < dim.top) {
dim.top = row;
} else if (row > dim.bottom) {
dim.bottom = row;
}
// debug logging, print out boardmat
// for (var i=dim.top; i<=dim.bottom; i++) {
// for (var j=dim.left; j<=dim.right; j++) {
// var piecestr = (typeof game.boardmat[i][j] == "undefined") ? " ":
// game.boardmat[i][j];
// process.stdout.write('['+piecestr+']');
// }
// console.log('');
// }
return points+1; // get one point for placing a piece
}
// find player from request cookie
function playerFromReq(request, response, game) {
var jar = new cookies(request, response);
var p = decodeURIComponent(jar.get('player'));
return game.players[p];
}
// extract data from query string
function requestQuery(request) {
return querystring.parse(url.parse(request.url).query);
}
// extract data from request body and pass to onEnd functon
function requestBody(request, onEnd) {
var fullBody = '';
request.on('data', function(d) {
fullBody += d.toString();
});
request.on('end', function() {
onEnd(querystring.parse(fullBody));
});
}
/**
* Pass the turn to the next player,
* @param game: {obj} game object
* @param player: {obj} player object
*/
function nextTurn(game, player) {
if (player.has_turn === false) { // we assume that player has the turn
return;
}
player.has_turn = false;
// give next player the turn
var _players = Object.keys(game.players);
var next_idx = (_players.indexOf(player.name) + 1) %
_players.length;
var next = game.players[_players[next_idx]];
next.has_turn = true;
// next player draws new pieces
next.pieces = next.pieces.concat(game.drawPieces(
6 - next.pieces.length));
}
/**
* End the turn for the player and start for the next.
* @param {obj} player: the player whose turn will end
*/
function switchPlayers(game, player) {
// clear pieces played this turn
game.turn_pieces = [];
nextTurn(game, player);
}
/**
* Create and add a player to a game.
* @param game: {obj} game object
* @param playernm: {str} player name
*/
function addPlayerToGame(game, playernm) {
var p = new Player(playernm);
p.pieces = game.drawPieces(6);
game.players[p.name] = p;
// if first player, make it his turn
if (Object.keys(game.players).length === 1) {
p.has_turn = true;
}
}
/**
* Handle a player resource transaction.
* - POST to add player to the game.
* - GET player pieces
*/
function handlePlayers(request, response, game, path) {
var func, player, resp;
if (!path.length) {
// return info on the players collection
if (request.method === "POST") {
player = playerFromReq(request, response, game);
if (player) {
// end turn
// TODO should this be under /players/<name>/?
func = function (form) {
if (form && form.end_turn) {
switchPlayers(game, player);
respOk(response);
}
};
} else {
// add player to a game
func = function(form) {
if (form && form.name) {
addPlayerToGame(game, form.name);
var jar = new cookies(request, response);
jar.set("player", encodeURIComponent(form.name),
{httpOnly: false});
respOk(response, '', 'text/json');
}
};
}
requestBody(request, func);
return;
} else if (request.method === 'DELETE') {
// delete player from a game
func = function(form) {
if (form && form.name) {
player = game.players[form.name];
if (player === undefined) {
// huh? player is not in this game
response.writeHead(404, {'Content-Type': 'text/json'});
response.end();
return;
}
nextTurn(game, player);
game.returnPieces(player.pieces);
delete game.players[form.name];
if (Object.keys(game.players).length === 0) {
delete games[game.name];
}
respOk(response);
}
};
requestBody(request, func);
return;
} else {
resp = JSON.stringify(game.players);
}
} else {
// return info on a specific player
player = game.players[path[0]];
if (typeof player === 'undefined') {
// player not found
response.writeHead(404, {'Content-Type': 'text/json'});
response.end();
return;
}
if (path[1] === 'pieces') {
resp = JSON.stringify(player.pieces);
}
}
respOk(response, resp, 'text/json');
}
/**
* Handle a game resource transaction.
* - POST to add piece to the board.
* - Forward player transactions to separate function.
* - GET pieces on board & in bag
* - GET dimensions
*/
function handleGame(request, response, game, path) {
var resp;
switch(path[0]) {
case 'board':
// add pieces to the board
if (request.method === "POST") {
requestBody(request, function(form) {
var player = playerFromReq(request, response, game);
// console.info('adding pieces, player:'+player.name);
// console.info('form info:'+JSON.stringify(form));
if (form && form.shape && form.color &&
form.row && form.column && player) {
// TODO should do form check?
var row = parseInt(form.row, 10);
var column = parseInt(form.column, 10);
var piece = new Piece(form.shape, form.color);
// check player has piece
var idx = -1, _idx = 0;
for (var p in player.pieces) {
var _piece = player.pieces[p];
//console.log('check:'+JSON.stringify(p)+', and:'+
// JSON.stringify(piece));
if (piece.equals(_piece)) {
idx = _idx;
break;
}
_idx += 1;
}
if (idx > -1) {
var gp = new GamePiece(piece, row, column);
// console.info('adding piece:'+JSON.stringify(gp));
resp = addGamePiece(game, gp);
if (typeof resp === "string") {
// add gamepiece failed
response.writeHead(409, {'Content-Type': 'text/json'});
response.write(resp, 'utf-8');
response.end();
return;
} else {
// add gamepiece succeeded
player.points += resp;
player.pieces.splice(idx, 1);
respOk(response, '', 'text/json');
}
}
}
});
return;
}
// get pieces on the board
resp = JSON.stringify(game.board);
break;
case 'players':
handlePlayers(request, response, game, path.slice(1));
return;
case 'pieces':
// get pieces in the bag
resp = JSON.stringify(game.pieces);
break;
case 'chat':
handleChat(request, response, game.chat);
break;
case 'dimensions':
resp = JSON.stringify(game.dimensions);
}
respOk(response, resp, 'text/json');
}
/**
* Handle transaction on game collection resource.
*/
function handleGames(request, response, path) {
var resp;
if (!path.length) {
if (request.method === "POST") {
// add a new game object
requestBody(request, function(form) {
var gamenm = form.name;
while (games[gamenm]) {
// game already exists, randomize a new one
gamenm = gamenm+Math.floor(Math.random()*10);
}
var game = new Game(gamenm);
var jar = new cookies(request, response);
var p = decodeURIComponent(jar.get('player'));
games[gamenm] = game;
addPlayerToGame(game, p);
// respond with the game name, in case we randomized a new one
respOk(response, JSON.stringify({name: gamenm}), 'text/json');
});
} else {
// return info on the games collection
resp = JSON.stringify(games);
respOk(response, resp, 'text/json');
}
} else {
// return info on a specifc game
var game = games[path.shift()];
if (game === undefined) {
response.writeHead(404, {'Content-Type': 'text/json'});
response.write("No such game exists", 'utf-8');
response.end();
return;
}
handleGame(request, response, game, path);
}
}
/**
* Handle transaction on chat.
* @param chat {list}: a chat object, which is a list of
* {id: {number}, name: {string}, input: {string}} objects
*/
function handleChat(request, response, chat) {
var resp, id;
if (request.method === "POST") {
// add a line to the chat log
requestBody(request, function(form) {
while (chat.length > CHATLINES) {
chat.shift();
}
/* If data is present in the chat, then increment the last id,
* otherwise start at 0.
*/
if (chat.length) {
id = chat[chat.length-1].id + 1;
} else {
id = 0;
}
chat.push({
id: id, // chat line id
name: form.name, // the user's name
input: form.input // the user's text input
});
respOk(response, '', 'text/json');
});
} else {
/* Return chat data. If lastid is specified, then we only return
* chat lines since this id.
*/
var form = requestQuery(request);
var lastid = +form.lastid;
if (lastid >= 0) {
for (var i=0; i<chat.length; i++) {
if (chat[i].id === lastid) {
break;
}
}
resp = JSON.stringify(chat.slice(i+1));
} else {
resp = JSON.stringify(chat);
}
respOk(response, resp, 'text/json');
}
}
var chat = [];
var games = {};
var server = http.createServer();
server.on('request', function(request, response) {
//console.log('games: '+JSON.stringify(games));
//console.log('got url:'+request.url);
var u = url.parse(request.url);
var path = u.pathname.split('/').map(function(x) {
return decodeURIComponent(x);
}).filter(function(x) {
return Boolean(x);
});
//console.log('decode: '+JSON.stringify(path));
//console.log('req headers:'+JSON.stringify(request.headers));
//console.log('got path:'+JSON.stringify(path));
switch(path[0]) {
case 'games':
handleGames(request, response, path.slice(1));
break;
case 'chat':
handleChat(request, response, chat);
break;
default:
var f;
// Assignment in if clase is purposeful
if (f = static_files[path[0]]) {
var type = 'text/html';
if (path[0].search('css$') >= 0) {
type = 'text/css';
} else if (path[0].search('js$') >= 0) {
type = 'text/javascript';
}
respOk(response, f, type);
} else {
respOk(response, static_files['index.html'], 'text/html');
}
break;
}
});
var port = (process.env.PORT || process.env.npm_package_config_port || 8010);
server.listen(port);