MatchService.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. const io = require('./sockets.js');
  2. const GameMachine = require('../game').GameMachine;
  3. const Factory = require('../game').GameMoves.Factory;
  4. class MatchService {
  5. constructor(socket1, socket2, channel, game) {
  6. this._persistence = false;
  7. this.channel = channel;
  8. this._setupSocket(socket1, channel); // setup events
  9. this._setupSocket(socket2, channel); // setup events
  10. this.machine = new GameMachine(game.setup);
  11. }
  12. reconnect(socket, setup) {
  13. this._setupSocket(socket, this.channel);
  14. let gamedetails = { ...this.machine.getStack(), personal: setup };
  15. console.log(gamedetails.stack.moves);
  16. socket.emit('gameInProgress', gamedetails);
  17. }
  18. _setupSocket(socket) {
  19. //
  20. let token = socket.request._query['token'];
  21. socket.on('broadcast', (data) => this._broadcast(data, this.channel, token, socket));
  22. socket.on('abandon', (data) => this._abandon(data, this.channel));
  23. socket.on('gameOver', (data) => this._gameOver(data, this.channel));
  24. socket.on('dispute', (data) => this._dispute(data, this.channel));
  25. socket.leave('queue', this.errorHandler);
  26. socket.join(this.channel, this.errorHandler);
  27. }
  28. _dropMatch() {
  29. io.in(this.channel).emit('matchFinished');
  30. }
  31. _broadcast(data, channel, token, socket) {
  32. data.timestamp = new Date().getTime();
  33. data.signature = token;
  34. try{
  35. //console.log(data);
  36. let mv = Factory(data);
  37. this.machine.runMove(mv);
  38. this.finished = this.machine.hasFinished();
  39. socket.broadcast.to(channel).emit('move', data);
  40. if(this.finished) {
  41. //
  42. this._dropMatch();
  43. this.onMatchFinished();
  44. }
  45. } catch (e) {
  46. console.log(e);
  47. // throw 'Wrong Move';
  48. }
  49. }
  50. _dispute(data, channel) {
  51. let result;
  52. // result. gameService.dispute(data);
  53. //may change to 'disputeResult'
  54. io.in(channel).emit('result', result);
  55. }
  56. _gameOver(data, channel) {
  57. // TODO this should be emitted ONLY if all 9 moves have been played
  58. // TODO verify move stack (compare with hashed cards)
  59. console.log("[---!!!---]GameOver is called!!! ");
  60. let gameMachine = new GameMachine(data.setup);
  61. let winner = gameMachine.runMatch(data.stack.moves);
  62. console.log("[!!!!--->]Winner is " + winner);
  63. io.in(channel).emit('winner', winner);
  64. }
  65. }
  66. module.exports = MatchService;