This repository was 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
/
Copy pathAsyncApi.ts
82 lines (71 loc) · 2.65 KB
/
AsyncApi.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
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
import { Server } from './Server'
import { GameState, Move } from '../rules/CurrentGame'
import { AsyncGameManager } from './AsyncGameManager'
import * as portfinder from 'portfinder'
export class AsyncApi {
private static server: Promise<Server>
private static asyncGameManager: AsyncGameManager
private static moveRequests: Map<number, Map<number, MoveRequest>> = new Map<number, Map<number, MoveRequest>>()
private static nextKey: number = 0
public static getServer(): Promise<Server> {
if (AsyncApi.server == null) {
try {
AsyncApi.server = portfinder.getPortPromise({ port: 13050 })
.then(port => new Server(port, true))
.catch(e => {
console.log('Error while creating new AsyncApi-Server on port 13050: ' + e)
return null
})
} catch (e) {
console.log('Error while creating new AsyncApi-Server on port 13050: ' + e)
}
}
return AsyncApi.server
}
public static getAsyncGameManager(port: number): AsyncGameManager {
if (!this.asyncGameManager) {
try {
this.asyncGameManager = new AsyncGameManager(port)
} catch (e) {
console.log('Error while creating new AsyncGameManager on port ' + port + ': ' + e)
}
}
return this.asyncGameManager
}
public static hasMoveRequest(gameId: number): boolean {
if (this.moveRequests.has(gameId)) {
return this.moveRequests.has(gameId) && this.moveRequests.get(gameId).size > 0
} else {
return false
}
}
public static getMoveRequest(gameId: number): [number, MoveRequest] {
return this.moveRequests.get(gameId).entries().next().value
}
public static redeemMoveRequest(gameId: number, id: number, move: Move) {
console.log(`redeemMoveRequest for game ${gameId}, id ${id}, map: `, this.moveRequests.get(gameId))
console.log('Move:', move)
let request = this.moveRequests.get(gameId).get(id)
if (!request) {
console.log(`found no request for id ${id}, map was`, this.moveRequests.get(gameId))
} else {
request.callback(move)//Handle things on the client side
this.moveRequests.get(gameId).delete(id)//Remove request from list
}
}
public static lodgeActionRequest(gameId: number, state: GameState, callback: (m: Move) => void) {
console.log('new move request for game ' + gameId)
if (!this.moveRequests.has(gameId)) {
this.moveRequests.set(gameId, new Map<number, MoveRequest>())
}
this.moveRequests.get(gameId).set(this.nextKey, {
state: state,
callback: callback,
})
this.nextKey++
}
}
interface MoveRequest {
state: GameState;
callback: (m: Move) => void;
}