-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
69 lines (56 loc) · 1.67 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
const express = require('express');
const app = express();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
app.use('/public', express.static(`${__dirname}/public`));
const Game = require('./game/Game.js');
const ROWS = 21;
const COLUMNS = 21;
app.all('*', (req, res) => {
res.sendFile(`${__dirname}/public/index.html`);
});
// roomID:{players:[], game:gameObj}
const rooms = {};
io.on('connection', (socket) => {
const ID = socket.id;
let USERNAME = '';
let ROOM = '';
let GAME = '';
socket.on('join', (room) => {
// sanity check needed
ROOM = escape(room);
socket.join(ROOM);
if (Object.prototype.hasOwnProperty.call(rooms, ROOM)) {
rooms[ROOM].players.push(ID);
} else {
rooms[ROOM] = { players: [ID], game: new Game(ROWS, COLUMNS, ROOM, io) };
}
GAME = rooms[ROOM].game;
});
socket.on('move', (direction) => {
GAME.movePlayer(ID, direction);
});
socket.on('plantBomb', () => {
GAME.plantBomb(ID);
});
socket.on('disconnect', () => {
if (GAME.players && Object.prototype.hasOwnProperty.call(GAME.players, ID)) {
GAME.removePlayer(ID);
}
io.in(ROOM).emit('message', `${USERNAME} has left.`);
});
socket.on('message', (msg) => {
io.in(ROOM).emit('message', `${USERNAME}: ${msg}`);
});
socket.on('setUsername', (name) => {
USERNAME = name;
io.in(ROOM).emit('message', `${USERNAME} has joined.`);
GAME.addPlayer(ID, null, USERNAME);
});
});
http.listen(3000, () => {
console.log('listening on *:3000');
});
process.on('uncaughtException', (err) => {
console.error(err);
});