-
Notifications
You must be signed in to change notification settings - Fork 34
/
SpaaaceServerEngine.js
91 lines (71 loc) · 2.57 KB
/
SpaaaceServerEngine.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
'use strict';
const ServerEngine = require('incheon').ServerEngine;
const nameGenerator = require('./NameGenerator');
class SpaaaceServerEngine extends ServerEngine {
constructor(io, gameEngine, inputOptions) {
super(io, gameEngine, inputOptions);
this.serializer.registerClass(require('../common/Missile'));
this.serializer.registerClass(require('../common/Ship'));
this.scoreData = {};
}
start() {
super.start();
for (let x = 0; x < 3; x++) this.makeBot();
this.gameEngine.on('missileHit', (e) => {
// add kills
if (this.scoreData[e.missile.shipOwnerId]) this.scoreData[e.missile.shipOwnerId].kills++;
// remove score data for killed ship
delete this.scoreData[e.ship.id];
this.updateScore();
console.log(`ship killed: ${e.ship.toString()}`);
this.gameEngine.removeObjectFromWorld(e.ship.id);
if (e.ship.isBot) {
setTimeout(() => this.makeBot(), 5000);
}
});
}
onPlayerConnected(socket) {
super.onPlayerConnected(socket);
let makePlayerShip = () => {
let ship = this.gameEngine.makeShip(socket.playerId);
this.scoreData[ship.id] = {
kills: 0,
name: nameGenerator('general')
};
this.updateScore();
};
// handle client restart requests
socket.on('requestRestart', makePlayerShip);
}
onPlayerDisconnected(socketId, playerId) {
super.onPlayerDisconnected(socketId, playerId);
// iterate through all objects, delete those that are associated with the player
for (let objId of Object.keys(this.gameEngine.world.objects)) {
let obj = this.gameEngine.world.objects[objId];
if (obj.playerId == playerId) {
// remove score data
if (this.scoreData[objId]) {
delete this.scoreData[objId];
}
delete this.gameEngine.world.objects[objId];
}
}
this.updateScore();
}
makeBot() {
let bot = this.gameEngine.makeShip(0);
bot.attachAI();
this.scoreData[bot.id] = {
kills: 0,
name: nameGenerator('general') + 'Bot'
};
this.updateScore();
}
updateScore() {
// delay so player socket can catch up
setTimeout(() => {
this.io.sockets.emit('scoreUpdate', this.scoreData);
}, 1000);
}
}
module.exports = SpaaaceServerEngine;