-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgame-engine.js
70 lines (57 loc) · 1.97 KB
/
game-engine.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
let gameEngine = {};
const duration = 300000;
let sessionObj = {};
let socketRef = null;
let socketServerRef = null;
let gameLoopInterval = null;
gameEngine.init = (server) => {
socketServerRef = server;
}
gameEngine.startSession = (socket) => {
console.log("INFO: Starting game session.");
sessionObj.id = socket.id;
sessionObj.start = new Date();
sessionObj.end = new Date(new Date().getTime() + duration);
gameLoopInterval = setInterval(function() {
gameEngine.gameLoop();
}, 1000);
}
gameEngine.getSession = () => {
return sessionObj;
}
gameEngine.stopSession = () => {
let scores = Object.keys(sessionObj.mapData).map(function(key) {
return {country: key, score: sessionObj.mapData[key]};
}).sort((a, b) => (b.score - a.score));
socketServerRef.sockets.emit('sessionEnded', scores); // session is over. notify all clients
clearInterval(gameLoopInterval);
sessionObj = {};
console.log('INFO: Session ended..', scores);
}
gameEngine.gameLoop = () => {
console.log('INFO: Session is active..');
socketServerRef.sockets.emit('timerTick', {
diff: (sessionObj.end.getTime() - new Date().getTime()) / 1000,
end: sessionObj.end.getTime()
});
if(sessionObj.end.getTime() <= new Date().getTime()) {
gameEngine.stopSession();
}
}
gameEngine.connectPlayer = (socket, player) => {
if(!sessionObj.id)
gameEngine.startSession(socket);
if(!sessionObj.mapData)
sessionObj.mapData = {};
if(sessionObj.mapData[player.country])
sessionObj.mapData[player.country]++;
else
sessionObj.mapData[player.country] = 1;
socketRef = socket;
socketRef.broadcast.emit('playerConnected', player);
socketServerRef.sockets.emit('receiveMapData', sessionObj.mapData); // broadcast map data to all
console.log('INFO: Player connected. ', player, sessionObj.mapData);
}
gameEngine.disconnectPlayer = () => {
}
module.exports = gameEngine;