forked from mayuk24/espcar.io
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
95 lines (83 loc) · 1.98 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
const
express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io')(server),
Move = require('./move');
host = (process.env.HOST || 'YOUR-HOST'),
port = (process.env.PORT || '3000'),
pbl = './public',
msg = () =>
{
console.log(`Server running at http://${host}:${port}/`);
};
server.listen(port,host,msg);
app.use(express.static(pbl));
let
conexions = 0,
clients = {
joysticks:[],
esps: []
},
log = true;
const uEsps = (io,socketId = false) =>{
if(socketId)io.to(socketId).emit('uEsps',{clientId:socketId,esps:clients.esps});
else clients.joysticks.forEach(clientid => {
io.to(clientid).emit('uEsps',{clientId:clientid,esps:clients.esps});
});
if(log)console.log(clients);
};
io.on('connection', (socket) => {
conexions++;
if(log)console.log(`conexions = ${conexions}`);
socket.on('identify', data =>{
if(data == 'joystick'){
clients.joysticks.push(socket.id);
uEsps(io,socket.id);
}
else if(data == 'esp'){
clients.esps.push({id:socket.id,useBy:'none'});
uEsps(io);
}
});
socket.on('selectEsp',data =>{
if(clients.esps[data].useBy == 'none'){
clients.esps[data].useBy = socket.id;
uEsps(io);
}
});
socket.on('unselectEsp',data =>{
if(clients.esps[data].useBy == socket.id){
clients.esps[data].useBy = 'none';
uEsps(io);
}
});
socket.on('move', data =>{
esp = new Move(data,socket,{
eventName:'moving',
debug:log
});
esp.init(clients.esps,socket.id);
});
socket.on('disconnect',()=>
{
conexions--;
let joystick = clients.joysticks.indexOf(socket.id);
if (joystick > -1){
clients.joysticks.splice(joystick ,1);
clients.esps.forEach(element => {
if (element.useBy == socket.id ){
element.useBy = 'none';
uEsps(io);
}
});
}
else{
clients.esps = clients.esps.filter( item =>{
if(item.id == socket.id ) io.to(item.useBy).emit('dEsp');
return item.id !== socket.id;
});
uEsps(io);
}
});
});