enable replays
This commit is contained in:
parent
eabe338971
commit
7a7d6580fc
7 changed files with 129 additions and 36 deletions
|
|
@ -1,4 +1,6 @@
|
|||
import fs from 'fs'
|
||||
import readline from 'readline'
|
||||
import stream from 'stream'
|
||||
import { logger } from './../common/Util'
|
||||
import { DATA_DIR } from './../server/Dirs'
|
||||
|
||||
|
|
@ -27,19 +29,39 @@ const _log = (gameId: string, ...args: Array<any>) => {
|
|||
fs.appendFileSync(file, str + "\n")
|
||||
}
|
||||
|
||||
const get = (gameId: string) => {
|
||||
const get = async (
|
||||
gameId: string,
|
||||
offset: number = 0,
|
||||
size: number = 10000
|
||||
): Promise<any[]> => {
|
||||
const file = filename(gameId)
|
||||
if (!fs.existsSync(file)) {
|
||||
return []
|
||||
}
|
||||
const lines = fs.readFileSync(file, 'utf-8').split("\n")
|
||||
return lines.filter((line: string) => !!line).map((line: string) => {
|
||||
try {
|
||||
return JSON.parse(line)
|
||||
} catch (e) {
|
||||
log.log(line)
|
||||
log.log(e)
|
||||
}
|
||||
return new Promise((resolve) => {
|
||||
const instream = fs.createReadStream(file)
|
||||
const outstream = new stream.Writable()
|
||||
const rl = readline.createInterface(instream, outstream)
|
||||
const lines: any[] = []
|
||||
let i = -1
|
||||
rl.on('line', (line) => {
|
||||
if (!line) {
|
||||
// skip empty
|
||||
return
|
||||
}
|
||||
i++
|
||||
if (offset > i) {
|
||||
return
|
||||
}
|
||||
if (offset + size <= i) {
|
||||
rl.close()
|
||||
return
|
||||
}
|
||||
lines.push(JSON.parse(line))
|
||||
})
|
||||
rl.on('close', () => {
|
||||
resolve(lines)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -203,20 +203,27 @@ wss.on('message', async ({socket, data} : { socket: WebSocket, data: any }) => {
|
|||
const msg = JSON.parse(data)
|
||||
const msgType = msg[0]
|
||||
switch (msgType) {
|
||||
case Protocol.EV_CLIENT_INIT_REPLAY: {
|
||||
case Protocol.EV_CLIENT_REPLAY_DATA: {
|
||||
if (!GameLog.exists(gameId)) {
|
||||
throw `[gamelog ${gameId} does not exist... ]`
|
||||
}
|
||||
const log = GameLog.get(gameId)
|
||||
const game = await Game.createGameObject(
|
||||
gameId,
|
||||
log[0][2],
|
||||
log[0][3],
|
||||
log[0][4],
|
||||
log[0][5] || ScoreMode.FINAL
|
||||
)
|
||||
const offset = msg[1]
|
||||
const size = msg[2]
|
||||
|
||||
const log = await GameLog.get(gameId, offset, size)
|
||||
let game = null
|
||||
if (offset === 0) {
|
||||
// also need the game
|
||||
game = await Game.createGameObject(
|
||||
gameId,
|
||||
log[0][2],
|
||||
log[0][3],
|
||||
log[0][4],
|
||||
log[0][5] || ScoreMode.FINAL
|
||||
)
|
||||
}
|
||||
notify(
|
||||
[Protocol.EV_SERVER_INIT_REPLAY, Util.encodeGame(game), log],
|
||||
[Protocol.EV_SERVER_REPLAY_DATA, log, game ? Util.encodeGame(game) : null],
|
||||
[socket]
|
||||
)
|
||||
} break
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue