ESPTrainer built with Meteor and React

Board.jsx 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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,
  10. win: false,
  11. trials: 0,
  12. score: 0,
  13. squares: [ false, false, false, false ],
  14. image: "/images/img1.jpg"
  15. };
  16. this.actions = [
  17. { label: 'Reset', action: this.reset.bind(this), active: () => true },
  18. { label: 'Pass', action: this.pass.bind(this), active: () => !this.state.end }
  19. ];
  20. this.choices = [];
  21. [0, 1, 2, 3].map(i => this.choices.push(this.choice.bind(this, i)));
  22. }
  23. fail(corrected) {
  24. this.setState({ squares: update(this.state.squares, { [corrected]: { $set: true } }) });
  25. this.props.setTimeout(() => this.setState({
  26. squares: update(this.state.squares, { [corrected]: { $set: false } })
  27. }), 1000);
  28. }
  29. win() {
  30. this.setState({ win: true, score: this.state.score + 1 });
  31. this.props.setTimeout(() => this.setState({ win: false }), 2000);
  32. }
  33. choice(answer) {
  34. let corrected = Math.floor(Math.random() * 10) % 4;
  35. this.setState({
  36. trials: this.state.trials + 1,
  37. image: `images/img${this.state.trials + 1}.jpg`,
  38. end: this.state.trials + 1 >= 24
  39. });
  40. if (answer === corrected)
  41. this.win();
  42. else
  43. this.fail(corrected);
  44. }
  45. reset() {
  46. this.setState({ trials: 0, image: 'images/img0.jpg', score: 0 });
  47. }
  48. pass() {
  49. let corrected = Math.floor(Math.random() * 10) % 4;
  50. this.fail(corrected);
  51. }
  52. render() {
  53. return <BoardLayout win={this.state.win} choices={this.choices} score={this.state.score}
  54. highlighted={this.state.squares} actions={this.actions} active={!this.state.end}
  55. trials={this.state.trials} image={this.state.image} />;
  56. }
  57. }
  58. export default ReactTimeout(Board);