-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsockets.js
More file actions
40 lines (30 loc) · 906 Bytes
/
sockets.js
File metadata and controls
40 lines (30 loc) · 906 Bytes
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
let readyPlayerCount = 0;
function listen(io) {
const pongNamespace = io.of('/pong');
pongNamespace.on('connection', (socket) => {
let room;
console.log('a user connected', socket.id);
socket.on('ready', () => {
room = 'room' + Math.floor(readyPlayerCount / 2);
socket.join(room);
console.log('Player ready', socket.id, room);
readyPlayerCount++;
if (readyPlayerCount % 2 === 0) {
pongNamespace.in(room).emit('startGame', socket.id);
}
});
socket.on('paddleMove', (paddleData) => {
socket.to(room).emit('paddleMove', paddleData);
});
socket.on('ballMove', (ballData) => {
socket.to(room).emit('ballMove', ballData);
});
socket.on('disconnect', (reason) => {
console.log(`Client ${socket.id} disconnected: ${reason}`);
socket.leave(room);
});
})
}
module.exports = {
listen,
};