| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- import React, { Component } from 'react';
- import update from 'react-addons-update';
- import ReactTimeout from 'react-timeout';
- import BoardLayout from './BoardLayout';
-
- class Board extends Component {
- constructor(props) {
- super(props);
- this.state = {
- end: false, win: false,
- trials: 0, score: 0,
- squares: [ false, false, false, false ],
- image: "/images/img1.jpg",
- scores: JSON.parse(localStorage.getItem('esp-scores') || "{}")
- };
- this.actions = [
- { label: 'Reset', action: this.reset.bind(this), active: () => true },
- { label: 'Pass', action: this.pass.bind(this), active: () => !this.state.end },
- ];
- this.choices = [0, 1, 2, 3].map(i => this.choice.bind(this, i));
- }
-
- fail(corrected) {
- this.setState({ squares: update(this.state.squares, { [corrected]: { $set: true } }) });
- this.props.setTimeout(() => this.setState({
- squares: update(this.state.squares, { [corrected]: { $set: false } })
- }), 1000);
- }
-
- win() {
- this.setState({ win: true, score: this.state.score + 1 });
- this.props.setTimeout(() => this.setState({ win: false }), 2000);
- }
-
- registerScore(score) {
- this.setState({ scores: update(this.state.scores, {
- $merge: { [moment().unix()]: score } })
- }, () => localStorage.setItem('esp-scores', JSON.stringify(this.state.scores)));
- }
-
- choice(answer) {
- let corrected = Math.floor(Math.random() * 10) % 4;
- this.setState({
- trials: this.state.trials + 1,
- image: `images/img${this.state.trials + 1}.jpg`,
- end: this.state.trials + 1 >= 24
- }, () => {
- if (this.state.trials >= 24)
- this.registerScore(this.state.score);
- });
- if (answer === corrected)
- this.win();
- else
- this.fail(corrected);
- }
-
- reset() {
- this.setState({ trials: 0, image: 'images/img0.jpg', score: 0, end: false });
- }
-
- pass() {
- let corrected = Math.floor(Math.random() * 10) % 4;
- this.fail(corrected);
- }
-
- render() {
- return <BoardLayout win={this.state.win} choices={this.choices} score={this.state.score}
- highlighted={this.state.squares} actions={this.actions} active={!this.state.end}
- trials={this.state.trials} image={this.state.image} scores={this.state.scores}/>;
- }
- }
-
- export default ReactTimeout(Board);
|