ESPTrainer built with Meteor and React

Board.jsx 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import React, { Component } from 'react';
  2. import update from 'react-addons-update';
  3. import ReactTimeout from 'react-timeout';
  4. import BoardLayout from './BoardLayout';
  5. class Board extends Component {
  6. constructor(props) {
  7. super(props);
  8. this.state = {
  9. end: false, win: false,
  10. trials: 0, score: 0,
  11. squares: [ false, false, false, false ],
  12. image: "/images/img1.jpg",
  13. scores: JSON.parse(localStorage.getItem('esp-scores') || "{}")
  14. };
  15. this.actions = [
  16. { label: 'Reset', action: this.reset.bind(this), active: () => true },
  17. { label: 'Pass', action: this.pass.bind(this), active: () => !this.state.end },
  18. ];
  19. this.choices = [0, 1, 2, 3].map(i => this.choice.bind(this, i));
  20. }
  21. fail(corrected) {
  22. this.setState({ squares: update(this.state.squares, { [corrected]: { $set: true } }) });
  23. this.props.setTimeout(() => this.setState({
  24. squares: update(this.state.squares, { [corrected]: { $set: false } })
  25. }), 1000);
  26. }
  27. win() {
  28. this.setState({ win: true, score: this.state.score + 1 });
  29. this.props.setTimeout(() => this.setState({ win: false }), 2000);
  30. }
  31. registerScore(score) {
  32. this.setState({ scores: update(this.state.scores, {
  33. $merge: { [moment().unix()]: score } })
  34. }, () => localStorage.setItem('esp-scores', JSON.stringify(this.state.scores)));
  35. }
  36. choice(answer) {
  37. let corrected = Math.floor(Math.random() * 10) % 4;
  38. this.setState({
  39. trials: this.state.trials + 1,
  40. image: `images/img${this.state.trials + 1}.jpg`,
  41. end: this.state.trials + 1 >= 24
  42. }, () => {
  43. if (this.state.trials >= 24)
  44. this.registerScore(this.state.score);
  45. });
  46. if (answer === corrected)
  47. this.win();
  48. else
  49. this.fail(corrected);
  50. }
  51. reset() {
  52. this.setState({ trials: 0, image: 'images/img0.jpg', score: 0, end: false });
  53. }
  54. pass() {
  55. let corrected = Math.floor(Math.random() * 10) % 4;
  56. this.fail(corrected);
  57. }
  58. render() {
  59. return <BoardLayout win={this.state.win} choices={this.choices} score={this.state.score}
  60. highlighted={this.state.squares} actions={this.actions} active={!this.state.end}
  61. trials={this.state.trials} image={this.state.image} scores={this.state.scores}/>;
  62. }
  63. }
  64. export default ReactTimeout(Board);