-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
101 lines (87 loc) · 2.6 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
const CONSTANTS = require('./utils/constants.js');
const http = require('http');
const fs = require('fs');
const path = require('path');
const WebSocket = require('ws');
const { PORT, MAX_TIME, CLIENT, SERVER } = CONSTANTS;
let nextPlayerIndex = 0;
const server = http.createServer((req, res) => {
const filePath = ( req.url === '/' ) ? '/public/index.html' : req.url;
const extname = path.extname(filePath);
let contentType = 'text/html';
if (extname === '.js') contentType = 'text/javascript';
else if (extname === '.css') contentType = 'text/css';
res.writeHead(200, { 'Content-Type': contentType });
fs.createReadStream(`${__dirname}/${filePath}`, 'utf8').pipe(res);
});
const wsServer = new WebSocket.Server({ server });
wsServer.on('connection', (socket) => {
console.log('A new client has joined the server');
socket.on('message', (data) => {
const { type, payload } = JSON.parse(data);
switch(type) {
case CLIENT.MESSAGE.NEW_USER:
handleNewUser(socket);
break;
case CLIENT.MESSAGE.PASS_POTATO:
passThePotatoTo(payload.newPotatoHolderIndex);
break;
default:
break;
}
});
});
function broadcast(data, socketToOmit) {
wsServer.clients.forEach((connectedClient) => {
if (connectedClient.readyState === WebSocket.OPEN && connectedClient !== socketToOmit) {
connectedClient.send(JSON.stringify(data));
}
});
}
function handleNewUser(socket) {
if (nextPlayerIndex < 4) {
const message = {
type: SERVER.MESSAGE.PLAYER_ASSIGNMENT,
payload: { clientPlayerIndex: nextPlayerIndex }
}
socket.send(JSON.stringify(message))
nextPlayerIndex++;
if (nextPlayerIndex === 4) {
const randomFirstPotatoHolder = Math.floor(Math.random() * 4);
passThePotatoTo(randomFirstPotatoHolder);
startTimer();
}
} else {
const message = {
type: SERVER.MESSAGE.GAME_FULL
}
socket.send(JSON.stringify(message))
}
}
function passThePotatoTo(newPotatoHolderIndex) {
broadcast({
type: SERVER.BROADCAST.NEW_POTATO_HOLDER,
payload: { newPotatoHolderIndex }
})
}
function startTimer() {
let clockValue = MAX_TIME;
const interval = setInterval(() => {
if (clockValue > 0) {
broadcast({
type: SERVER.BROADCAST.COUNTDOWN,
payload: { clockValue }
});
clockValue--;
} else {
clearInterval(interval);
nextPlayerIndex = 0;
broadcast({
type: SERVER.BROADCAST.GAME_OVER,
});
}
}, 1000);
}
server.listen(PORT, () => {
console.log(`Listening on: http://localhost:${server.address().port}`);
});