-
Notifications
You must be signed in to change notification settings - Fork 0
/
sockets.js
103 lines (83 loc) · 2.4 KB
/
sockets.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
102
103
const HumanPlayer = require('./human_player');
const Game = require('./game');
class Sockets {
constructor(io) {
this.socket = io;
this.setEventHandlers();
this.humanPlayerIds = {};
}
setEventHandlers() {
this.socket.on("connection", this.onSocketConnection.bind(this));
}
onSocketConnection(client) {
client.on("disconnect", () => { this.onClientDisconnect(client); });
client.on("new player", this.onNewPlayer(client));
client.on("move player", this.onMovePlayer.bind(this));
client.on("dire hit player", this.onDireHitPlayer.bind(this));
}
onClientDisconnect(client) {
if (this.game) {
this.game.removePlayer(this.humanPlayerIds[client.id]);
}
}
onNewPlayer(client) {
return data => {
if (!this.game) {
this.startNewGame();
}
const humanPlayer = this.game.addNewHumanPlayer(
data.name,
data.pokemonId,
data.id);
this.humanPlayerIds[client.id] = humanPlayer;
};
}
startNewGame() {
this.game = new Game();
this.lastTime = Date.now();
this.gameLoop = setInterval(this.stepCurrentGame.bind(this), REDRAW_RATE);
}
stepCurrentGame() {
if (this.closeGameIfNeeded()) return;
const currentTime = Date.now();
const timeDelta = currentTime - this.lastTime;
const data = this.game.step(timeDelta, currentTime);
this.notifyInactivePlayers(data.inactivityData);
this.socket.emit("draw game", data.playerData);
this.lastTime = currentTime;
}
notifyInactivePlayers(inactivePlayerIds) {
inactivePlayerIds.forEach(inactivePlayerId => {
this.socket.emit("inactive player", { id: inactivePlayerId });
});
}
closeGameIfNeeded() {
if (this.game.isEmpty()) {
this.stopGame();
return true;
}
return false;
}
stopGame() {
clearInterval(this.gameLoop);
this.gameLoop = null;
this.game = null;
}
onMovePlayer(data) {
if (!this.game) return;
const player = this.game.findHumanPlayer(data.id);
if (player) player.power(data.impulses);
}
onDireHitPlayer(data) {
if (!this.game) return;
const player = this.game.findHumanPlayer(data.id);
if (player && !player.activatingDireHit) {
player.activateDireHit();
this.socket.emit("activate dire hit",
{ id: player.id, lag: player.direHitDelay() }
);
}
}
}
const REDRAW_RATE = 1000 / 20;
module.exports = Sockets;