-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
71 lines (57 loc) · 1.58 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
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require('socket.io');
const Coordinate = require('./private/game/Coordinate');
const Game = require('./private/game/Game');
const io = new Server(server, {
cookie: {
name: 'io',
path: '/',
httpOnly: true,
sameSite: 'lax',
},
});
app.use(express.static('public'));
app.get('/', (req, res) => {
res.sendFile(`${__dirname}/public/index.html`);
});
const game = new Game();
function updateGame(socket) {
const gameState = game.getGameState();
socket.emit('update', gameState);
console.log('updated');
}
io.on('connection', (socket) => {
console.log('a user connected');
updateGame(socket);
// Implement a vote for 50% + 1 to start the match
socket.on('ready', () => {
setInterval(() => {
game.giveEnergyToPlayers();
updateGame(socket);
}, 5000);
// game.giveEnergyToPlayers
updateGame(socket);
});
socket.on('join', (data) => {
game.addPlayer(socket.id, data.name, data.color);
updateGame(socket);
});
socket.on('action', (data) => {
const coordinate = new Coordinate(data.coordinateClicked.x, data.coordinateClicked.y);
const change = game.action(socket.id, coordinate, data.action);
if (change) {
updateGame(socket);
}
});
socket.on('disconnect', () => {
console.log('user disconnected');
game.removePlayer(socket.id);
updateGame(socket);
});
});
server.listen(process.env.PORT, () => {
console.log('listening on *:', process.env.PORT);
});