-
Notifications
You must be signed in to change notification settings - Fork 0
/
HighestNumber.js
112 lines (99 loc) · 2.41 KB
/
HighestNumber.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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import React from 'react';
import ReactDOM from 'react-dom';
import { TopNumber } from './TopNumber';
import { Display } from './Display';
import { Target } from './Target';
import { random, clone } from './helpers';
const fieldStyle = {
position: 'absolute',
width: 250,
bottom: 60,
left: 10,
height: '60%',
};
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
game: false,
targets: {},
latestClick: 0
};
this.intervals = null;
this.hitTarget = this.hitTarget.bind(this);
this.startGame = this.startGame.bind(this);
this.endGame = this.endGame.bind(this);
}
createTarget(key, ms) {
ms = ms || random(500, 2000);
this.intervals.push(setInterval(function(){
let targets = clone(this.state.targets);
let num = random(1, 1000*1000);
targets[key] = targets[key] != 0 ? 0 : num;
this.setState({ targets: targets });
}.bind(this), ms));
}
hitTarget(e) {
if (e.target.className != 'target') return;
let num = parseInt(e.target.innerText);
for (let target in this.state.targets) {
let key = Math.random().toFixed(4);
this.createTarget(key);
}
this.setState({ latestClick: num });
}
startGame() {
this.createTarget('first', 750);
this.setState({
game: true
});
}
endGame() {
this.intervals.forEach((int) => {
clearInterval(int);
});
this.intervals = [];
this.setState({
game: false,
targets: {},
latestClick: 0
});
}
componentWillMount() {
this.intervals = [];
}
componentDidUpdate(prevProps, prevState) {
if (this.state.latestClick < prevState.latestClick) {
this.endGame();
}
};
render() {
let buttonStyle = {
display: this.state.game ? 'none' : 'inline-block'
};
let targets = [];
for (let key in this.state.targets) {
targets.push(
<Target
number={this.state.targets[key]}
key={key} />
);
}
return (
<div>
<TopNumber number={this.state.latestClick} game={this.state.game} />
<Display number={this.state.latestClick} />
<button onClick={this.startGame} style={buttonStyle}>
New Game
</button>
<div style={fieldStyle} onClick={this.hitTarget}>
{targets}
</div>
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('app')
);