ESPTrainer built with Meteor and React

Board.jsx 2.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. { label: 'AddScore', action: () => this.registerScore(Math.floor(Math.random() * 100) % 24), active: () => true }
  19. ];
  20. this.choices = [0, 1, 2, 3].map(i => this.choice.bind(this, i));
  21. }
  22. fail(corrected) {
  23. this.setState({ squares: update(this.state.squares, { [corrected]: { $set: true } }) });
  24. this.props.setTimeout(() => this.setState({
  25. squares: update(this.state.squares, { [corrected]: { $set: false } })
  26. }), 1000);
  27. }
  28. win() {
  29. this.setState({ win: true, score: this.state.score + 1 });
  30. this.props.setTimeout(() => this.setState({ win: false }), 2000);
  31. }
  32. registerScore(score) {
  33. this.setState({ scores: update(this.state.scores, {
  34. $merge: { [moment().unix()]: score } })
  35. }, () => localStorage.setItem('esp-scores', JSON.stringify(this.state.scores)));
  36. }
  37. choice(answer) {
  38. let corrected = Math.floor(Math.random() * 10) % 4;
  39. this.setState({
  40. trials: this.state.trials + 1,
  41. image: `images/img${this.state.trials + 1}.jpg`,
  42. end: this.state.trials + 1 >= 24
  43. }, () => {
  44. if (this.state.trials >= 24)
  45. this.registerScore(this.state.score);
  46. });
  47. if (answer === corrected)
  48. this.win();
  49. else
  50. this.fail(corrected);
  51. }
  52. reset() {
  53. this.setState({ trials: 0, image: 'images/img0.jpg', score: 0, end: false });
  54. }
  55. pass() {
  56. let corrected = Math.floor(Math.random() * 10) % 4;
  57. this.fail(corrected);
  58. }
  59. render() {
  60. return <BoardLayout win={this.state.win} choices={this.choices} score={this.state.score}
  61. highlighted={this.state.squares} actions={this.actions} active={!this.state.end}
  62. trials={this.state.trials} image={this.state.image} scores={this.state.scores}/>;
  63. }
  64. }
  65. export default ReactTimeout(Board);