-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
70 lines (62 loc) · 1.81 KB
/
Copy pathserver.js
File metadata and controls
70 lines (62 loc) · 1.81 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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// modules
const express = require('express');
const socketIO = require('socket.io');
//init port and dir
const port = process.env.PORT || 3000;
const index = '/index.html';
// init server
const server = express()
.use((req, res) => {
res.sendFile(index, { root: __dirname })
})
.listen(port, () =>{
console.log(`Server started on port ${port}`)
});
// init socketIO
const io = socketIO(server);
let users = [];
let currentPlayer = null;
let timeout = null;
const words = ['porte', 'tableau', 'pantoufle', 'lune', 'assiette', 'mamie'];
io.on('connection', (socket) => {
socket.on('username', (username) => {
console.log(`The user ${username} has joined the server`);
socket.username = username;
users.push(socket);
sendUsers();
if(users.length === 1 ) {
currentPlayer = socket;
switchPlayer();
}
});
socket.on('disconnect', () => {
users = users.filter((user) => {
return user !== socket;
});
sendUsers();
if(user.length === 0) {
timeout = clearTimeout(timeout);
}
});
socket.on('line', (data) => {
socket.broadcast.emit('line', data);
});
});
function sendUsers() {
const usersData = users.map((user) => {
return {
username : user.username,
isActive: user === currentPlayer
}
});
io.emit('users', usersData);
}
function switchPlayer() {
timeout = setTimeout(switchPlayer, 15000);
const indexCurrentPlayer = users.indexOf(currentPlayer);
currentPlayer = users[(indexCurrentPlayer + 1) % users.length];
sendUsers();
const nextWord = words[Math.floor(Math.random() * words.length)];
currentPlayer.emit('word', nextWord);
io.emit('clear');
}