GameStore.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. 'use strict';
  2. const AppDispatcher = require('../dispatcher/AppDispatcher');
  3. const EventEmitter = require('eventemitter2').EventEmitter2;
  4. const GameConstants = require('../constants/GameConstants');
  5. const Chess = require('chess.js').Chess;
  6. const Immutable = require('immutable');
  7. const {List, Map, OrderedMap, Set} = Immutable;
  8. const CHANGE_EVENT = 'change';
  9. var _gameOver = Map({
  10. status: false,
  11. type: null,
  12. winner: null
  13. });
  14. var _capturedPieces = OrderedMap([
  15. ['white', List()],
  16. ['black', List()]
  17. ]);
  18. var _moves = List();
  19. var _promotion = 'q';
  20. var _turn = 'w';
  21. var _chess = new Chess();
  22. const GameStore = Object.assign({}, EventEmitter.prototype, {
  23. getState() {
  24. return {
  25. gameOver: _gameOver,
  26. promotion: _promotion,
  27. turn: _turn
  28. };
  29. },
  30. getCapturedPieces() {
  31. return _capturedPieces;
  32. },
  33. getMoves() {
  34. return _moves;
  35. },
  36. getFEN() {
  37. return _chess.fen();
  38. }
  39. });
  40. function rematch() {
  41. _gameOver = _gameOver
  42. .set('status', false)
  43. .set('winner', null)
  44. .set('type', null);
  45. }
  46. function gameOver(options) {
  47. _gameOver = _gameOver
  48. .set('status', true)
  49. .set('winner', options.winner)
  50. .set('type', options.type);
  51. }
  52. AppDispatcher.register(payload => {
  53. var action = payload.action;
  54. switch (action.actionType) {
  55. case GameConstants.REMATCH:
  56. rematch();
  57. break;
  58. case GameConstants.GAME_OVER:
  59. gameOver(action.options);
  60. break;
  61. case GameConstants.CHANGE_PROMOTION:
  62. _promotion = action.promotion;
  63. break;
  64. default:
  65. return true;
  66. }
  67. GameStore.emit(CHANGE_EVENT);
  68. return true;
  69. });
  70. module.exports = GameStore;