-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
46 lines (44 loc) · 1.35 KB
/
server.js
File metadata and controls
46 lines (44 loc) · 1.35 KB
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
function randomXToY(minVal,maxVal,floatVal)
{
var randVal = minVal+(Math.random()*(maxVal-minVal));
return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}
var clients = {};
var io = require('socket.io').listen(8080);
io.sockets.on('connection', function (socket) {
clients[socket.id] = {};
socket.on('new', function (data) {
clients[socket.id].name = data.name;
var position = {};
position.x = randomXToY(0, 300);
position.y = randomXToY(0, 200);
clients[socket.id].position = position;
for(var i in clients){
socket.emit('add', clients[i]);
}
socket.broadcast.emit('add', clients[socket.id]);
});
socket.on('move', function (data) {
clients[socket.id].dir = data.dir;
switch (data.dir) {
case 2:
clients[socket.id].position.x -= 2;
break;
case 0:
clients[socket.id].position.y -= 2;
break;
case 3:
clients[socket.id].position.x += 2;
break;
case 1:
clients[socket.id].position.y += 2;
break;
}
socket.emit('move', clients[socket.id]);
socket.broadcast.emit('move', clients[socket.id]);
});
socket.on('disconnect', function () {
socket.broadcast.emit('remove', clients[socket.id]);
delete clients[socket.id];
});
});