"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = OnlineDuelSync; var _duelController = _interopRequireDefault(require("../client-server-shared/duel-controller")); var fs = require('fs'); function OnlineDuelSync(ioServer, mariadbConnector, gameId, firstPlayer, isNewGame, gameOptions) { var io = ioServer; var mdb = mariadbConnector; var isNew = isNewGame; var players = new Map(); var duelController = new _duelController.default(); players.set(firstPlayer.playerName, firstPlayer); // If not new game, set status to PLAYING right now // Otherwise we wait second player if (!isNew) { mdb.updateGameStatus(gameId, 'PLAYING'); duelController.resumeGame(); } var loadGameData = function loadGameData() { var gameDetails = {}; try { gameDetails = mdb.getGameById(gameId); } catch (err) { console.log('Error retreiving game : ', err.message); } return gameDetails; }; var chat = function chat(name, message) { io.to(gameId).emit('message', { from: name, text: message }); }; firstPlayer.getSocket().join(gameId, function () { chat(firstPlayer.playerName, firstPlayer.playerName + ' has entered the game, waiting for second player...'); }).emit('update-game-data', loadGameData().game_data).on('chat', function (message) { chat(firstPlayer.playerName, message); }); var addPlayer = function addPlayer(player) { var res = true; if (players.size === 1) { if (players.has(player.playerName)) { console.log('ERROR : this player is already there ! ', player.playerName); return false; } players.set(player.playerName, player); // Both players connected to new game, set status to PLAYING if (isNew) { isNew = false; mdb.updateGameStatus(gameId, 'PLAYING', player.playerName); var allHeroesJson = JSON.parse(fs.readFileSync('../../src/server-shared/all-heroes.json')); duelController.startNewGame(firstPlayer.playerName, player.playerName, allHeroesJson, gameOptions); } player.getSocket().join(gameId, function () { chat(player.playerName, player.playerName + ' has entered the game'); }).emit('update-game-data', loadGameData().game_data).on('chat', function (message) { chat(player.playerName, message); }); } else { console.log('Already 2 players, weird :' + player.playerName + ' was trying to join : ', players); res = false; } return res; }; var playerLeft = function playerLeft(player, disconnected) { var playerLeaving = players.get(player.playerName); if (playerLeaving) { if (!disconnected) { playerLeaving.getSocket().leave(gameId); } chat(player.playerName, player.playerName + ' has left the game'); players.delete(player.playerName); } }; var hasPlayers = function hasPlayers() { return players.size > 0; }; return { addPlayer: addPlayer, playerLeft: playerLeft, hasPlayers: hasPlayers }; } //# sourceMappingURL=online-duel-sync.js.map