-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
191 lines (162 loc) · 5.63 KB
/
server.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
var Connect4 = require('./connect4.js');
var Room = require('./room.js');
var GeohashMap = require('./geohash_map.js');
var Sanitizer = require('sanitizer');
var Express = require('express');
var BodyParser = require('body-parser');
var app = Express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
const port = parseInt(process.argv[2] || '3000');
const rooms = { debug: new Room('debug', new Connect4(7, 6)),
debug2: new Room('debug2', new Connect4(9, 9, 5))};
const geohashMap = new GeohashMap();
const backgrounds = ['beach', 'field', 'flowers', 'sunset'];
// Results
let results = [];
const RESULTS_FILE = 'results.json';
try {
console.log('Reading results file...');
var file = fs.readFileSync(RESULTS_FILE);
results = JSON.parse(file);
}
catch (e) {
if (e instanceof Error && e.code == 'ENOENT') {
console.log('No ' + RESULTS_FILE + ' file found!')
} else {
throw e;
}
}
app.use(Express.static('public'));
app.use(BodyParser.urlencoded({ extended: true }));
app.post('/game', function (req, res) {
// Generate a unique ID
let id;
do {
id = Math.random().toString(36).substr(2, 9);
} while (typeof rooms[id] !== 'undefined');
let cols = constrain(req.body.cols, 7, 4, 10);
let rows = constrain(req.body.rows, 6, 4, 10);
let toWin = constrain(parseInt(req.body.toWin), 4, 3, 7);
let background = req.body.bg;
if (!background) {
background = backgrounds[Math.floor(Math.random() * backgrounds.length)];
}
rooms[id] = new Room(id, new Connect4(cols, rows, toWin), { background: background });
console.log('Created new room:', id,
'( cols: ', cols, ', rows: ', rows, ' to win: ', toWin, ')');
if (req.body.geohash) {
rooms[id].geohash = req.body.geohash;
geohashMap.add(req.body.geohash, rooms[id]);
console.log(' with geohash:', req.body.geohash);
}
sweepRoom(rooms[id], 10 * 60 * 1000);
res.redirect('game/' + id);
});
app.get('/game/:id', function (req, res) {
if (rooms[req.params.id]) {
res.sendFile(__dirname + '/public/game.html');
} else {
res.status(404).send('Invalid game ID');
}
});
app.get('/games/:geohash', function (req, res) {
res.send(
geohashMap.nearest(req.params.geohash, 10).map(function (room) {
return { id: room.id, game: room.game };
}));
});
app.get('/results', function (req, res) {
res.send(results.slice(-10).reverse());
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
io.on('connection', function(socket) {
console.log('New connection');
let room;
let name;
let game;
let player;
socket.on('join', function (data) {
let roomId = data.id;
let name = Sanitizer.sanitize(data.name).substr(0,30);
if (name.replace(/ /g,'') === '') {
name = 'anon';
}
console.log(name + ' joined room ' + roomId);
room = rooms[roomId];
player = { name: name };
socket.player = player;
if (room) {
game = room.game;
if (!(game.player1 && game.player2)) {
game.addPlayer(player);
socket.emit('player-number', player.number);
socket.on('place-token', function (column) {
if (game.turn === player) {
game.placeToken(column);
room.broadcast('place-token', { column: column, player: player, turn: game.turn });
if (game.state === 'won') {
room.status(game.winner, 'wins!');
pushResult({ winner: game.winner, loser: game.loser, board: game.board, winning: game.winning, columns: game.columns, rows: game.rows });
room.sync();
} else if (game.state === 'draw') {
pushResult({ draw: true, winner: game.player1, loser: game.player2, board: game.board, columns: game.columns, rows: game.rows });
room.sync();
}
}
});
}
room.join(socket);
if (room.sweeper) {
console.log('Cancelling delete timer for room:', room.id);
clearTimeout(room.sweeper);
delete room.sweeper;
}
socket.emit('room', room.options);
room.sync();
socket.on('chat-message', function (msg) {
room.chat(player, msg);
});
} else {
socket.emit('game-closed');
}
});
socket.on('disconnect', function(){
console.log((name || 'anonymous user') + ' disconnected');
if (room) {
room.leave(socket);
game.removePlayer(player);
room.sync();
if (!room.sockets.length) {
sweepRoom(room, 10 * 60 * 1000);
}
}
});
});
function sweepRoom(room, timer) {
console.log('Starting delete timer for room:', room.id);
room.sweeper = setTimeout(function () {
console.log('Deleting empty room:', room.id);
delete rooms[room.id];
if (room.geohash) {
geohashMap.remove(room.geohash, room);
}
}, timer);
}
function pushResult(result) {
results.push(result);
fs.writeFile(RESULTS_FILE, JSON.stringify(results));
}
function constrain(value, defaultValue, min, max) {
if (!value)
return defaultValue;
else if (value > max)
return max;
else if (value < min)
return min;
else
return value;
}