This repository has been archived by the owner on Oct 19, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
GameController.js
91 lines (82 loc) · 3.12 KB
/
GameController.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
const Game = require("./Game");
async function sleep(ms) {
return new Promise(function (res) {
setTimeout(res, ms)
})
}
class GameController {
constructor(httpWrapper, serverList, gameDataManager, botWebInterface) {
this.bots = new Map();
this.serverList = serverList;
this.httpWrapper = httpWrapper;
this.gameDataManager = gameDataManager;
this.botWebInterface = botWebInterface;
}
async startCharacter(characterId, server, runScript, characterName, gameVersion) {
return new Promise(async (resolve) => {
let serverInfo = await this.serverList.getServerInfo(server);
while (!serverInfo) {
console.log(`Unable to find server: ${server}, retrying in 10 seconds`);
await sleep(10000);
serverInfo = await this.serverList.getServerInfo(server);
}
let botUI = null;
if (this.botWebInterface)
botUI = this.botWebInterface.publisher.createInterface();
const game = new Game(gameVersion, this.httpWrapper.sessionCookie, serverInfo.addr, serverInfo.port, characterId, runScript, botUI, characterName);
game.on("start", resolve);
game.on("stop", () => {
let data = this.bots.get(characterId);
if (data.botUI)
data.botUI.destroy();
this.bots.delete(characterId);
if (!data.stopping) {
console.log(`character: ${characterId} stopped unexpectedly, restarting ...`)
this.bots.delete(characterId);
setTimeout(() => {
this.startCharacter(characterId, server, runScript, characterName, gameVersion)
}, 1000);
}
});
game.on("cm", (data) => {
for (let [characterId, bot] of this.bots) {
if (bot.game.send_cm(data)) {
return;
}
}
game.send_cm_failed(data)
})
game.on("config", async (data) => {
console.log(data)
switch (data.type) {
case "switchServer":
await this.stopCharacter(characterId);
await this.startCharacter(characterId, data.server, runScript, characterName, gameVersion)
break;
}
})
this.bots.set(characterId, {
characterId,
server,
runScript,
botUI,
game: game,
stopping: false,
});
game.start();
})
}
async stopCharacter(characterId) {
return new Promise((resolve, reject) => {
let bot = this.bots.get(characterId);
if (bot) {
bot.game.on("stop", resolve);
bot.stopping = true;
bot.game.stop();
} else {
resolve();
}
});
}
}
module.exports = GameController;