'use strict'; import PlayerId from './players/player-id'; import DuelController from './game-server/duel-controller'; console.log('Starting 12 heroes server'); const io = require('socket.io'); const server = io.listen(4000); let players = []; const authorizedPlayersNames = ["jojo", "mart", "lily"]; let authorizedPlayers = new Map(); let connectedPlayers = new Map(); authorizedPlayersNames.forEach(name => { authorizedPlayers.set(name, new PlayerId(name)); }); let addNewPlayer = function (playerSocket, playerName) { console.log('players length : ' + players.length + ' : ' + players); if (players.length < 2) { let newPlayer = new PlayerId(playerSocket, playerName); console.log('push player : ' + newPlayer); players.push(newPlayer); } if (players.length === 2) { let duelController = new DuelController(players[0], players[1]); } }; server.on('connection', function (socket) { console.log("A player connected with id : " + socket.id); socket.on('disconnect', (reason) => { if (reason === 'client namespace disconnect') { console.log("A player disconnected with id : " + socket.id); let playerName = connectedPlayers.get(socket.id); if (playerName) { connectedPlayers.delete(socket.id); authorizedPlayers.get(playerName).setConnected(false); authorizedPlayers.get(playerName).setSocket(null); console.log(playerName + " disconnected"); } } else { console.log("disconnected unexpectidly with reason : " + reason); } }); socket.on('connect', () => { console.log("Connected to server"); }); socket.on('auth', (playerName, callback) => { console.log(' Received auth message, player name : ' + playerName); let response = {}; let kickout = false; if (!authorizedPlayersNames.includes(playerName)) { response = { res: "ko", message: playerName + " Not found" }; kickout = true; } // If the player is already connected and active else if (authorizedPlayers.get(playerName).isConnected() && authorizedPlayers.get(playerName).getSocket().connected) { response = { res: "ko", message: playerName + " already connected" }; kickout = true; } else { // Player marked as connected but socket is down if (authorizedPlayers.get(playerName).isConnected()) { authorizedPlayers.get(playerName).getSocket().disconnect(true); } response = { res: "ok", message: playerName + " connected" }; authorizedPlayers.get(playerName).setConnected(true); authorizedPlayers.get(playerName).setSocket(socket); connectedPlayers.set(socket.id, playerName); } callback(response); if (kickout === true) { setTimeout(() => { socket.disconnect(true); }, 600); } }); socket.on('games-list', (playerName, callback) => { console.log(' Received games-list message, player name : ' + playerName); let games= { game1: {p1:"jojo", p2:'lily',mode:'faction', rules:[]}, game2: {p1:"mart", p2:'',mode:'tournament', rules:['popularity', 'discard']}, game3: {p1:"jojo", p2:'mart',mode:'draft', rules:['discard']} }; let response = { res: "ok", message: games }; callback(response); }); });