-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
81 lines (69 loc) · 2.08 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
var express = require('express')
var app = express()
var server = require('http').createServer(app)
var io = require('socket.io').listen(server)
users = []
connections = []
server.listen(process.env.PORT || 3000)
console.log('Server running on port 3000')
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html')
})
io.sockets.on('connection', function(socket) {
connections.push(socket)
console.log('Connected: %s sockets connected', connections.length)
// Disconnect
socket.on('disconnect', function(data) {
connections.splice(connections.indexOf(socket), 1)
users = users.filter(function(obj) { return obj.id !== socket.id; })
updateUsers();
console.log('Disconnected: %s sockets connected', connections.length)
})
socket.on("new user", function(data) {
users.push({
id:socket.id,
posx:0,
posy:0,
color: getRandomColor(),
username: data
});
updateUsers();
console.log("new user boys" + data);
});
socket.on('left', function() {
var user = fetchUser(socket.id);
user.posx -= 5;
updateUsers();
})
socket.on('right', function() {
var user = fetchUser(socket.id);
user.posx += 5;
updateUsers();
})
socket.on('up', function() {
var user = fetchUser(socket.id);
user.posy -= 5;
updateUsers();
})
socket.on('down', function() {
var user = fetchUser(socket.id);
user.posy += 5;
updateUsers();
})
function fetchUser(id) {
return users.filter(function( user ) {
return user.id == id;
})[0];
}
function updateUsers() {
io.sockets.emit('get users', users);
}
function getRandomColor() {
var letters = '0123456789ABCDEF';
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
})