-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
106 lines (97 loc) · 2.8 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
'use strict';
const express = require('express');
const app = express();
app.use(express.static('public'));
const expressWs = require('express-ws')(app);
const clients = [];
const nameCounts = {};
function clientForName(name) {
for(let i = 0; i < clients.length; i++) {
if (clients[i].name === name) return clients[i];
}
}
function normalizeName(name) {
console.log('Normalizing: [' + name + ']');
if (/[\,\<\>\\\/]/.test(name)) {
return "onvre!"
}
return name.substring(0, 10);
}
function getUniqueName(name) {
if (!nameCounts[name]) {
nameCounts[name] = 1;
return name;
} else {
nameCounts[name] ++;
return name + ' (' + nameCounts[name] + ')';
}
}
const SPAWN_TIME = 2000;
app.ws('/game', function(ws, req) {
const client = { ws: ws, kills: 0, deaths: 0 };
clients.push(client);
ws.on('message', function(msg) {
const now = new Date().getTime();
if (client.disconnected) {
return;
}
const parts = msg.split(',');
const messageType = parts[0];
if (messageType === 'c') {
client.givenName = normalizeName(msg.substring(2) || 'New Folder');
client.name = getUniqueName(client.givenName);
client.color = '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16);
console.log('Client Connected: ' + client.name);
client.ws.send(client.name + ',n,'+client.color.toString(16));
clients.forEach(function(c) {
if (c !== client && !c.disconnected) {
try {
c.ws.send(client.name+',c,'+client.color);
client.ws.send(c.name+',c,'+c.color);
} catch (e) {console.error(e);}
}
});
} else {
if (messageType === 'k') {
client.kills++;
const deadClient = clientForName(parts[1]);
if (deadClient) {
deadClient.deaths++;
deadClient.dead = true;
}
} else if (messageType === 'p') {
if (client.dead) {
if (now - client.diedAt < SPAWN_TIME) return;
client.dead = false;
}
}
clients.forEach(function(c) {
if (c !== client && !c.disconnected) {
try { c.ws.send('' + client.name + ',' + msg); }
catch (e) {console.error(e);}
}
});
}
});
ws.on('close', function() {
console.log('' + client.name + ' disconnected.');
client.disconnected = true;
nameCounts[client.givenName]--;
clients.forEach(function(c) {
if (c !== client && !c.disconnected) {
try { c.ws.send('' + client.name + ',d'); }
catch (e) {console.error(e);}
}
});
for(let i = clients.length - 1; i >= 0; i--) {
if(clients[i] === client) {
clients.splice(i, 1);
return;
}
}
});
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Running on port ${PORT}`);
});