-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.js
53 lines (43 loc) · 1010 Bytes
/
timer.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
const DEFAULT_TIME = 600; // 600 sec = 10 min
export default class Timer {
constructor() {
this.counters = [
{
w: DEFAULT_TIME,
b: DEFAULT_TIME
},
{
w: DEFAULT_TIME,
b: DEFAULT_TIME
}
];
this.turns = ['w', 'w'];
}
startTimer(emitTime, endGame) {
this.timer = setInterval(() => {
emitTime(this.counters);
[0, 1].forEach((boardNum) => {
const turn = this.turns[boardNum];
// Decrease seconds counter
const counter = this.counters[boardNum][turn]--;
// If reaches 0
if (counter <= 0) {
// Update winner
const winner = {
boardNum,
color: turn === 'w' ? 'b' : 'w'
};
endGame(winner);
// Stop timer
clearInterval(this.timer);
}
});
}, 1000);
}
endTimer() {
clearInterval(this.timer);
}
updateTurn(boardNum, nextTurn) {
this.turns[boardNum] = nextTurn;
}
}