This repository has been archived by the owner on Sep 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Replay.ts
55 lines (51 loc) · 1.9 KB
/
Replay.ts
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
import { Game } from '../rules/Game'
import { GameResult, GameState } from '../rules/CurrentGame'
import { Replay as GCO_Replay } from '../rules/GameCreationOptions'
import { Parser } from './Parser'
import { Logger } from '../Logger'
export class Replay extends Game {
constructor(replay: GCO_Replay) {
super(replay.gameId)
this.isReplay = true
this.replayPath = replay.path
this.ready = new Promise<void>((gameReady, gameError) => {
new Promise((res: (string) => void, rej) => {
let fs = require('fs')
let zlib = require('zlib')
let buf = []
let stream = fs.createReadStream(replay.path)
if (replay.path.endsWith('.gz')) {
stream = stream.pipe(zlib.createGunzip())
}
stream
.on('error', function(error) { rej(error) })
.on('data', function(data) { buf.push(data) })
.on('end', function() { res(buf.join(''))})
}).then(Parser.getJSONFromXML)
.then(decoded => {
if (decoded.protocol) {
if (decoded.protocol.room) {
for (let room of decoded.protocol.room) {
if (room.data[0].state) {
const state = room.data[0].state[0]
this.gameStates.push(GameState.fromJSON(state))
} else if (room.data[0].score) {
const result = room.data[0]
this.gameResult = GameResult.fromJSON(result)
}
}
Logger.getLogger().log('Replay', 'constructor', `loaded ${this.gameStates.length} states from ${replay.path}`)
}
}
gameReady()
})
})
}
getState(n: number) {
if (n >= 0 && n < this.gameStates.length) {
return Promise.resolve(this.gameStates[n])
} else {
return Promise.resolve(this.gameStates[this.gameStates.length - 1])
}
}
}