var glob = require('glob'), fs = require('fs'), crypto = require('crypto'); commands = require('./commands'); session = {}; class Core { constructor() { this.timerId = -1; this.lastTime = 0; } load() { session.players = []; session.playerIndex = 1; if(this.timerId != -1 ) { clearInterval(this.timerId); } this.lastTime = new Date().getTime(); //todo: populate rooms this.timerId = setInterval(function() { core.tick(new Date().getTime()); }, 250); } handleInput(player, input) { var action = input.action; for(var commanderClass in commands) { var commander = new commands[commanderClass](); if (typeof commander[action] == 'function') { try { if(commander[action](player, input)) { return true; } } catch (error) { console.error("Exception in command " + commanderClass, error, error.stack); } } } throw new Error("Unhandled Command"); return true; } tick(time) { var delta = this.getUpdateRate(this.lastTime, time); this.lastTime = time; try { //loop over tick-able items for(var i in session.players) { var player = session.players[i]; if(player == null) { continue; } player.update(delta); } } catch (error) { console.error("Tick error", error, error.stack); } } sendUpdateToAll(sender) { for(var i in session.players) { var player = session.players[i]; if(player == null) { continue; } player.sendUpdate(sender); } } sendToAll(data) { for(var i in session.players) { var player = session.players[i]; if(player == null) { continue; } player.sendMessage(data); } } getUpdateRate(start, stop) { return (stop - start) / 16; } getColor() { var colors = [ "#DD3333", "#DDDD33", "#33DD33", "#33DDDD", "#3333DD", "#333333", ]; return colors[parseInt(Math.random() * colors.length)]; } attachPlayer(player) { player.id = session.playerIndex++; player.shipColor = this.getColor(); player.playerName = "Player " + player.id; for(var i in session.players) { var other = session.players[i]; if(other == null) { continue; } player.sendUpdate(other); } session.players[player.id] = player; core.sendUpdateToAll(player); } removePlayer(player) { session.players[session.players.indexOf(player)] = null; core.sendToAll({"remove": player.id}); } rollRandom(probabilitySet) { var rollValue = parseInt(Math.random() * 100) + 1; var probabilityTotal = 0; var sortedSet = probabilitySet.sort(function(a, b) { return (a.probability < b.probability) ? 1 : ((a.probability > b.probability) ? -1 : 0); }); for(var index in sortedSet) { var row = sortedSet[index]; probabilityTotal += row.probability; if(rollValue <= probabilityTotal) { return row.value; } } } } module.exports = new Core();