const io = require('./sockets.js'); const GameMachine = require('../game').GameMachine; const Factory = require('../game').GameMoves.Factory; class MatchService { constructor(socket1, socket2, channel, game) { this._persistence = false; this.channel = channel; this._setupSocket(socket1, channel); // setup events this._setupSocket(socket2, channel); // setup events this.machine = new GameMachine(game.setup); } reconnect(socket, setup) { this._setupSocket(socket, this.channel); let gamedetails = { ...this.machine.getStack(), personal: setup }; console.log(gamedetails.stack.moves); socket.emit('gameInProgress', gamedetails); } _setupSocket(socket) { // let token = socket.request._query['token']; socket.on('broadcast', (data) => this._broadcast(data, this.channel, token, socket)); socket.on('abandon', (data) => this._abandon(data, this.channel)); socket.on('gameOver', (data) => this._gameOver(data, this.channel)); socket.on('dispute', (data) => this._dispute(data, this.channel)); socket.leave('queue', this.errorHandler); socket.join(this.channel, this.errorHandler); } _dropMatch() { io.in(this.channel).emit('matchFinished'); } _broadcast(data, channel, token, socket) { data.timestamp = new Date().getTime(); data.signature = token; try{ //console.log(data); let mv = Factory(data); this.machine.runMove(mv); this.finished = this.machine.hasFinished(); socket.broadcast.to(channel).emit('move', data); if(this.finished) { // this._dropMatch(); this.onMatchFinished(); } } catch (e) { console.log(e); // throw 'Wrong Move'; } } _dispute(data, channel) { let result; // result. gameService.dispute(data); //may change to 'disputeResult' io.in(channel).emit('result', result); } _gameOver(data, channel) { // TODO this should be emitted ONLY if all 9 moves have been played // TODO verify move stack (compare with hashed cards) console.log("[---!!!---]GameOver is called!!! "); let gameMachine = new GameMachine(data.setup); let winner = gameMachine.runMatch(data.stack.moves); console.log("[!!!!--->]Winner is " + winner); io.in(channel).emit('winner', winner); } } module.exports = MatchService;