Learn RxJS
Search…
Click Ninja Game
By adamlubek
This recipe shows usage of time interval operator in a simple game

Example Code

Click Ninja Game

index.ts

1
// RxJS v6+
2
import { fromEvent, TimeInterval } from 'rxjs';
3
import { timeInterval, takeWhile, scan, tap, repeat, finalize } from 'rxjs/operators';
4
import { render, clear } from './html-renderer';
5
6
interface State {
7
score: number;
8
interval: number;
9
threshold: number;
10
}
11
12
fromEvent(document, 'mousedown').pipe(
13
timeInterval(),
14
scan<TimeInterval<Event>, State>((state, timeInterval) => ({
15
score: state.score + 1,
16
interval: timeInterval.interval,
17
threshold: state.threshold - 2
18
}), { score: 0, interval: 0, threshold: 300 }),
19
takeWhile((state: State) => state.interval < state.threshold),
20
tap((state: State) => render(state.score, Math.floor(state.score / 10))),
21
finalize(clear),
22
repeat()
23
).subscribe();
Copied!

html-renderer.ts

1
const texts = {
2
0: 'click, click',
3
1: 'keep clicking',
4
2: 'wow',
5
3: 'not tired yet?!',
6
4: 'click master!',
7
5: 'inhuman!!!',
8
6: 'ininhuman!!!'
9
};
10
11
const text = (score: number, level: number) => `${texts[level]} \n ${score}`;
12
13
export const render = (score: number, level: number) => {
14
const id = 'level' + level;
15
const element = document.getElementById(id);
16
const innerText = text(score, level);
17
if (element) {
18
element.innerText = innerText;
19
} else {
20
const elem = document.createElement('div');
21
elem.id = id;
22
elem.style.zIndex = `${level}`;
23
elem.style.position = 'absolute';
24
elem.style.height = '150px';
25
elem.style.width = '150px';
26
elem.style.borderRadius = '10px';
27
const position = level * 20;
28
elem.style.top = position + 'px';
29
elem.style.left = position + 'px';
30
const col = 100 + position;
31
elem.style.background = `rgb(0,${col},0)`;
32
elem.style.color = 'white';
33
elem.innerText = innerText;
34
elem.style.textAlign = 'center';
35
elem.style.verticalAlign = 'middle';
36
elem.style.lineHeight = '90px';
37
document.body.appendChild(elem);
38
}
39
};
40
41
export const clear = () => (document.body.innerText = '');
Copied!

html

1
<div>How fast can you click?!</div>
Copied!
Last modified 1yr ago