-
Notifications
You must be signed in to change notification settings - Fork 2
/
Game.ts
96 lines (74 loc) · 1.96 KB
/
Game.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import type Team from './Team';
import type { GameEvent } from './types/GameEvent';
import type Commentator from './Commentator';
import { EventEmitter } from 'events';
import Engine from './Engine';
import Reporter from './Reporter';
export default class Game extends EventEmitter {
/**
* Milliseconds between each simulation
*/
gameSpeed = 500;
/**
* Engine
*/
engine: Engine;
/**
* The home team
*/
homeTeam: Team;
/**
* The away team
*/
awayTeam: Team;
/**
* The commentator
*/
commentator: Commentator;
/**
* Events copy
*/
events: GameEvent[] = [];
constructor(homeTeam: Team, awayTeam: Team, commentator: Commentator) {
super();
this.homeTeam = homeTeam;
this.awayTeam = awayTeam;
this.commentator = commentator;
this.engine = new Engine(this.homeTeam, this.awayTeam);
}
start() {
this.engine.start();
this.events = this.engine.gameEvents.slice();
this.events.forEach(gameEvent => {
this.emit('comment', {
text: this.commentator.comment(gameEvent),
gameInfo: this.engine.gameInfo,
});
});
// Clear events so we only dispatch new ones
this.events = [];
this.simulate();
}
simulate() {
this.engine.simulate();
this.events = this.engine.gameEvents.slice();
this.loop();
}
loop = () => {
const event = this.events.shift();
if (!event) {
this.report();
return;
}
this.emit('comment', {
text: this.commentator.comment(event),
gameInfo: event.gameInfo,
});
this.emit('event', event);
setTimeout(this.loop, this.gameSpeed);
};
report() {
const reporter = new Reporter(this.engine.gameEvents);
this.emit('report', reporter.getReport());
}
}