From 89c4d168c3b84e3510f76f1e3922ea2e49a3bc74 Mon Sep 17 00:00:00 2001 From: Barbosik Date: Fri, 15 Jul 2016 08:11:06 +0200 Subject: [PATCH] fix inconsistent code formatting (use CR-LF line ending; 4x space tab) --- CONTRIBUTING.md | 2 +- README.md | 4 +- package.json | 48 +- src/GameServer.js | 140 ++-- src/PacketHandler.js | 10 +- src/PlayerTracker.js | 58 +- src/ai/BotLoader.js | 100 +-- src/ai/BotPlayer.js | 40 +- src/ai/FakeSocket.js | 6 +- src/ai/Readme.txt | 2 +- src/entity/Cell.js | 26 +- src/entity/EjectedMass.js | 46 +- src/entity/Food.js | 6 +- src/entity/MotherCell.js | 2 +- src/entity/PlayerCell.js | 8 +- src/entity/Virus.js | 106 +-- src/entity/index.js | 2 +- src/gamemodes/Experimental.js | 20 +- src/gamemodes/FFA.js | 18 +- src/gamemodes/HungerGames.js | 40 +- src/gamemodes/Mode.js | 104 +-- src/gamemodes/Rainbow.js | 22 +- src/gamemodes/TeamX.js | 88 +-- src/gamemodes/TeamZ.js | 354 ++++----- src/gamemodes/Teams.js | 62 +- src/gamemodes/Tournament.js | 494 ++++++------- src/gamemodes/Zombie.js | 36 +- src/gamemodes/index.js | 22 +- src/index.js | 170 ++--- src/modules/CommandList.js | 1228 +++++++++++++++---------------- src/modules/Logger.js | 246 +++---- src/modules/PlayerCommand.js | 176 ++--- src/modules/ini.js | 450 +++++------ src/packet/AddNode.js | 4 +- src/packet/BinaryReader.js | 4 +- src/packet/ChatMessage.js | 4 +- src/packet/ClearAll.js | 2 +- src/packet/DrawLine.js | 4 +- src/packet/SetBorder.js | 2 +- src/packet/UpdateLeaderboard.js | 6 +- src/packet/UpdateNodes.js | 10 +- src/packet/UpdatePosition.js | 4 +- src/packet/index.js | 2 +- src/userRoles.json | 38 +- 44 files changed, 2108 insertions(+), 2108 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index de613bdbc..64d6d48b7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -16,7 +16,7 @@ Contributions are appreciated in the form of pull requests. However, to maintain ... } ``` -* Unix-style line endings should be used (`\n`). +* CR-LF line endings should be used (`\r\n`). * Please leave a blank line at the end of each file. * Conditional/loop statements (`if`, `for`, `while`, etc.) should always use braces, and the opening brace should be placed on the same line as the statement. * There should be a space after a conditional/loop statement and before the condition, as well as a space after the condition and before the brace. Example: diff --git a/README.md b/README.md index b02d479e3..2a34a8d0c 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ -# MultiOgar +# MultiOgar Ogar game server with fast and smooth vanilla physics and multi-protocol support. -Current version: **1.2.42** +Current version: **1.2.43** ## Project Info ![Language](https://img.shields.io/badge/language-node.js-yellow.svg) diff --git a/package.json b/package.json index 39848ae10..fa3c5eaa2 100644 --- a/package.json +++ b/package.json @@ -1,25 +1,25 @@ -{ - "name": "MultiOgar", - "version": "1.2.42", - "description": "Open source Ogar server", - "author": "Barbosik (https://github.com/Barbosik/MultiOgar)", - "homepage": "https://github.com/Barbosik/MultiOgar", - "license": "Apache-2.0", - "main": "src/index.js", - "dependencies": { - "quad-node": "^1.0.5", - "vector2-node": "latest", - "ws": "latest" - }, - "devDependencies": {}, - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1" - }, - "repository": { - "type": "git", - "url": "https://github.com/Barbosik/MultiOgar" - }, - "bugs": { - "url": "https://github.com/Barbosik/MultiOgar/issues" - } +{ + "name": "MultiOgar", + "version": "1.2.43", + "description": "Open source Ogar server", + "author": "Barbosik (https://github.com/Barbosik/MultiOgar)", + "homepage": "https://github.com/Barbosik/MultiOgar", + "license": "Apache-2.0", + "main": "src/index.js", + "dependencies": { + "quad-node": "^1.0.5", + "vector2-node": "latest", + "ws": "latest" + }, + "devDependencies": {}, + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "https://github.com/Barbosik/MultiOgar" + }, + "bugs": { + "url": "https://github.com/Barbosik/MultiOgar/issues" + } } diff --git a/src/GameServer.js b/src/GameServer.js index 8463dcae0..c1fd08217 100644 --- a/src/GameServer.js +++ b/src/GameServer.js @@ -1,4 +1,4 @@ -// Library imports +// Library imports var WebSocket = require('ws'); var http = require('http'); var fs = require("fs"); @@ -36,15 +36,15 @@ function GameServer() { this.nodesVirus = []; // Virus nodes this.nodesEjected = []; // Ejected mass nodes this.quadTree = null; - + this.currentFood = 0; this.movingNodes = []; // For move engine this.leaderboard = []; this.leaderboardType = -1; // no type - + this.bots = new BotLoader(this); this.commands; // Command handler - + // Main loop tick this.startTime = +new Date; this.timeStamp = 0; @@ -56,7 +56,7 @@ function GameServer() { this.tickCounter = 0; this.setBorder(10000, 10000); - + // Config this.config = { logVerbosity: 4, // Console log level (0=NONE; 1=FATAL; 2=ERROR; 3=WARN; 4=INFO; 5=DEBUG) @@ -145,7 +145,7 @@ function GameServer() { module.exports = GameServer; -GameServer.prototype.start = function() { +GameServer.prototype.start = function () { this.timerLoopBind = this.timerLoop.bind(this); this.mainLoopBind = this.mainLoop.bind(this); @@ -155,7 +155,7 @@ GameServer.prototype.start = function() { var dirSsl = path.join(path.dirname(module.filename), '../ssl'); var pathKey = path.join(dirSsl, 'key.pem'); var pathCert = path.join(dirSsl, 'cert.pem'); - + if (fs.existsSync(pathKey) && fs.existsSync(pathCert)) { // HTTP/TLS var options = { @@ -178,7 +178,7 @@ GameServer.prototype.start = function() { this.wsServer.on('error', this.onServerSocketError.bind(this)); this.wsServer.on('connection', this.onClientSocketOpen.bind(this)); this.httpServer.listen(this.config.serverPort, this.config.serverBind, this.onHttpServerOpen.bind(this)); - + this.startStatsServer(this.config.serverStatsPort); }; @@ -270,7 +270,7 @@ GameServer.prototype.onClientSocketOpen = function (ws) { // Minion detection if (this.config.serverMinionThreshold) { - if ((ws.lastAliveTime - this.startTime)/1000 >= this.config.serverMinionIgnoreTime) { + if ((ws.lastAliveTime - this.startTime) / 1000 >= this.config.serverMinionIgnoreTime) { if (this.minionTest.length >= this.config.serverMinionThreshold) { ws.playerTracker.isMinion = true; for (var i = 0; i < this.minionTest.length; i++) { @@ -297,8 +297,8 @@ GameServer.prototype.onClientSocketClose = function (ws, code) { ws.sendPacket = function (data) { }; ws.closeReason = { code: ws._closeCode, message: ws._closeMessage }; ws.closeTime = +new Date; - Logger.write("DISCONNECTED " + ws.remoteAddress + ":" + ws.remotePort + ", code: " + ws._closeCode + ", reason: \"" + ws._closeMessage + "\", name: \""+ws.playerTracker.getName()+"\""); - + Logger.write("DISCONNECTED " + ws.remoteAddress + ":" + ws.remotePort + ", code: " + ws._closeCode + ", reason: \"" + ws._closeMessage + "\", name: \"" + ws.playerTracker.getName() + "\""); + // disconnected effect var color = this.getGrayColor(ws.playerTracker.getColor()); ws.playerTracker.setColor(color); @@ -316,7 +316,7 @@ GameServer.prototype.onClientSocketMessage = function (ws, message) { ws.packetHandler.handleMessage(message); }; -GameServer.prototype.setBorder = function(width, height) { +GameServer.prototype.setBorder = function (width, height) { var hw = width / 2; var hh = height / 2; this.border = { @@ -339,7 +339,7 @@ GameServer.prototype.getMode = function () { return this.gameMode; }; -GameServer.prototype.getNextNodeId = function() { +GameServer.prototype.getNextNodeId = function () { // Resets integer if (this.lastNodeId > 2147483647) { this.lastNodeId = 1; @@ -347,7 +347,7 @@ GameServer.prototype.getNextNodeId = function() { return this.lastNodeId++ >>> 0; }; -GameServer.prototype.getNewPlayerID = function() { +GameServer.prototype.getNewPlayerID = function () { // Resets integer if (this.lastPlayerId > 2147483647) { this.lastPlayerId = 1; @@ -355,7 +355,7 @@ GameServer.prototype.getNewPlayerID = function() { return this.lastPlayerId++ >>> 0; }; -GameServer.prototype.getRandomPosition = function() { +GameServer.prototype.getRandomPosition = function () { return { x: Math.floor(this.border.minx + this.border.width * Math.random()), y: Math.floor(this.border.miny + this.border.height * Math.random()) @@ -371,7 +371,7 @@ GameServer.prototype.getGrayColor = function (rgb) { }; }; -GameServer.prototype.getRandomColor = function() { +GameServer.prototype.getRandomColor = function () { var h = 360 * Math.random(); var s = 248 / 255; var v = 1; @@ -434,7 +434,7 @@ GameServer.prototype.updateNodeQuad = function (node) { }; -GameServer.prototype.addNode = function(node) { +GameServer.prototype.addNode = function (node) { node.quadItem = { cell: node, x: node.position.x, @@ -450,19 +450,19 @@ GameServer.prototype.addNode = function(node) { this.quadTree.insert(node.quadItem); this.nodes.push(node); - + // Adds to the owning player's screen if (node.owner) { node.setColor(node.owner.getColor()); node.owner.cells.push(node); node.owner.socket.sendPacket(new Packet.AddNode(node.owner, node)); } - + // Special on-add actions node.onAdd(this); }; -GameServer.prototype.removeNode = function(node) { +GameServer.prototype.removeNode = function (node) { if (node.quadItem == null) { throw new TypeError("GameServer.removeNode: attempt to remove invalid node!"); } @@ -475,13 +475,13 @@ GameServer.prototype.removeNode = function(node) { if (index != -1) { this.nodes.splice(index, 1); } - + // Remove from moving cells list index = this.movingNodes.indexOf(node); if (index != -1) { this.movingNodes.splice(index, 1); } - + // Special on-remove actions node.onRemove(this); }; @@ -578,7 +578,7 @@ GameServer.prototype.sendChatMessage = function (from, to, message) { if (to == null || to == client.playerTracker) client.sendPacket(new Packet.ChatMessage(from, message)); } -}; +}; GameServer.prototype.timerLoop = function () { var timeStep = this.updateTimeAvg >> 0; @@ -588,7 +588,7 @@ GameServer.prototype.timerLoop = function () { var ts = new Date().getTime(); var dt = ts - this.timeStamp; if (dt < timeStep - 5) { - setTimeout(this.timerLoopBind, ((timeStep-5) - dt) >> 0); + setTimeout(this.timerLoopBind, ((timeStep - 5) - dt) >> 0); return; } if (dt < timeStep - 1) { @@ -616,7 +616,7 @@ GameServer.prototype.timerLoop = function () { setTimeout(this.timerLoopBind, 0); }; -GameServer.prototype.mainLoop = function() { +GameServer.prototype.mainLoop = function () { var tStart = process.hrtime(); // Loop main functions @@ -627,21 +627,21 @@ GameServer.prototype.mainLoop = function() { this.updateVirus(); // Spawn viruses } this.gameMode.onTick(this); - if (((this.getTick()+3) % (1000 / 40)) == 0) { + if (((this.getTick() + 3) % (1000 / 40)) == 0) { // once per second this.updateMassDecay(); } } this.updateClients(); - - if (((this.getTick()+7) % (1000 / 40)) == 0) { + + if (((this.getTick() + 7) % (1000 / 40)) == 0) { // once per second this.updateLeaderboard(); } // ping server tracker - if (this.config.serverTracker && (this.getTick() % (30000/40)) == 0) { + if (this.config.serverTracker && (this.getTick() % (30000 / 40)) == 0) { // once per 30 seconds this.pingServerTracker(); } @@ -653,14 +653,14 @@ GameServer.prototype.mainLoop = function() { this.updateTime = tEnd[0] * 1000 + tEnd[1] / 1000000; }; -GameServer.prototype.startingFood = function() { +GameServer.prototype.startingFood = function () { // Spawns the starting amount of food cells for (var i = 0; i < this.config.foodMinAmount; i++) { this.spawnFood(); } }; -GameServer.prototype.updateFood = function() { +GameServer.prototype.updateFood = function () { var maxCount = this.config.foodMinAmount - this.currentFood; var spawnCount = Math.min(maxCount, this.config.foodSpawnAmount); for (var i = 0; i < spawnCount; i++) { @@ -676,7 +676,7 @@ GameServer.prototype.updateVirus = function () { } }; -GameServer.prototype.spawnFood = function() { +GameServer.prototype.spawnFood = function () { var cell = new Entity.Food(this, null, this.getRandomPosition(), this.config.foodMinSize); if (this.config.foodMassGrow) { var size = cell.getSize(); @@ -699,7 +699,7 @@ GameServer.prototype.spawnVirus = function () { this.addNode(v); }; -GameServer.prototype.spawnPlayer = function(player, pos, size) { +GameServer.prototype.spawnPlayer = function (player, pos, size) { // Check if can spawn from ejected mass if (!pos && this.config.ejectSpawnPlayer && this.nodesEjected.length > 0) { if (Math.random() >= 0.5) { @@ -730,11 +730,11 @@ GameServer.prototype.spawnPlayer = function(player, pos, size) { // Get starting mass size = this.config.playerStartSize; } - + // Spawn player and add to world var cell = new Entity.PlayerCell(this, player, pos, size); this.addNode(cell); - + // Set initial mouse coords player.mouse = { x: pos.x, @@ -759,7 +759,7 @@ GameServer.prototype.willCollide = function (pos, size) { // Checks cells for collision. // Returns collision manifold or null if there is no collision -GameServer.prototype.checkCellCollision = function(cell, check) { +GameServer.prototype.checkCellCollision = function (cell, check) { var r = cell.getSize() + check.getSize(); var dx = check.position.x - cell.position.x; var dy = check.position.y - cell.position.y; @@ -910,7 +910,7 @@ GameServer.prototype.resolveCollision = function (manifold) { // update bounds this.updateNodeQuad(maxCell); } - + // Remove cell minCell.setKiller(maxCell); this.removeNode(minCell); @@ -1051,7 +1051,7 @@ GameServer.prototype.updateMoveEngine = function () { } }); } - + // resolve rigid body collisions for (var k = 0; k < rigidCollisions.length; k++) { var c = rigidCollisions[k]; @@ -1086,7 +1086,7 @@ GameServer.prototype.splitMass = function (mass, count) { // check maxCount var maxCount = count; var curMass = mass; - while (maxCount > 1 && curMass / (maxCount-1) < throwMass) { + while (maxCount > 1 && curMass / (maxCount - 1) < throwMass) { maxCount = maxCount / 2 >>> 0; } if (maxCount < 2) { @@ -1156,8 +1156,8 @@ GameServer.prototype.splitMass = function (mass, count) { } if (restCount > 0) { splitMass = curMass / restCount; - if (splitMass < throwMass-0.001) { - Logger.warn("GameServer.splitMass: throwMass-splitMass = "+(throwMass-splitMass).toFixed(3)+" (" + mass.toFixed(4) + ", " + count + ")"); + if (splitMass < throwMass - 0.001) { + Logger.warn("GameServer.splitMass: throwMass-splitMass = " + (throwMass - splitMass).toFixed(3) + " (" + mass.toFixed(4) + ", " + count + ")"); } while (restCount > 0) { masses.push(splitMass); @@ -1176,7 +1176,7 @@ GameServer.prototype.splitMass = function (mass, count) { return masses; }; -GameServer.prototype.splitCells = function(client) { +GameServer.prototype.splitCells = function (client) { // it seems that vanilla uses order by cell age var cellToSplit = []; for (var i = 0; i < client.cells.length; i++) { @@ -1200,7 +1200,7 @@ GameServer.prototype.splitCells = function(client) { } var angle = Math.atan2(dx, dy); if (isNaN(angle)) angle = Math.PI / 2; - + if (this.splitPlayerCell(client, cell, angle, null)) { splitCells++; } @@ -1210,12 +1210,12 @@ GameServer.prototype.splitCells = function(client) { // TODO: replace mass with size (Virus) GameServer.prototype.splitPlayerCell = function (client, parent, angle, mass) { // Returns boolean whether a cell has been split or not. You can use this in the future. - + if (client.cells.length >= this.config.playerMaxCells) { // Player cell limit return false; } - + var size1 = 0; var size2 = 0; if (mass == null) { @@ -1247,7 +1247,7 @@ GameServer.prototype.splitPlayerCell = function (client, parent, angle, mass) { return true; }; -GameServer.prototype.canEjectMass = function(client) { +GameServer.prototype.canEjectMass = function (client) { var tick = this.getTick(); if (client.lastEject == null) { // first eject @@ -1263,16 +1263,16 @@ GameServer.prototype.canEjectMass = function(client) { return true; }; -GameServer.prototype.ejectMass = function(client) { +GameServer.prototype.ejectMass = function (client) { if (!this.canEjectMass(client)) return; for (var i = 0; i < client.cells.length; i++) { var cell = client.cells[i]; - + if (!cell) { continue; } - + if (cell.getSize() < this.config.playerMinSplitSize) { continue; } @@ -1283,7 +1283,7 @@ GameServer.prototype.ejectMass = function(client) { continue; } var size1 = Math.sqrt(sizeSquared); - + var dx = client.mouse.x - cell.position.x; var dy = client.mouse.y - cell.position.y; var dl = dx * dx + dy * dy; @@ -1298,7 +1298,7 @@ GameServer.prototype.ejectMass = function(client) { // Remove mass from parent cell first cell.setSize(size1); - + // Get starting position var pos = { x: cell.position.x + dx * cell.getSize(), @@ -1310,31 +1310,31 @@ GameServer.prototype.ejectMass = function(client) { // Randomize angle angle += (Math.random() * 0.6) - 0.3; - + // Create cell var ejected = new Entity.EjectedMass(this, null, pos, size2); ejected.ejector = cell; ejected.setColor(cell.getColor()); ejected.setBoost(780, angle); - + this.addNode(ejected); } }; -GameServer.prototype.shootVirus = function(parent, angle) { +GameServer.prototype.shootVirus = function (parent, angle) { var parentPos = { x: parent.position.x, y: parent.position.y, }; - + var newVirus = new Entity.Virus(this, null, parentPos, this.config.virusMinSize); newVirus.setBoost(780, angle); - + // Add to moving cells list this.addNode(newVirus); }; -GameServer.prototype.getNearestVirus = function(cell) { +GameServer.prototype.getNearestVirus = function (cell) { // Loop through all viruses on the map. There is probably a more efficient way of doing this but whatever for (var i = 0; i < this.nodesVirus.length; i++) { var check = this.nodesVirus[i]; @@ -1345,7 +1345,7 @@ GameServer.prototype.getNearestVirus = function(cell) { } }; -GameServer.prototype.updateMassDecay = function() { +GameServer.prototype.updateMassDecay = function () { if (!this.config.playerDecayRate) { return; } @@ -1445,7 +1445,7 @@ GameServer.prototype.changeConfig = function (name, value) { this.config.playerMinSize = Math.max(32, this.config.playerMinSize); Logger.setVerbosity(this.config.logVerbosity); Logger.setFileVerbosity(this.config.logFileVerbosity); - + Logger.print("Set " + name + " = " + this.config[name]); }; @@ -1578,7 +1578,7 @@ GameServer.prototype.banIp = function (ip) { return; } this.ipBanList.push(ip); - if (ipBin[2]=="*" || ipBin[3] == "*") { + if (ipBin[2] == "*" || ipBin[3] == "*") { Logger.print("The IP sub-net " + ip + " has been banned"); } else { Logger.print("The IP " + ip + " has been banned"); @@ -1637,23 +1637,23 @@ GameServer.prototype.kickId = function (id) { if (id == 0) Logger.warn("No players to kick!"); else - Logger.warn("Player with ID "+id+" not found!"); + Logger.warn("Player with ID " + id + " not found!"); }; // Stats server -GameServer.prototype.startStatsServer = function(port) { +GameServer.prototype.startStatsServer = function (port) { // Do not start the server if the port is negative if (port < 1) { return; } - + // Create stats this.stats = "Test"; this.getStats(); - + // Show stats - this.httpServer = http.createServer(function(req, res) { + this.httpServer = http.createServer(function (req, res) { res.setHeader('Access-Control-Allow-Origin', '*'); res.writeHead(200); res.end(this.stats); @@ -1661,7 +1661,7 @@ GameServer.prototype.startStatsServer = function(port) { this.httpServer.on('error', function (err) { Logger.error("Stats Server: " + err.message); }); - + var getStatsBind = this.getStats.bind(this); this.httpServer.listen(port, function () { // Stats server @@ -1670,7 +1670,7 @@ GameServer.prototype.startStatsServer = function(port) { }.bind(this)); }; -GameServer.prototype.getStats = function() { +GameServer.prototype.getStats = function () { // Get server statistics var totalPlayers = 0; var alivePlayers = 0; @@ -1696,16 +1696,16 @@ GameServer.prototype.getStats = function() { 'alive': alivePlayers, 'spectators': spectatePlayers, 'update_time': this.updateTimeAvg.toFixed(3), - 'uptime': Math.round((new Date().getTime() - this.startTime)/1000/60), + 'uptime': Math.round((new Date().getTime() - this.startTime) / 1000 / 60), 'start_time': this.startTime }; this.stats = JSON.stringify(s); }; // Custom prototype functions -WebSocket.prototype.sendPacket = function(packet) { +WebSocket.prototype.sendPacket = function (packet) { if (packet == null) return; - + //if (this.readyState == WebSocket.OPEN && (this._socket.bufferSize == 0) && packet.build) { if (this.readyState == WebSocket.OPEN) { var buffer = packet.build(this.playerTracker.socket.packetHandler.protocol); diff --git a/src/PacketHandler.js b/src/PacketHandler.js index 2571cf8ea..d10221257 100644 --- a/src/PacketHandler.js +++ b/src/PacketHandler.js @@ -1,4 +1,4 @@ -var pjson = require('../package.json'); +var pjson = require('../package.json'); var Packet = require('./packet'); var BinaryReader = require('./packet/BinaryReader'); @@ -8,7 +8,7 @@ function PacketHandler(gameServer, socket) { this.protocol = 0; this.isHandshakePassed = false; this.lastChatTick = 0; - + this.pressQ = false; this.pressW = false; this.pressSpace = false; @@ -17,7 +17,7 @@ function PacketHandler(gameServer, socket) { module.exports = PacketHandler; -PacketHandler.prototype.handleMessage = function(message) { +PacketHandler.prototype.handleMessage = function (message) { // Validation if (message.length == 0) { return; @@ -29,7 +29,7 @@ PacketHandler.prototype.handleMessage = function(message) { } // no handshake? - if (!this.isHandshakePassed) { + if (!this.isHandshakePassed) { if (message[0] != 254 || message.length != 5) { // wait handshake return; @@ -68,7 +68,7 @@ PacketHandler.prototype.handleMessage = function(message) { var reader = new BinaryReader(message); var packetId = reader.readUInt8(); - + switch (packetId) { case 0: if (this.socket.playerTracker.cells.length > 0) { diff --git a/src/PlayerTracker.js b/src/PlayerTracker.js index 4d3474d45..ef5a03e1e 100644 --- a/src/PlayerTracker.js +++ b/src/PlayerTracker.js @@ -1,4 +1,4 @@ -var Packet = require('./packet'); +var Packet = require('./packet'); var GameServer = require('./GameServer'); var BinaryWriter = require("./packet/BinaryWriter"); var UserRoleEnum = require("./enum/UserRoleEnum"); @@ -25,19 +25,19 @@ function PlayerTracker(gameServer, socket) { this._scale = 1; this.isMassChanged = true; this.borderCounter = 0; - + this.mouse = { x: 0, y: 0 }; this.tickLeaderboard = 0; - + this.team = 0; this.spectate = false; this.freeRoam = false; // Free-roam mode enables player to move in spectate mode this.spectateTarget = null; // Spectate target, null for largest player this.lastSpectateSwitchTick = 0; - + this.centerPos = { x: 0, y: 0 @@ -52,7 +52,7 @@ function PlayerTracker(gameServer, socket) { halfWidth: 0, halfHeight: 0 }; - + // Scramble the coordinate system for anti-raga this.scrambleX = 0; this.scrambleY = 0; @@ -61,7 +61,7 @@ function PlayerTracker(gameServer, socket) { this.connectedTime = new Date; this.isMinion = false; this.spawnCounter = 0; - + // Gamemode function if (gameServer) { this.centerPos.x = gameServer.border.centerx; @@ -108,7 +108,7 @@ PlayerTracker.prototype.getFriendlyName = function () { return name; }; -PlayerTracker.prototype.setName = function(name) { +PlayerTracker.prototype.setName = function (name) { this._name = name; if (!name || name.length < 1) { this._nameUnicode = null; @@ -123,7 +123,7 @@ PlayerTracker.prototype.setName = function(name) { this._nameUtf8 = writer.toBuffer(); }; -PlayerTracker.prototype.getName = function() { +PlayerTracker.prototype.getName = function () { return this._name; }; @@ -202,7 +202,7 @@ PlayerTracker.prototype.updateMass = function () { }; PlayerTracker.prototype.massChanged = function () { - this.isMassChanged = true; + this.isMassChanged = true; }; // Functions @@ -211,12 +211,12 @@ PlayerTracker.prototype.joinGame = function (name, skin) { if (this.cells.length > 0) return; if (name == null) name = ""; this.setName(name); - if (skin != null) + if (skin != null) this.setSkin(skin); this.spectate = false; - this.freeRoam = false; - this.spectateTarget = null; - + this.freeRoam = false; + this.spectateTarget = null; + // some old clients don't understand ClearAll message // so we will send update for them if (this.socket.packetHandler.protocol < 6) { @@ -294,7 +294,7 @@ PlayerTracker.prototype.updateTick = function () { this.pressQ(); this.socket.packetHandler.pressQ = false; } - + if (this.spectate) { if (this.freeRoam || this.getSpectateTarget() == null) { // free roam @@ -412,7 +412,7 @@ PlayerTracker.prototype.sendUpdate = function () { // Viewing box -PlayerTracker.prototype.updateCenterInGame = function() { // Get center of cells +PlayerTracker.prototype.updateCenterInGame = function () { // Get center of cells var len = this.cells.length; if (len <= 0) return; var cx = 0; @@ -474,12 +474,12 @@ PlayerTracker.prototype.pressQ = function () { if (tick - this.lastSpectateSwitchTick < 40) return; this.lastSpectateSwitchTick = tick; - + if (this.spectateTarget == null) { - this.freeRoam = !this.freeRoam; - } - this.spectateTarget = null; - } + this.freeRoam = !this.freeRoam; + } + this.spectateTarget = null; + } }; PlayerTracker.prototype.pressW = function () { @@ -487,8 +487,8 @@ PlayerTracker.prototype.pressW = function () { return; } else if (this.gameServer.run) { - this.gameServer.ejectMass(this); - } + this.gameServer.ejectMass(this); + } }; PlayerTracker.prototype.pressSpace = function () { @@ -498,16 +498,16 @@ PlayerTracker.prototype.pressSpace = function () { if (tick - this.lastSpectateSwitchTick < 40) return; this.lastSpectateSwitchTick = tick; - + // Space doesn't work for freeRoam mode - if (this.freeRoam || this.gameServer.largestClient==null) + if (this.freeRoam || this.gameServer.largestClient == null) return; this.nextSpectateTarget(); } else if (this.gameServer.run) { if (this.mergeOverride) return; - this.gameServer.splitCells(this); - } + this.gameServer.splitCells(this); + } }; PlayerTracker.prototype.nextSpectateTarget = function () { @@ -548,7 +548,7 @@ PlayerTracker.prototype.getSpectateTarget = function () { return this.spectateTarget; }; -PlayerTracker.prototype.updateVisibleNodes = function() { +PlayerTracker.prototype.updateVisibleNodes = function () { this.viewNodes = []; if (!this.isMinion) { var self = this; @@ -561,7 +561,7 @@ PlayerTracker.prototype.updateVisibleNodes = function() { this.viewNodes.sort(function (a, b) { return a.nodeId - b.nodeId; }); }; -PlayerTracker.prototype.setCenterPos = function(x, y) { +PlayerTracker.prototype.setCenterPos = function (x, y) { if (isNaN(x) || isNaN(y)) { throw new TypeError("PlayerTracker.setCenterPos: NaN"); } @@ -573,7 +573,7 @@ PlayerTracker.prototype.setCenterPos = function(x, y) { this.centerPos.y = y; }; -PlayerTracker.prototype.sendCameraPacket = function() { +PlayerTracker.prototype.sendCameraPacket = function () { this.socket.sendPacket(new Packet.UpdatePosition( this, this.centerPos.x, diff --git a/src/ai/BotLoader.js b/src/ai/BotLoader.js index 118c2b538..7f9004954 100644 --- a/src/ai/BotLoader.js +++ b/src/ai/BotLoader.js @@ -1,51 +1,51 @@ -// Project imports -var fs = require("fs"); +// Project imports +var fs = require("fs"); var Logger = require('../modules/Logger'); -var BotPlayer = require('./BotPlayer'); -var FakeSocket = require('./FakeSocket'); -var PacketHandler = require('../PacketHandler'); - -function BotLoader(gameServer) { - this.gameServer = gameServer; - this.loadNames(); -} - -module.exports = BotLoader; - -BotLoader.prototype.getName = function() { - var name = ""; - - // Picks a random name for the bot - if (this.randomNames.length > 0) { - var index = (this.randomNames.length * Math.random()) >>> 0; - name = this.randomNames[index]; - } else { - name = "bot" + ++this.nameIndex; - } - - return name; -}; - -BotLoader.prototype.loadNames = function() { - this.randomNames = []; - - if (fs.existsSync("./botnames.txt")) { - // Read and parse the names - filter out whitespace-only names - this.randomNames = fs.readFileSync("./botnames.txt", "utf8").split(/[\r\n]+/).filter(function (x) { - return x != ''; // filter empty names - }); - } - this.nameIndex = 0; -}; - -BotLoader.prototype.addBot = function() { - var s = new FakeSocket(this.gameServer); - s.playerTracker = new BotPlayer(this.gameServer, s); - s.packetHandler = new PacketHandler(this.gameServer, s); - - // Add to client list - this.gameServer.clients.push(s); - - // Add to world - s.packetHandler.setNickname(this.getName()); -}; +var BotPlayer = require('./BotPlayer'); +var FakeSocket = require('./FakeSocket'); +var PacketHandler = require('../PacketHandler'); + +function BotLoader(gameServer) { + this.gameServer = gameServer; + this.loadNames(); +} + +module.exports = BotLoader; + +BotLoader.prototype.getName = function () { + var name = ""; + + // Picks a random name for the bot + if (this.randomNames.length > 0) { + var index = (this.randomNames.length * Math.random()) >>> 0; + name = this.randomNames[index]; + } else { + name = "bot" + ++this.nameIndex; + } + + return name; +}; + +BotLoader.prototype.loadNames = function () { + this.randomNames = []; + + if (fs.existsSync("./botnames.txt")) { + // Read and parse the names - filter out whitespace-only names + this.randomNames = fs.readFileSync("./botnames.txt", "utf8").split(/[\r\n]+/).filter(function (x) { + return x != ''; // filter empty names + }); + } + this.nameIndex = 0; +}; + +BotLoader.prototype.addBot = function () { + var s = new FakeSocket(this.gameServer); + s.playerTracker = new BotPlayer(this.gameServer, s); + s.packetHandler = new PacketHandler(this.gameServer, s); + + // Add to client list + this.gameServer.clients.push(s); + + // Add to world + s.packetHandler.setNickname(this.getName()); +}; diff --git a/src/ai/BotPlayer.js b/src/ai/BotPlayer.js index c94fd81f6..94c86b2cf 100644 --- a/src/ai/BotPlayer.js +++ b/src/ai/BotPlayer.js @@ -1,11 +1,11 @@ -var PlayerTracker = require('../PlayerTracker'); +var PlayerTracker = require('../PlayerTracker'); var gameServer = require('../GameServer'); var Vector = require('vector2-node'); function BotPlayer() { PlayerTracker.apply(this, Array.prototype.slice.call(arguments)); //this.setColor(gameServer.getRandomColor()); - + this.splitCooldown = 0; } @@ -14,18 +14,18 @@ BotPlayer.prototype = new PlayerTracker(); // Functions -BotPlayer.prototype.getLowestCell = function() { +BotPlayer.prototype.getLowestCell = function () { // Gets the cell with the lowest mass if (this.cells.length <= 0) { return null; // Error! } - + // Sort the cells by Array.sort() function to avoid errors var sorted = this.cells.valueOf(); - sorted.sort(function(a, b) { + sorted.sort(function (a, b) { return b.getSize() - a.getSize(); }); - + return sorted[0]; }; @@ -59,7 +59,7 @@ BotPlayer.prototype.sendUpdate = function () { // Overrides the update function }; // Custom -BotPlayer.prototype.decide = function(cell) { +BotPlayer.prototype.decide = function (cell) { if (!cell) return; // Cell was eaten, check in the next tick (I'm too lazy) var cellPos = cell.position; @@ -68,7 +68,7 @@ BotPlayer.prototype.decide = function(cell) { var split = false, splitTarget = null, threats = []; - + for (var i = 0; i < this.viewNodes.length; i++) { var check = this.viewNodes[i]; if (check.owner == this) continue; @@ -89,7 +89,7 @@ BotPlayer.prototype.decide = function(cell) { // Can eat me influence = -check.getSize(); } else { - influence = -(check.getSize()/cell.getSize()) / 3; + influence = -(check.getSize() / cell.getSize()) / 3; } } else if (check.cellType == 1) { // Food @@ -118,7 +118,7 @@ BotPlayer.prototype.decide = function(cell) { } else { influence = check.getSize(); // Might be TeamZ } - + // Apply influence if it isn't 0 or my cell if (influence == 0 || cell.owner == check.owner) continue; @@ -126,7 +126,7 @@ BotPlayer.prototype.decide = function(cell) { // Calculate separation between cell and check var checkPos = check.position; var displacement = new Vector(checkPos.x - cellPos.x, checkPos.y - cellPos.y); - + // Figure out distance between cells var distance = displacement.length(); if (influence < 0) { @@ -134,14 +134,14 @@ BotPlayer.prototype.decide = function(cell) { distance -= cell.getSize() + check.getSize(); if (check.cellType == 0) threats.push(check); } - + // The farther they are the smaller influnce it is if (distance < 1) distance = 1; // Avoid NaN and positive influence with negative distance & attraction influence /= distance; - + // Produce force vector exerted by this entity on the cell var force = displacement.normalize().scale(influence); - + // Splitting conditions if (check.cellType == 0 && cell.getSize() > (check.getSize() + 4) * 1.15 && @@ -149,7 +149,7 @@ BotPlayer.prototype.decide = function(cell) { (!split) && this.splitCooldown == 0 && this.cells.length < 3) { - + var endDist = 780 + 40 - cell.getSize() / 2 - check.getSize(); if (endDist > 0 && distance < endDist) { @@ -161,10 +161,10 @@ BotPlayer.prototype.decide = function(cell) { result.add(force); } } - + // Normalize the resulting vector result.normalize(); - + // Check for splitkilling and threats if (split) { // Can be shortened but I'm too lazy @@ -202,12 +202,12 @@ BotPlayer.prototype.decide = function(cell) { // Subfunctions -BotPlayer.prototype.largest = function(list) { +BotPlayer.prototype.largest = function (list) { // Sort the cells by Array.sort() function to avoid errors var sorted = list.valueOf(); - sorted.sort(function(a, b) { + sorted.sort(function (a, b) { return b.getSize() - a.getSize(); }); - + return sorted[0]; }; diff --git a/src/ai/FakeSocket.js b/src/ai/FakeSocket.js index 227348ca7..6204aee5d 100644 --- a/src/ai/FakeSocket.js +++ b/src/ai/FakeSocket.js @@ -1,4 +1,4 @@ -// A fake socket for bot players +// A fake socket for bot players function FakeSocket(gameServer) { this.server = gameServer; @@ -9,11 +9,11 @@ module.exports = FakeSocket; // Override -FakeSocket.prototype.sendPacket = function(packet) { +FakeSocket.prototype.sendPacket = function (packet) { // Fakes sending a packet return; }; -FakeSocket.prototype.close = function(error) { +FakeSocket.prototype.close = function (error) { this.isCloseRequest = true; }; diff --git a/src/ai/Readme.txt b/src/ai/Readme.txt index 17f605ef7..c2660acf7 100644 --- a/src/ai/Readme.txt +++ b/src/ai/Readme.txt @@ -1,4 +1,4 @@ -[Ogar player bots] +[Ogar player bots] These bots are designed to be used for testing new commits of Ogar. To install this module, set the serverBots config field in gameserver.js to an amount higher than 0 (10 is a good amount), or issue command addBots [number] in console. diff --git a/src/entity/Cell.js b/src/entity/Cell.js index 3cb6c872e..22e5a9357 100644 --- a/src/entity/Cell.js +++ b/src/entity/Cell.js @@ -1,4 +1,4 @@ -function Cell(gameServer, owner, position, size) { +function Cell(gameServer, owner, position, size) { this.gameServer = gameServer; this.owner = owner; // playerTracker that owns this cell @@ -14,7 +14,7 @@ function Cell(gameServer, owner, position, size) { this.isAgitated = false;// If true, then this cell has waves on it's outline this.killedBy = null; // Cell that ate this cell this.isMoving = false; // Indicate that cell is in boosted mode - + this.boostDistance = 0; this.boostDirection = { x: 1, y: 0, angle: Math.PI / 2 }; this.boostMaxSpeed = 78; // boost speed limit, sqrt(780*780/100) @@ -37,17 +37,17 @@ module.exports = Cell; // Fields not defined by the constructor are considered private and need a getter/setter to access from a different class -Cell.prototype.setColor = function(color) { +Cell.prototype.setColor = function (color) { this.color.r = color.r; this.color.g = color.g; this.color.b = color.b; }; -Cell.prototype.getColor = function() { +Cell.prototype.getColor = function () { return this.color; }; -Cell.prototype.getType = function() { +Cell.prototype.getType = function () { return this.cellType; }; @@ -64,7 +64,7 @@ Cell.prototype.setSize = function (size) { this.owner.massChanged(); }; -Cell.prototype.getSize = function() { +Cell.prototype.getSize = function () { return this._size; }; @@ -74,12 +74,12 @@ Cell.prototype.getSizeSquared = function () { Cell.prototype.getMass = function () { if (this._mass == null) { - this._mass = this.getSizeSquared() / 100; - } + this._mass = this.getSizeSquared() / 100; + } return this._mass; }; -Cell.prototype.getSpeed = function() { +Cell.prototype.getSpeed = function () { if (this._speed == null) { var speed = 2.1106 / Math.pow(this.getSize(), 0.449); // tickStep=40ms @@ -88,7 +88,7 @@ Cell.prototype.getSpeed = function() { return this._speed; }; -Cell.prototype.setAngle = function(angle) { +Cell.prototype.setAngle = function (angle) { this.boostDirection = { x: Math.sin(angle), y: Math.cos(angle), @@ -96,7 +96,7 @@ Cell.prototype.setAngle = function(angle) { }; }; -Cell.prototype.getAngle = function() { +Cell.prototype.getAngle = function () { return this.boostDirection.angle; }; @@ -131,7 +131,7 @@ Cell.prototype.canEat = function (cell) { Cell.prototype.onEat = function (prey) { // Called to eat prey cell - this.setSize(Math.sqrt(this.getSizeSquared() + prey.getSizeSquared())); + this.setSize(Math.sqrt(this.getSizeSquared() + prey.getSizeSquared())); }; Cell.prototype.onEaten = function (hunter) { @@ -273,7 +273,7 @@ Cell.prototype.checkBorder = function (border) { // Lib -function findLineIntersection (p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) { +function findLineIntersection(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) { var z1 = p1x - p0x; var z2 = p3x - p2x; var w1 = p1y - p0y; diff --git a/src/entity/EjectedMass.js b/src/entity/EjectedMass.js index 2d7e831ba..b5b480265 100644 --- a/src/entity/EjectedMass.js +++ b/src/entity/EjectedMass.js @@ -1,25 +1,25 @@ -var Cell = require('./Cell'); - -function EjectedMass() { - Cell.apply(this, Array.prototype.slice.call(arguments)); - - this.cellType = 3; -} - -module.exports = EjectedMass; -EjectedMass.prototype = new Cell(); - -// Main Functions - +var Cell = require('./Cell'); + +function EjectedMass() { + Cell.apply(this, Array.prototype.slice.call(arguments)); + + this.cellType = 3; +} + +module.exports = EjectedMass; +EjectedMass.prototype = new Cell(); + +// Main Functions + EjectedMass.prototype.onAdd = function (gameServer) { - // Add to list of ejected mass - gameServer.nodesEjected.push(this); + // Add to list of ejected mass + gameServer.nodesEjected.push(this); +}; + +EjectedMass.prototype.onRemove = function (gameServer) { + // Remove from list of ejected mass + var index = gameServer.nodesEjected.indexOf(this); + if (index != -1) { + gameServer.nodesEjected.splice(index, 1); + } }; - -EjectedMass.prototype.onRemove = function(gameServer) { - // Remove from list of ejected mass - var index = gameServer.nodesEjected.indexOf(this); - if (index != -1) { - gameServer.nodesEjected.splice(index, 1); - } -}; diff --git a/src/entity/Food.js b/src/entity/Food.js index a83c216b2..16fe7e14b 100644 --- a/src/entity/Food.js +++ b/src/entity/Food.js @@ -1,8 +1,8 @@ -var Cell = require('./Cell'); +var Cell = require('./Cell'); function Food() { Cell.apply(this, Array.prototype.slice.call(arguments)); - + this.cellType = 1; } @@ -15,6 +15,6 @@ Food.prototype.onAdd = function (gameServer) { gameServer.currentFood++; }; -Food.prototype.onRemove = function(gameServer) { +Food.prototype.onRemove = function (gameServer) { gameServer.currentFood--; }; diff --git a/src/entity/MotherCell.js b/src/entity/MotherCell.js index 1929b5e12..d16fd8b2f 100644 --- a/src/entity/MotherCell.js +++ b/src/entity/MotherCell.js @@ -29,7 +29,7 @@ MotherCell.prototype.canEat = function (cell) { MotherCell.prototype.onEaten = Virus.prototype.onEaten; // Copies the virus prototype function MotherCell.prototype.onUpdate = function () { - if (this.getSize() <= this.motherCellMinSize) { + if (this.getSize() <= this.motherCellMinSize) { return; } var maxFood = this.gameServer.config.foodMaxAmount; diff --git a/src/entity/PlayerCell.js b/src/entity/PlayerCell.js index 3004d4e48..9227ea2b8 100644 --- a/src/entity/PlayerCell.js +++ b/src/entity/PlayerCell.js @@ -1,4 +1,4 @@ -var Cell = require('./Cell'); +var Cell = require('./Cell'); function PlayerCell() { Cell.apply(this, Array.prototype.slice.call(arguments)); @@ -22,7 +22,7 @@ PlayerCell.prototype.updateRemerge = function () { var baseTtr = this.gameServer.config.playerRecombineTime; // default baseTtr = 30 if (baseTtr == 0) { // instant merge - if (this.getSize() >= 780/2) { + if (this.getSize() >= 780 / 2) { this._canRemerge = age > 20; return; } @@ -86,12 +86,12 @@ PlayerCell.prototype.moveUser = function (border) { // Override -PlayerCell.prototype.onAdd = function(gameServer) { +PlayerCell.prototype.onAdd = function (gameServer) { // Gamemode actions gameServer.gameMode.onCellAdd(this); }; -PlayerCell.prototype.onRemove = function(gameServer) { +PlayerCell.prototype.onRemove = function (gameServer) { var index; // Remove from player cell list index = this.owner.cells.indexOf(this); diff --git a/src/entity/Virus.js b/src/entity/Virus.js index ff303d5ba..dc66e1c3b 100644 --- a/src/entity/Virus.js +++ b/src/entity/Virus.js @@ -1,42 +1,42 @@ -var Cell = require('./Cell'); -var Logger = require('../modules/Logger'); - -function Virus() { - Cell.apply(this, Array.prototype.slice.call(arguments)); - - this.cellType = 2; - this.isSpiked = true; - this.fed = 0; - this.isMotherCell = false; // Not to confuse bots - this.setColor({ r: 0, g: 255, b: 0 }); -} - -module.exports = Virus; -Virus.prototype = new Cell(); - -// Main Functions - -Virus.prototype.canEat = function (cell) { - return cell.cellType == 3; // virus can eat ejected mass only -}; - -Virus.prototype.onEat = function (prey) { +var Cell = require('./Cell'); +var Logger = require('../modules/Logger'); + +function Virus() { + Cell.apply(this, Array.prototype.slice.call(arguments)); + + this.cellType = 2; + this.isSpiked = true; + this.fed = 0; + this.isMotherCell = false; // Not to confuse bots + this.setColor({ r: 0, g: 255, b: 0 }); +} + +module.exports = Virus; +Virus.prototype = new Cell(); + +// Main Functions + +Virus.prototype.canEat = function (cell) { + return cell.cellType == 3; // virus can eat ejected mass only +}; + +Virus.prototype.onEat = function (prey) { // Called to eat prey cell - this.setSize(Math.sqrt(this.getSizeSquared() + prey.getSizeSquared())); - - if (this.getSize() >= this.gameServer.config.virusMaxSize) { - this.setSize(this.gameServer.config.virusMinSize); // Reset mass - this.gameServer.shootVirus(this, prey.getAngle()); - } -}; - -Virus.prototype.onEaten = function(consumer) { - var client = consumer.owner; - if (client == null) return; - + this.setSize(Math.sqrt(this.getSizeSquared() + prey.getSizeSquared())); + + if (this.getSize() >= this.gameServer.config.virusMaxSize) { + this.setSize(this.gameServer.config.virusMinSize); // Reset mass + this.gameServer.shootVirus(this, prey.getAngle()); + } +}; + +Virus.prototype.onEaten = function (consumer) { + var client = consumer.owner; + if (client == null) return; + var maxSplit = this.gameServer.config.playerMaxCells - consumer.owner.cells.length; var masses = this.gameServer.splitMass(consumer.getMass(), maxSplit + 1); - if (masses.length < 2) { + if (masses.length < 2) { return; } @@ -51,26 +51,26 @@ Virus.prototype.onEaten = function(consumer) { // Blow up the cell... var angle = 2 * Math.PI * Math.random(); var step = 2 * Math.PI / masses.length; - for (var i = 0; i < masses.length; i++) { - if (!this.gameServer.splitPlayerCell(client, consumer, angle, masses[i])) { + for (var i = 0; i < masses.length; i++) { + if (!this.gameServer.splitPlayerCell(client, consumer, angle, masses[i])) { break; } angle += step; - if (angle >= 2 * Math.PI) { + if (angle >= 2 * Math.PI) { angle -= 2 * Math.PI; } } -}; - -Virus.prototype.onAdd = function(gameServer) { - gameServer.nodesVirus.push(this); -}; - -Virus.prototype.onRemove = function(gameServer) { - var index = gameServer.nodesVirus.indexOf(this); - if (index != -1) { - gameServer.nodesVirus.splice(index, 1); - } else { - Logger.error("Virus.onRemove: Tried to remove a non existing virus!"); - } -}; +}; + +Virus.prototype.onAdd = function (gameServer) { + gameServer.nodesVirus.push(this); +}; + +Virus.prototype.onRemove = function (gameServer) { + var index = gameServer.nodesVirus.indexOf(this); + if (index != -1) { + gameServer.nodesVirus.splice(index, 1); + } else { + Logger.error("Virus.onRemove: Tried to remove a non existing virus!"); + } +}; diff --git a/src/entity/index.js b/src/entity/index.js index 4913f6e2b..745b68638 100644 --- a/src/entity/index.js +++ b/src/entity/index.js @@ -1,4 +1,4 @@ -module.exports = { +module.exports = { Cell: require('./Cell'), PlayerCell: require('./PlayerCell'), Food: require('./Food'), diff --git a/src/gamemodes/Experimental.js b/src/gamemodes/Experimental.js index 80a4cfeeb..4d9965d97 100644 --- a/src/gamemodes/Experimental.js +++ b/src/gamemodes/Experimental.js @@ -1,19 +1,19 @@ -var FFA = require('./FFA'); // Base gamemode +var FFA = require('./FFA'); // Base gamemode var Entity = require('../entity'); var Logger = require('../modules/Logger'); function Experimental() { FFA.apply(this, Array.prototype.slice.call(arguments)); - + this.ID = 2; this.name = "Experimental"; this.specByLeaderboard = true; - + // Gamemode Specific Variables this.nodesMother = []; this.tickMotherSpawn = 0; this.tickMotherUpdate = 0; - + // Config this.motherSpawnInterval = 25 * 5; // How many ticks it takes to spawn another mother cell (5 seconds) this.motherUpdateInterval = 5; // How many ticks it takes to spawn mother food (1 second) @@ -44,21 +44,21 @@ Experimental.prototype.spawnMotherCell = function (gameServer) { // Override -Experimental.prototype.onServerInit = function(gameServer) { +Experimental.prototype.onServerInit = function (gameServer) { // Called when the server starts gameServer.run = true; - + var mapSize = Math.max(gameServer.border.width, gameServer.border.height); - + // 7 mother cells for vanilla map size //this.motherMinAmount = Math.ceil(mapSize / 2000); //this.motherMaxAmount = this.motherMinAmount * 2; - + var self = this; // Override // Special virus mechanics - Entity.Virus.prototype.onEat = function(prey) { + Entity.Virus.prototype.onEat = function (prey) { // Pushes the virus var angle = prey.isMoving ? prey.getAngle() : this.getAngle(); this.setBoost(16 * 20, angle); @@ -88,7 +88,7 @@ Experimental.prototype.onChange = function (gameServer) { Entity.MotherCell.prototype.onRemove = require('../Entity/MotherCell').prototype.onRemove; }; -Experimental.prototype.onTick = function(gameServer) { +Experimental.prototype.onTick = function (gameServer) { // Mother Cell Spawning if (this.tickMotherSpawn >= this.motherSpawnInterval) { this.tickMotherSpawn = 0; diff --git a/src/gamemodes/FFA.js b/src/gamemodes/FFA.js index 96f24a75e..59163afec 100644 --- a/src/gamemodes/FFA.js +++ b/src/gamemodes/FFA.js @@ -1,8 +1,8 @@ -var Mode = require('./Mode'); +var Mode = require('./Mode'); function FFA() { Mode.apply(this, Array.prototype.slice.call(arguments)); - + this.ID = 0; this.name = "Free For All"; this.specByLeaderboard = true; @@ -13,7 +13,7 @@ FFA.prototype = new Mode(); // Gamemode Specific Functions -FFA.prototype.leaderboardAddSort = function(player, leaderboard) { +FFA.prototype.leaderboardAddSort = function (player, leaderboard) { // Adds the player and sorts the leaderboard var len = leaderboard.length - 1; var loop = true; @@ -33,20 +33,20 @@ FFA.prototype.leaderboardAddSort = function(player, leaderboard) { // Override -FFA.prototype.onPlayerSpawn = function(gameServer, player) { - player.setColor(player.isMinion ? {r:240, g:240, b:255} : gameServer.getRandomColor()); +FFA.prototype.onPlayerSpawn = function (gameServer, player) { + player.setColor(player.isMinion ? { r: 240, g: 240, b: 255 } : gameServer.getRandomColor()); // Spawn player gameServer.spawnPlayer(player); }; -FFA.prototype.updateLB = function(gameServer) { +FFA.prototype.updateLB = function (gameServer) { gameServer.leaderboardType = this.packetLB; var lb = gameServer.leaderboard; // Loop through all clients for (var i = 0; i < gameServer.clients.length; i++) { var client = gameServer.clients[i]; if (client == null) continue; - + var player = client.playerTracker; if (player.isRemoved) continue; // Don't add disconnected players to list @@ -55,7 +55,7 @@ FFA.prototype.updateLB = function(gameServer) { if (player.cells.length <= 0) continue; - + if (lb.length == 0) { // Initial player lb.push(player); @@ -70,6 +70,6 @@ FFA.prototype.updateLB = function(gameServer) { } } } - + this.rankOne = lb[0]; } diff --git a/src/gamemodes/HungerGames.js b/src/gamemodes/HungerGames.js index a8d81804b..8f11345d0 100644 --- a/src/gamemodes/HungerGames.js +++ b/src/gamemodes/HungerGames.js @@ -1,12 +1,12 @@ -var Tournament = require('./Tournament'); +var Tournament = require('./Tournament'); var Entity = require('../entity'); function HungerGames() { Tournament.apply(this, Array.prototype.slice.call(arguments)); - + this.ID = 11; this.name = "Hunger Games"; - + // Gamemode Specific Variables this.maxContenders = 12; this.baseSpawnPoints = [{ @@ -59,50 +59,50 @@ HungerGames.prototype = new Tournament(); // Gamemode Specific Functions -HungerGames.prototype.getPos = function() { +HungerGames.prototype.getPos = function () { var pos = { x: 0, y: 0 }; - + // Random Position if (this.contenderSpawnPoints.length > 0) { var index = Math.floor(Math.random() * this.contenderSpawnPoints.length); pos = this.contenderSpawnPoints[index]; this.contenderSpawnPoints.splice(index, 1); } - + return { x: pos.x, y: pos.y }; }; -HungerGames.prototype.spawnFood = function(gameServer, mass, pos) { +HungerGames.prototype.spawnFood = function (gameServer, mass, pos) { var cell = new Entity.Food(gameServer, null, pos, mass); cell.setColor(gameServer.getRandomColor()); gameServer.addNode(cell); }; -HungerGames.prototype.spawnVirus = function(gameServer, pos) { +HungerGames.prototype.spawnVirus = function (gameServer, pos) { var v = new Entity.Virus(gameServer, null, pos, gameServer.config.virusMinSize); gameServer.addNode(v); }; -HungerGames.prototype.onPlayerDeath = function(gameServer) { +HungerGames.prototype.onPlayerDeath = function (gameServer) { gameServer.setBorder( gameServer.border.width - this.borderDec * 2, gameServer.border.height - this.borderDec * 2); - + // Remove all cells var len = gameServer.nodes.length; for (var i = 0; i < len; i++) { var node = gameServer.nodes[i]; - + if ((!node) || (node.getType() == 0)) { continue; } - + // Move if (node.position.x < gameServer.border.minx) { gameServer.removeNode(node); @@ -122,13 +122,13 @@ HungerGames.prototype.onPlayerDeath = function(gameServer) { // Override -HungerGames.prototype.onServerInit = function(gameServer) { +HungerGames.prototype.onServerInit = function (gameServer) { // Prepare this.prepare(gameServer); - + // Resets spawn points this.contenderSpawnPoints = this.baseSpawnPoints.slice(); - + // Override config values if (gameServer.config.serverBots > this.maxContenders) { // The number of bots cannot exceed the maximum amount of contenders @@ -145,11 +145,11 @@ HungerGames.prototype.onServerInit = function(gameServer) { gameServer.config.virusMaxAmount = 100; gameServer.config.ejectSpawnPlayer = 0; gameServer.config.playerDisconnectTime = 10; // So that people dont disconnect and stall the game for too long - + // Spawn Initial Virus/Large food var mapWidth = gameServer.border.width; var mapHeight = gameServer.border.height; - + // Food this.spawnFood(gameServer, 200, { x: mapWidth * .5, @@ -219,7 +219,7 @@ HungerGames.prototype.onServerInit = function(gameServer) { x: mapWidth * .4, y: mapHeight * .7 }); - + // Virus this.spawnVirus(gameServer, { x: mapWidth * .6, @@ -287,13 +287,13 @@ HungerGames.prototype.onServerInit = function(gameServer) { }); }; -HungerGames.prototype.onPlayerSpawn = function(gameServer, player) { +HungerGames.prototype.onPlayerSpawn = function (gameServer, player) { // Only spawn players if the game hasnt started yet if ((this.gamePhase == 0) && (this.contenders.length < this.maxContenders)) { player.setColor(gameServer.getRandomColor()); // Random color this.contenders.push(player); // Add to contenders list gameServer.spawnPlayer(player, this.getPos()); - + if (this.contenders.length == this.maxContenders) { // Start the game once there is enough players this.startGamePrep(gameServer); diff --git a/src/gamemodes/Mode.js b/src/gamemodes/Mode.js index c45dcdcd2..0c030e786 100644 --- a/src/gamemodes/Mode.js +++ b/src/gamemodes/Mode.js @@ -1,53 +1,53 @@ -function Mode() { - this.ID = -1; - this.name = "Blank"; - this.decayMod = 1.0; // Modifier for decay rate (Multiplier) - this.packetLB = 49; // Packet id for leaderboard packet (48 = Text List, 49 = List, 50 = Pie chart) - this.haveTeams = false; // True = gamemode uses teams, false = gamemode doesnt use teams - - this.specByLeaderboard = false; // false = spectate from player list instead of leaderboard -} - -module.exports = Mode; - -// Override these - -Mode.prototype.onServerInit = function(gameServer) { - // Called when the server starts - gameServer.run = true; -}; - -Mode.prototype.onTick = function(gameServer) { - // Called on every game tick -}; - -Mode.prototype.onChange = function(gameServer) { - // Called when someone changes the gamemode via console commands -}; - -Mode.prototype.onPlayerInit = function(player) { - // Called after a player object is constructed -}; - -Mode.prototype.onPlayerSpawn = function(gameServer, player) { - // Called when a player is spawned - player.setColor(gameServer.getRandomColor()); // Random color - gameServer.spawnPlayer(player); -}; - -Mode.prototype.onCellAdd = function(cell) { - // Called when a player cell is added -}; - -Mode.prototype.onCellRemove = function(cell) { - // Called when a player cell is removed -}; - -Mode.prototype.onCellMove = function(cell, gameServer) { - // Called when a player cell is moved -}; - -Mode.prototype.updateLB = function (gameServer) { +function Mode() { + this.ID = -1; + this.name = "Blank"; + this.decayMod = 1.0; // Modifier for decay rate (Multiplier) + this.packetLB = 49; // Packet id for leaderboard packet (48 = Text List, 49 = List, 50 = Pie chart) + this.haveTeams = false; // True = gamemode uses teams, false = gamemode doesnt use teams + + this.specByLeaderboard = false; // false = spectate from player list instead of leaderboard +} + +module.exports = Mode; + +// Override these + +Mode.prototype.onServerInit = function (gameServer) { + // Called when the server starts + gameServer.run = true; +}; + +Mode.prototype.onTick = function (gameServer) { + // Called on every game tick +}; + +Mode.prototype.onChange = function (gameServer) { + // Called when someone changes the gamemode via console commands +}; + +Mode.prototype.onPlayerInit = function (player) { + // Called after a player object is constructed +}; + +Mode.prototype.onPlayerSpawn = function (gameServer, player) { + // Called when a player is spawned + player.setColor(gameServer.getRandomColor()); // Random color + gameServer.spawnPlayer(player); +}; + +Mode.prototype.onCellAdd = function (cell) { + // Called when a player cell is added +}; + +Mode.prototype.onCellRemove = function (cell) { + // Called when a player cell is removed +}; + +Mode.prototype.onCellMove = function (cell, gameServer) { + // Called when a player cell is moved +}; + +Mode.prototype.updateLB = function (gameServer) { gameServer.leaderboardType = this.packetLB; - // Called when the leaderboard update function is called -}; + // Called when the leaderboard update function is called +}; diff --git a/src/gamemodes/Rainbow.js b/src/gamemodes/Rainbow.js index 0e3e10f2b..d39c56e1d 100644 --- a/src/gamemodes/Rainbow.js +++ b/src/gamemodes/Rainbow.js @@ -1,13 +1,13 @@ -var FFA = require('./FFA'); // Base gamemode +var FFA = require('./FFA'); // Base gamemode var Food = require('../entity/Food'); function Rainbow() { FFA.apply(this, Array.prototype.slice.call(arguments)); - + this.ID = 20; this.name = "Rainbow FFA"; this.specByLeaderboard = true; - + this.colors = [{ 'r': 255, 'g': 0, @@ -138,37 +138,37 @@ Rainbow.prototype = new FFA(); // Gamemode Specific Functions -Rainbow.prototype.changeColor = function(node) { +Rainbow.prototype.changeColor = function (node) { if (typeof node.rainbow == 'undefined') { node.rainbow = Math.floor(Math.random() * this.colors.length); } - + if (node.rainbow >= this.colorsLength) { node.rainbow = 0; } - + node.setColor(this.colors[node.rainbow]); node.rainbow += this.speed; }; // Override -Rainbow.prototype.onServerInit = function() { +Rainbow.prototype.onServerInit = function () { }; -Rainbow.prototype.onChange = function() { +Rainbow.prototype.onChange = function () { }; -Rainbow.prototype.onTick = function(gameServer) { +Rainbow.prototype.onTick = function (gameServer) { var color, node; // Change color for (var i in gameServer.nodes) { node = gameServer.nodes[i]; - + if (!node) { continue; } - + this.changeColor(node); } }; diff --git a/src/gamemodes/TeamX.js b/src/gamemodes/TeamX.js index 7f6554aeb..0455d28bb 100644 --- a/src/gamemodes/TeamX.js +++ b/src/gamemodes/TeamX.js @@ -1,4 +1,4 @@ -// TODO: fix this game mode has outdated code and probably will not works +// TODO: fix this game mode has outdated code and probably will not works var Teams = require('./Teams.js'); var Cell = require('../entity/Cell.js'); var Food = require('../entity/Food.js'); @@ -11,10 +11,10 @@ var GS_getCellsInRange = null; function TeamX() { Teams.apply(this, Array.prototype.slice.call(arguments)); - + this.ID = 14; this.name = 'Experimental Team'; - + // configurations: this.teamCollision = false; // set to true to disable eating teammates this.pushVirus = false; // true: pushing virus, false: splitting virus @@ -23,21 +23,21 @@ function TeamX() { this.motherUpdateInterval = 5; // How many ticks it takes to update the mother cell (1 tick = 50 ms) this.motherSpawnInterval = 100; // How many ticks it takes to spawn another mother cell - Currently 5 seconds this.motherMinAmount = 5; - + // game mode data: this.colors = [{ - 'r': 255, - 'g': 7, - 'b': 7 - }, { - 'r': 7, - 'g': 255, - 'b': 7 - }, { - 'r': 7, - 'g': 7, - 'b': 255 - }, ]; + 'r': 255, + 'g': 7, + 'b': 7 + }, { + 'r': 7, + 'g': 255, + 'b': 7 + }, { + 'r': 7, + 'g': 7, + 'b': 255 + },]; this.nodesMother = []; this.tickMother = 0; this.tickMotherS = 0; @@ -48,22 +48,22 @@ TeamX.prototype = new Teams(); // Gamemode Specific Functions -TeamX.prototype.updateMotherCells = function(gameServer) { +TeamX.prototype.updateMotherCells = function (gameServer) { for (var i in this.nodesMother) { var mother = this.nodesMother[i]; - + // Checks mother.update(gameServer); mother.checkEat(gameServer); } }; -TeamX.prototype.spawnMotherCell = function(gameServer) { +TeamX.prototype.spawnMotherCell = function (gameServer) { // Checks if there are enough mother cells on the map if (this.nodesMother.length < this.motherMinAmount) { // Spawns a mother cell var pos = gameServer.getRandomPosition(); - + // Check for players var size = Math.sqrt(this.motherCellMass * 100); var bound = { @@ -81,7 +81,7 @@ TeamX.prototype.spawnMotherCell = function(gameServer) { } }; -TeamX.prototype.countNotInRange = function(client) { +TeamX.prototype.countNotInRange = function (client) { var count = 0; for (var i = 0; i < client.cells.length; i++) { var cell = client.cells[i]; @@ -94,14 +94,14 @@ TeamX.prototype.countNotInRange = function(client) { // Overwrite: -TeamX.prototype.fuzzColorComponent = function(component) { +TeamX.prototype.fuzzColorComponent = function (component) { if (component != 255) { component = Math.random() * (this.colorFuzziness - 7) + 7; } return component; }; -TeamX.prototype.getTeamColor = function(team) { +TeamX.prototype.getTeamColor = function (team) { var color = this.colors[team]; return { r: this.fuzzColorComponent(color.r), @@ -110,12 +110,12 @@ TeamX.prototype.getTeamColor = function(team) { }; }; -TeamX.prototype.onServerInit = function(gameServer) { +TeamX.prototype.onServerInit = function (gameServer) { // Set up teams for (var i = 0; i < this.teamAmount; i++) { this.nodes[i] = []; } - + // Special virus mechanics if (this.pushVirus) { Virus.prototype.onEat = function (prey) { @@ -124,17 +124,17 @@ TeamX.prototype.onServerInit = function(gameServer) { this.setBoost(16 * 20, angle); }; } - + if (GS_getRandomColor == null) GS_getRandomColor = gameServer.getRandomColor; // backup if (GS_getRandomSpawn == null) GS_getRandomSpawn = gameServer.getRandomSpawn; - + // Override this gameServer.getRandomSpawn = gameServer.getRandomPosition; - gameServer.getRandomColor = function() { + gameServer.getRandomColor = function () { var colorRGB = [0xFF, 0x07, (Math.random() * 256) >> 0]; - colorRGB.sort(function() { + colorRGB.sort(function () { return 0.5 - Math.random(); }); return { @@ -143,7 +143,7 @@ TeamX.prototype.onServerInit = function(gameServer) { g: colorRGB[2] }; }; - + // migrate current players to team mode for (var i = 0; i < gameServer.clients.length; i++) { var client = gameServer.clients[i].playerTracker; @@ -157,7 +157,7 @@ TeamX.prototype.onServerInit = function(gameServer) { } }; -TeamX.prototype.onChange = function(gameServer) { +TeamX.prototype.onChange = function (gameServer) { // Remove all mother cells for (var i in this.nodesMother) { gameServer.removeNode(this.nodesMother[i]); @@ -175,7 +175,7 @@ TeamX.prototype.onChange = function(gameServer) { } }; -TeamX.prototype.onTick = function(gameServer) { +TeamX.prototype.onTick = function (gameServer) { // Mother Cell updates if (this.tickMother >= this.motherUpdateInterval) { this.updateMotherCells(gameServer); @@ -183,7 +183,7 @@ TeamX.prototype.onTick = function(gameServer) { } else { this.tickMother++; } - + // Mother Cell Spawning if (this.tickMotherS >= this.motherSpawnInterval) { this.spawnMotherCell(gameServer); @@ -198,7 +198,7 @@ TeamX.prototype.onTick = function(gameServer) { function MotherCell() { // Temporary - Will be in its own file if Zeach decides to add this to vanilla Cell.apply(this, Array.prototype.slice.call(arguments)); - + this.cellType = 2; // Copies virus cell this.setColor({ r: 205, g: 85, b: 100 }); this.isSpiked = true; @@ -206,10 +206,10 @@ function MotherCell() { // Temporary - Will be in its own file if Zeach decides MotherCell.prototype = new Cell(); // Base -MotherCell.prototype.update = function(gameServer) { +MotherCell.prototype.update = function (gameServer) { // Add mass this.setSize(Math.sqrt(this.getSize() * this.getSize() + 0.25 * 0.25)); - + // Spawn food var maxFood = 10; // Max food spawned per tick var i = 0; // Food spawn counter @@ -218,14 +218,14 @@ MotherCell.prototype.update = function(gameServer) { if (gameServer.currentFood < gameServer.config.foodMaxAmount) { this.spawnFood(gameServer); } - + // Incrementers this.setSize(Math.sqrt(this.getSize() * this.getSize() - 1)); i++; } }; -MotherCell.prototype.spawnFood = function(gameServer) { +MotherCell.prototype.spawnFood = function (gameServer) { // Get starting position var angle = Math.random() * 6.28; // (Math.PI * 2) ??? Precision is not our greatest concern here var r = this.getSize(); @@ -233,26 +233,26 @@ MotherCell.prototype.spawnFood = function(gameServer) { x: this.position.x + (r * Math.sin(angle)), y: this.position.y + (r * Math.cos(angle)) }; - + // Spawn food var cell = new Food(gameServer.getNextNodeId(), null, pos, gameServer.config.foodMinSize, gameServer); cell.setColor(gameServer.getRandomColor()); - + gameServer.addNode(cell); - + // Move engine var dist = (Math.random() * 10) + 22; // Random distance // TODO: check distance - cell.setBoost(dist*15, angle); + cell.setBoost(dist * 15, angle); }; MotherCell.prototype.onEaten = Virus.prototype.onEaten; // Copies the virus prototype function -MotherCell.prototype.onAdd = function(gameServer) { +MotherCell.prototype.onAdd = function (gameServer) { gameServer.gameMode.nodesMother.push(this); // Temporary }; -MotherCell.prototype.onRemove = function(gameServer) { +MotherCell.prototype.onRemove = function (gameServer) { var index = gameServer.gameMode.nodesMother.indexOf(this); if (index != -1) { gameServer.gameMode.nodesMother.splice(index, 1); diff --git a/src/gamemodes/TeamZ.js b/src/gamemodes/TeamZ.js index 1b7befaf3..7da98f48a 100644 --- a/src/gamemodes/TeamZ.js +++ b/src/gamemodes/TeamZ.js @@ -1,4 +1,4 @@ -// TODO: fix this game mode has outdated code and probably will not works +// TODO: fix this game mode has outdated code and probably will not works var Mode = require('./Mode.js'); var Cell = require('../entity/Cell.js'); var Entity = require('../entity'); @@ -32,12 +32,12 @@ var localLB = []; function TeamZ() { Mode.apply(this, Array.prototype.slice.call(arguments)); - + this.ID = 13; this.name = 'Zombie Team'; this.packetLB = 48; this.haveTeams = true; - + // configurations: this.minPlayer = 2; // game is auto started if there are at least 2 players this.gameDuration = 18000; // ticks, 1 tick = 50 ms (20 ticks = 1 s) @@ -52,23 +52,23 @@ function TeamZ() { g: 0x30, b: 0xff }; - + this.colorFactorStep = 5; this.colorLower = 50; // Min 0 this.colorUpper = 225; // Max 255 this.maxBrain = -1; // set this param to any negative number to keep the number of brains not exceed number of humans this.maxHero = 4; // set this param to any negative number to keep the number of heroes not exceed number of zombies - + // game mode data: this.state = GameState.WF_PLAYERS; this.winTeam = -1; this.gameTimer = 0; this.zombies = []; // the clients of zombie players this.humans = []; // the clients of human players - + this.heroes = []; this.brains = []; - + this.spawnHeroTimer = 0; this.spawnBrainTimer = 0; } @@ -78,12 +78,12 @@ TeamZ.prototype = new Mode(); // Gamemode Specific Functions -TeamZ.prototype.createZColorFactor = function(client) { +TeamZ.prototype.createZColorFactor = function (client) { client.zColorFactor = (Math.random() * (this.colorUpper - this.colorLower + 1)) >> 0 + this.colorLower; client.zColorIncr = true; // color will be increased if TRUE - otherwise it will be decreased. }; -TeamZ.prototype.nextZColorFactor = function(client) { +TeamZ.prototype.nextZColorFactor = function (client) { if (client.zColorIncr == true) { if (client.zColorFactor + this.colorFactorStep >= this.colorUpper) { client.zColorFactor = this.colorUpper; @@ -101,7 +101,7 @@ TeamZ.prototype.nextZColorFactor = function(client) { } }; -TeamZ.prototype.updateZColor = function(client, mask) { +TeamZ.prototype.updateZColor = function (client, mask) { var color = { r: (mask & 0x4) > 0 ? client.zColorFactor : 7, g: (mask & 0x2) > 0 ? client.zColorFactor : 7, @@ -114,19 +114,19 @@ TeamZ.prototype.updateZColor = function(client, mask) { } }; -TeamZ.prototype.isCrazy = function(client) { - return (typeof(client.crazyTimer) != 'undefined' && client.crazyTimer > 0 && client.team > 0); +TeamZ.prototype.isCrazy = function (client) { + return (typeof (client.crazyTimer) != 'undefined' && client.crazyTimer > 0 && client.team > 0); }; -TeamZ.prototype.hasEatenHero = function(client) { - return (typeof(client.eatenHeroTimer) != 'undefined' && client.eatenHeroTimer > 0); +TeamZ.prototype.hasEatenHero = function (client) { + return (typeof (client.eatenHeroTimer) != 'undefined' && client.eatenHeroTimer > 0); }; -TeamZ.prototype.hasEatenBrain = function(client) { - return (typeof(client.eatenBrainTimer) != 'undefined' && client.eatenBrainTimer > 0); +TeamZ.prototype.hasEatenBrain = function (client) { + return (typeof (client.eatenBrainTimer) != 'undefined' && client.eatenBrainTimer > 0); }; -TeamZ.prototype.spawnDrug = function(gameServer, cell) { // spawn HERO or BRAIN +TeamZ.prototype.spawnDrug = function (gameServer, cell) { // spawn HERO or BRAIN var max = 0; var proceedNext = false; if (cell.getType() == CellType.HERO) { @@ -138,19 +138,19 @@ TeamZ.prototype.spawnDrug = function(gameServer, cell) { // spawn HERO or BRAIN } if (proceedNext) { var pos = gameServer.getRandomPosition(); - + // Check for players - var size = cell.getSize(); - var bound = { - minx: pos.x - size, - miny: pos.y - size, - maxx: pos.x + size, - maxy: pos.y + size - }; - if (gameServer.quadTree.any(bound, function (item) { return item.cell.cellType == 0; })) { - // FAILED because of collision - return false; - } + var size = cell.getSize(); + var bound = { + minx: pos.x - size, + miny: pos.y - size, + maxx: pos.x + size, + maxy: pos.y + size + }; + if (gameServer.quadTree.any(bound, function (item) { return item.cell.cellType == 0; })) { + // FAILED because of collision + return false; + } cell.setPosition(pos); gameServer.addNode(cell); return true; // SUCCESS with spawn @@ -159,31 +159,31 @@ TeamZ.prototype.spawnDrug = function(gameServer, cell) { // spawn HERO or BRAIN }; // Call to change a human client to a zombie -TeamZ.prototype.turnToZombie = function(client) { +TeamZ.prototype.turnToZombie = function (client) { client.team = 0; // team Z this.createZColorFactor(client); this.updateZColor(client, 0x7); // Gray - + // remove from human list var index = this.humans.indexOf(client); if (index >= 0) { this.humans.splice(index, 1); } - + // add to zombie list this.zombies.push(client); }; -TeamZ.prototype.boostSpeedCell = function(cell) { +TeamZ.prototype.boostSpeedCell = function (cell) { if (typeof cell.originalSpeed == 'undefined' || cell.originalSpeed == null) { cell.originalSpeed = cell.getSpeed; - cell.getSpeed = function() { + cell.getSpeed = function () { return 2 * this.originalSpeed(); }; } }; -TeamZ.prototype.boostSpeed = function(client) { +TeamZ.prototype.boostSpeed = function (client) { for (var i = 0; i < client.cells.length; i++) { var cell = client.cells[i]; if (typeof cell == 'undefined') @@ -192,14 +192,14 @@ TeamZ.prototype.boostSpeed = function(client) { } }; -TeamZ.prototype.resetSpeedCell = function(cell) { +TeamZ.prototype.resetSpeedCell = function (cell) { if (typeof cell.originalSpeed != 'undefined' && cell.originalSpeed != null) { cell.getSpeed = cell.originalSpeed; cell.originalSpeed = null; } }; -TeamZ.prototype.resetSpeed = function(client) { +TeamZ.prototype.resetSpeed = function (client) { for (var i = 0; i < client.cells.length; i++) { var cell = client.cells[i]; if (typeof cell == 'undefined') @@ -208,7 +208,7 @@ TeamZ.prototype.resetSpeed = function(client) { } }; -TeamZ.prototype.startGame = function(gameServer) { +TeamZ.prototype.startGame = function (gameServer) { for (var i = 0; i < this.humans.length; i++) { var client = this.humans[i]; client.team = client.pID; @@ -225,17 +225,17 @@ TeamZ.prototype.startGame = function(gameServer) { } } } - + // Select random human to be the zombie var zombie = this.humans[(Math.random() * this.humans.length) >> 0]; this.turnToZombie(zombie); - + this.winTeam = -1; this.state = GameState.IN_PROGRESS; this.gameTimer = this.gameDuration; }; -TeamZ.prototype.endGame = function(gameServer) { +TeamZ.prototype.endGame = function (gameServer) { // reset game for (var i = 0; i < this.zombies.length; i++) { var client = this.zombies[i]; @@ -248,7 +248,7 @@ TeamZ.prototype.endGame = function(gameServer) { this.spawnHeroTimer = 0; this.spawnBrainTimer = 0; localLB = []; // reset leader board - + for (var i = 0; i < this.humans.length; i++) { var client = this.humans[i]; client.color = this.defaultColor; @@ -258,16 +258,16 @@ TeamZ.prototype.endGame = function(gameServer) { cell.setColor(this.defaultColor); } } - + this.state = GameState.WF_PLAYERS; this.gameTimer = 0; }; -TeamZ.prototype.leaderboardAddSort = function(player, leaderboard) { +TeamZ.prototype.leaderboardAddSort = function (player, leaderboard) { // Adds the player and sorts the leaderboard var len = leaderboard.length - 1; var loop = true; - + while ((len >= 0) && (loop)) { // Start from the bottom of the leaderboard if (player.getScore() <= leaderboard[len].getScore()) { @@ -284,10 +284,10 @@ TeamZ.prototype.leaderboardAddSort = function(player, leaderboard) { // Override -TeamZ.prototype.onServerInit = function(gameServer) { +TeamZ.prototype.onServerInit = function (gameServer) { // Called when the server starts gameServer.run = true; - + // Overwrite some server functions: GameServer = require('../GameServer.js'); GS_getRandomColor = GameServer.prototype.getRandomColor; // backup @@ -295,12 +295,12 @@ TeamZ.prototype.onServerInit = function(gameServer) { GS_getCellsInRange = GameServer.prototype.getCellsInRange; GS_splitCells = GameServer.prototype.splitCells; GS_newCellVirused = GameServer.prototype.newCellVirused; - + //OVERWRITE GLOBAL FUNCTIONs to adapt Zombie Team mode - - GameServer.prototype.getRandomColor = function() { + + GameServer.prototype.getRandomColor = function () { var colorRGB = [0xFF, 0x07, (Math.random() * 256) >> 0]; - colorRGB.sort(function() { + colorRGB.sort(function () { return 0.5 - Math.random(); }); return { @@ -309,11 +309,11 @@ TeamZ.prototype.onServerInit = function(gameServer) { g: colorRGB[2] }; }; - - GameServer.prototype.getNearestVirus = function(cell) { + + GameServer.prototype.getNearestVirus = function (cell) { // More like getNearbyVirus var virus = null; - + // loop through all heroes for (var i = 0; i < this.gameMode.heroes.length; i++) { var check = this.gameMode.heroes[i]; @@ -328,7 +328,7 @@ TeamZ.prototype.onServerInit = function(gameServer) { } if (virus != null) return virus; - + // loop through all brains for (var i = 0; i < this.gameMode.brains.length; i++) { var check = this.gameMode.brains[i]; @@ -341,54 +341,54 @@ TeamZ.prototype.onServerInit = function(gameServer) { virus = check; break; } - + if (virus != null) return virus; - + // Call base: // Loop through all viruses on the map. There is probably a more efficient way of doing this but whatever var len = this.nodesVirus.length; for (var i = 0; i < len; i++) { var check = this.nodesVirus[i]; - + if (typeof check === 'undefined') { continue; } - + if (this.checkCellCollision(cell, check) == null) { continue; } - + // Add to list of cells nearby virus = check; break; // stop checking when a virus found } return virus; }; - + // this is almost same to the legacy function - GameServer.prototype.getCellsInRange = function(cell) { + GameServer.prototype.getCellsInRange = function (cell) { var list = new Array(); - + if (this.gameMode.state != GameState.IN_PROGRESS) return list; - + var squareR = cell.getSizeSquared(); // Get cell squared radius - + // Loop through all cells that are visible to the cell. There is probably a more efficient way of doing this but whatever var len = cell.owner.visibleNodes.length; for (var i = 0; i < len; i++) { var check = cell.owner.visibleNodes[i]; - + if (typeof check === 'undefined') { continue; } - + // if something already collided with this cell, don't check for other collisions if (check.isRemoved) { continue; } - + // HERO and BRAIN checking if (cell.owner.getTeam() == 0) { // Z team @@ -399,49 +399,49 @@ TeamZ.prototype.onServerInit = function(gameServer) { if (check.getType() == CellType.BRAIN) continue; } - + // Can't eat itself if (cell.nodeId == check.nodeId) { continue; } - + // Can't eat cells that have collision turned off if ((cell.owner == check.owner) && (cell.ignoreCollision)) { continue; } - + // AABB Collision - if (gameServer.checkCellCollision(cell, check)==null) { + if (gameServer.checkCellCollision(cell, check) == null) { continue; } - + // Cell type check - Cell must be bigger than this number times the mass of the cell being eaten var multiplier = 1.25; - + switch (check.getType()) { - case 1: // Food cell + case 1:// Food cell list.push(check); check.isRemoved = true; // skip future collision checks for this food continue; - case 2: // Virus + case 2:// Virus multiplier = 1.33; break; - case 0: // Players + case 0:// Players // Can't eat self if it's not time to recombine yet if (check.owner == cell.owner) { if (!cell.canRemrege() || !check.canRemerge()) { continue; } - + multiplier = 1.00; } - + // Can't eat team members if (this.gameMode.haveTeams) { if (!check.owner) { // Error check continue; } - + if ((check.owner != cell.owner) && (check.owner.getTeam() == cell.owner.getTeam())) { continue; } @@ -450,55 +450,55 @@ TeamZ.prototype.onServerInit = function(gameServer) { default: break; } - + // Make sure the cell is big enough to be eaten. if ((check.getMass() * multiplier) > cell.getMass()) { continue; } - + // Eating range var xs = Math.pow(check.position.x - cell.position.x, 2); var ys = Math.pow(check.position.y - cell.position.y, 2); var dist = Math.sqrt(xs + ys); - + var eatingRange = cell.getSize() - check.getSize() / Math.PI; // Eating range = radius of eating cell + 40% of the radius of the cell being eaten if (dist > eatingRange) { // Not in eating range continue; } - + // Add to list of cells nearby list.push(check); - + // Something is about to eat this cell; no need to check for other collisions with it check.isRemoved = true; } return list; }; - + // this is almost same to the legacy function - GameServer.prototype.splitCells = function(client) { + GameServer.prototype.splitCells = function (client) { var len = client.cells.length; for (var i = 0; i < len; i++) { if (client.cells.length >= this.config.playerMaxCells) { // Player cell limit continue; } - + var cell = client.cells[i]; if (!cell) { continue; } - + if (cell.getSize() < this.config.playerMinSplitSize) { continue; } - + // Get angle var deltaY = client.mouse.y - cell.position.y; var deltaX = client.mouse.x - cell.position.x; var angle = Math.atan2(deltaX, deltaY); - + // Get starting position var size = cell.getSize() / 2; var startPos = { @@ -511,9 +511,9 @@ TeamZ.prototype.onServerInit = function(gameServer) { cell.setSize(newSize); // Create cell var split = new Entity.PlayerCell(this, client, startPos, newSize); - // TODO: check distance + // TODO: check distance split.setBoost(splitSpeed * 32, angle); - + // boost speed if zombie eats brain if (this.gameMode.hasEatenBrain(client) || this.gameMode.isCrazy(client)) { this.gameMode.boostSpeedCell(split); @@ -527,24 +527,24 @@ TeamZ.prototype.onServerInit = function(gameServer) { this.addNode(split); } }; - + // this function is almost same to the legacy - GameServer.prototype.newCellVirused = function(client, parent, angle, mass, speed) { + GameServer.prototype.newCellVirused = function (client, parent, angle, mass, speed) { // Starting position var startPos = { x: parent.position.x, y: parent.position.y }; - + var size = Math.sqrt(mass); // Create cell newCell = new Entity.PlayerCell(this, client, startPos, size); - // TODO: check distance + // TODO: check distance newCell.setBoost(speed * 10, angle); //newCell.setAngle(angle); //newCell.setMoveEngineData(speed, 10); newCell.ignoreCollision = true; // Turn off collision - + // boost speed if zombie eats brain if (this.gameMode.hasEatenBrain(client) || this.gameMode.isCrazy(client)) { this.gameMode.boostSpeedCell(newCell); @@ -555,23 +555,23 @@ TeamZ.prototype.onServerInit = function(gameServer) { //newCell.recombineTicks = 1; // TODO: fix? } - + // Add to moving cells list this.addNode(newCell); }; - - Virus.prototype.onEaten = function(consumer) { + + Virus.prototype.onEaten = function (consumer) { var client = consumer.owner; var maxSplits = Math.floor(consumer.getMass() / 16) - 1; // Maximum amount of splits var numSplits = this.gameServer.config.playerMaxCells - client.cells.length; // Get number of splits numSplits = Math.min(numSplits, maxSplits); var splitMass = Math.min(consumer.getMass() / (numSplits + 1), 36); // Maximum size of new splits - + // Cell cannot split any further if (numSplits <= 0) { return; } - + // Big cells will split into cells larger than 36 mass (1/4 of their mass) var bigSplits = 0; var endMass = consumer.getMass() - (numSplits * splitMass); @@ -587,34 +587,34 @@ TeamZ.prototype.onServerInit = function(gameServer) { bigSplits++; numSplits--; } - + // Splitting var angle = 0; // Starting angle for (var k = 0; k < numSplits; k++) { angle += 6 / numSplits; // Get directions of splitting cells this.gameServer.newCellVirused(client, consumer, angle, splitMass, 150); - consumer.setSize(Math.sqrt(consumer.getSize() * consumer.getSize() - splitMass*splitMass)); + consumer.setSize(Math.sqrt(consumer.getSize() * consumer.getSize() - splitMass * splitMass)); } - + for (var k = 0; k < bigSplits; k++) { angle = Math.random() * 6.28; // Random directions splitMass = consumer.getMass() / 4; this.gameServer.newCellVirused(client, consumer, angle, splitMass, 20); - consumer.setSize(Math.sqrt(consumer.getSize() * consumer.getSize() - splitMass * splitMass)); + consumer.setSize(Math.sqrt(consumer.getSize() * consumer.getSize() - splitMass * splitMass)); } - + if (this.gameServer.gameMode.hasEatenHero(client)) { //consumer.recombineTicks = 0; // TODO: fix? } }; - + // Handle "gamemode" command: for (var i = 0; i < this.gameServer.clients.length; i++) { var client = this.gameServer.clients[i].playerTracker; if (!client) continue; - + if (client.cells.length > 0) { client.eatenBrainTimer = 0; client.eatenHeroTimer = 0; @@ -630,7 +630,7 @@ TeamZ.prototype.onServerInit = function(gameServer) { } }; -TeamZ.prototype.onChange = function(gameServer) { +TeamZ.prototype.onChange = function (gameServer) { // Called when someone changes the gamemode via console commands // remove Brain and Hero for (var i = 0; this.brains.length; i++) { @@ -641,7 +641,7 @@ TeamZ.prototype.onChange = function(gameServer) { var node = this.heroes[i]; gameServer.removeNode(node); } - + // discard all boost: for (var i = 0; i < this.humans.length; i++) { var client = this.humans[i]; @@ -655,7 +655,7 @@ TeamZ.prototype.onChange = function(gameServer) { this.resetSpeed(client); } } - + // revert to default: GameServer.prototype.getRandomColor = GS_getRandomColor; GameServer.prototype.getNearestVirus = GS_getNearestVirus; @@ -665,9 +665,9 @@ TeamZ.prototype.onChange = function(gameServer) { Virus.prototype.onEaten = Virus_onEaten; }; -TeamZ.prototype.onTick = function(gameServer) { +TeamZ.prototype.onTick = function (gameServer) { // Called on every game tick - + switch (this.state) { case GameState.WF_PLAYERS: if (this.humans.length >= this.minPlayer) { @@ -701,22 +701,22 @@ TeamZ.prototype.onTick = function(gameServer) { this.winTeam = 1; } } - + if (this.winTeam >= 0) { this.endGame(gameServer); } - + break; } - + // change color of zombies for (var i = 0; i < this.zombies.length; i++) { var client = this.zombies[i]; this.nextZColorFactor(client); - + if (this.hasEatenBrain(client)) { client.eatenBrainTimer--; - + if (client.eatenBrainTimer > 0) { this.updateZColor(client, 0x5); // Pink continue; @@ -725,10 +725,10 @@ TeamZ.prototype.onTick = function(gameServer) { this.resetSpeed(client); } } - + this.updateZColor(client, 0x7); // Gray } - + for (var i = 0; i < this.humans.length; i++) { var client = this.humans[i]; if (this.isCrazy(client)) { @@ -738,12 +738,12 @@ TeamZ.prototype.onTick = function(gameServer) { var cell = client.cells[j]; // reset speed: this.resetSpeedCell(cell); - + // reset color: if (client.cured == true) cell.setColor(client.getColor()); } - + if (client.cured == true) { client.cured = false; // reset } else { @@ -755,7 +755,7 @@ TeamZ.prototype.onTick = function(gameServer) { client.colorToggle++; if (client.colorToggle % 10 == 0) { var blinkColor = null; - + if (client.colorToggle == 20) { blinkColor = client.getColor(); client.colorToggle = 0; @@ -774,7 +774,7 @@ TeamZ.prototype.onTick = function(gameServer) { }; // Gray } } - + for (var j = 0; j < client.cells.length; j++) { var cell = client.cells[j]; cell.setColor(blinkColor); @@ -802,32 +802,32 @@ TeamZ.prototype.onTick = function(gameServer) { } else { color = client.getColor(); // reset } - + for (var j = 0; j < client.cells.length; j++) { var cell = client.cells[j]; cell.setColor(color); } } } - + // check timer to spawn Hero: this.spawnHeroTimer++; if (this.spawnHeroTimer >= this.spawnHeroInterval) { this.spawnHeroTimer = 0; var cell = new Hero(gameServer.getNextNodeId(), null); - while (!this.spawnDrug(gameServer, cell)); // collision detect algorithm needs enhancement + while (!this.spawnDrug(gameServer, cell)) ; // collision detect algorithm needs enhancement } - + // check timer to spawn Brain: this.spawnBrainTimer++; if (this.spawnBrainTimer >= this.spawnBrainInterval) { this.spawnBrainTimer = 0; var cell = new Brain(gameServer.getNextNodeId(), null); - while (!this.spawnDrug(gameServer, cell)); // collision detect algorithm needs enhancement + while (!this.spawnDrug(gameServer, cell)) ; // collision detect algorithm needs enhancement } }; -TeamZ.prototype.onCellAdd = function(cell) { +TeamZ.prototype.onCellAdd = function (cell) { // Called when a player cell is added var client = cell.owner; if (client.cells.length == 1) { // first cell @@ -837,7 +837,7 @@ TeamZ.prototype.onCellAdd = function(cell) { client.eatenHeroTimer = 0; client.crazyTimer = 0; this.humans.push(client); - + if (this.state == GameState.IN_PROGRESS) { this.turnToZombie(client); } else { @@ -848,7 +848,7 @@ TeamZ.prototype.onCellAdd = function(cell) { } }; -TeamZ.prototype.onCellRemove = function(cell) { +TeamZ.prototype.onCellRemove = function (cell) { // Called when a player cell is removed var client = cell.owner; if (client.cells.length == 0) { // last cell @@ -871,20 +871,20 @@ TeamZ.prototype.onCellMove = function (x1, y1, cell) { // Called when a player cell is moved var team = cell.owner.getTeam(); var r = cell.getSize(); - + // Find team for (var i = 0; i < cell.owner.visibleNodes.length; i++) { // Only collide with player cells var check = cell.owner.visibleNodes[i]; - + if ((check.getType() != 0) || (cell.owner == check.owner)) { continue; } - + if ((this.hasEatenHero(check.owner)) || (this.hasEatenHero(cell.owner))) { continue; } - + // Collision with zombies if (check.owner.getTeam() == 0 || team == 0) { // Check if in collision range @@ -893,10 +893,10 @@ TeamZ.prototype.onCellMove = function (x1, y1, cell) { // Skip continue; } - + // First collision check passed... now more precise checking dist = cell.getDist(cell.position.x, cell.position.y, check.position.x, check.position.y); - + // Calculations if (dist < collisionDist) { // Collided var crazyClient = null; @@ -905,33 +905,33 @@ TeamZ.prototype.onCellMove = function (x1, y1, cell) { } else if (team == 0 && check.owner.getTeam() != 0) { crazyClient = check.owner; } - + if (crazyClient != null && !this.isCrazy(crazyClient)) { crazyClient.crazyTimer = this.crazyDuration; crazyClient.colorToggle = 0; this.boostSpeed(crazyClient); } - + // The moving cell pushes the colliding cell var newDeltaY = check.position.y - y1; var newDeltaX = check.position.x - x1; var newAngle = Math.atan2(newDeltaX, newDeltaY); - + var move = collisionDist - dist; - - check.setPosition({ + + check.setPosition({ x: check.position.x + (move * Math.sin(newAngle)) >> 0, - y: check.position.y + (move * Math.cos(newAngle)) >> 0 + y: check.position.y + (move * Math.cos(newAngle)) >> 0 }); } } } }; -TeamZ.prototype.updateLB = function(gameServer) { +TeamZ.prototype.updateLB = function (gameServer) { gameServer.leaderboardType = this.packetLB; var lb = gameServer.leaderboard; - + if (this.winTeam == 0) { lb.push('ZOMBIE WINS'); lb.push('_______________'); @@ -939,7 +939,7 @@ TeamZ.prototype.updateLB = function(gameServer) { lb.push('HUMAN WINS'); lb.push('_______________'); } - + switch (this.state) { case GameState.WF_PLAYERS: lb.push('WAITING FOR'); @@ -959,20 +959,20 @@ TeamZ.prototype.updateLB = function(gameServer) { lb.push('HUMAN: ' + this.humans.length); lb.push('ZOMBIE: ' + this.zombies.length); lb.push('_______________'); - + // Loop through all clients localLB = []; for (var i = 0; i < gameServer.clients.length; i++) { if (typeof gameServer.clients[i] == 'undefined' || gameServer.clients[i].playerTracker.team == 0) { continue; } - + var player = gameServer.clients[i].playerTracker; if (player.cells.length <= 0) { continue; } var playerScore = player.getScore(); - + if (localLB.length == 0) { // Initial player localLB.push(player); @@ -990,7 +990,7 @@ TeamZ.prototype.updateLB = function(gameServer) { for (var i = 0; i < localLB.length && lb.length < 10; i++) { lb.push(localLB[i].getName()); } - + break; default: lb.push('ERROR STATE'); @@ -1005,7 +1005,7 @@ TeamZ.prototype.updateLB = function(gameServer) { // HERO POISON CELL: function Hero() { Cell.apply(this, Array.prototype.slice.call(arguments)); - + this.cellType = CellType.HERO; //this.isSpiked = true; this.setColor({ r: 255, g: 255, b: 7 }); @@ -1014,17 +1014,17 @@ function Hero() { Hero.prototype = new Cell(); -Hero.prototype.getName = function() { +Hero.prototype.getName = function () { return 'HERO'; }; Hero.prototype.calcMove = null; -Hero.prototype.onAdd = function(gameServer) { +Hero.prototype.onAdd = function (gameServer) { gameServer.gameMode.heroes.push(this); }; -Hero.prototype.onRemove = function(gameServer) { +Hero.prototype.onRemove = function (gameServer) { var index = gameServer.gameMode.heroes.indexOf(this); if (index != -1) { gameServer.gameMode.heroes.splice(index, 1); @@ -1033,27 +1033,27 @@ Hero.prototype.onRemove = function(gameServer) { } }; -Hero.prototype.feed = function(feeder, gameServer) { +Hero.prototype.feed = function (feeder, gameServer) { gameServer.removeNode(feeder); - - // TODO: check distance + + // TODO: check distance this.setBoost(60 * 5, feeder.getAngle()); //this.setAngle(feeder.getAngle()); //this.moveEngineTicks = 5; // Amount of times to loop the movement function //this.moveEngineSpeed = 60; - + var index = gameServer.movingNodes.indexOf(this); if (index == -1) { gameServer.movingNodes.push(this); } }; -Hero.prototype.onEaten = function(consumer) { +Hero.prototype.onEaten = function (consumer) { // Called when the cell is consumed var client = consumer.owner; - - // delicious - + + // delicious + if (this.gameServer.gameMode.isCrazy(client)) { // Neutralize the Zombie effect client.cured = true; @@ -1076,7 +1076,7 @@ Hero.prototype.onEaten = function(consumer) { // BRAIN CELL: function Brain() { Cell.apply(this, Array.prototype.slice.call(arguments)); - + this.cellType = CellType.BRAIN; //this.isSpiked = true; this.setColor({ r: 255, g: 7, b: 255 }); @@ -1085,17 +1085,17 @@ function Brain() { Brain.prototype = new Cell(); -Brain.prototype.getName = function() { +Brain.prototype.getName = function () { return 'BRAIN'; }; Brain.prototype.calcMove = null; -Brain.prototype.onAdd = function(gameServer) { +Brain.prototype.onAdd = function (gameServer) { gameServer.gameMode.brains.push(this); }; -Brain.prototype.onRemove = function(gameServer) { +Brain.prototype.onRemove = function (gameServer) { var index = gameServer.gameMode.brains.indexOf(this); if (index != -1) { gameServer.gameMode.brains.splice(index, 1); @@ -1104,29 +1104,29 @@ Brain.prototype.onRemove = function(gameServer) { } }; -Brain.prototype.feed = function(feeder, gameServer) { +Brain.prototype.feed = function (feeder, gameServer) { gameServer.removeNode(feeder); - - // TODO: check distance + + // TODO: check distance this.setBoost(60 * 5, feeder.getAngle()); //this.setAngle(feeder.getAngle()); //this.moveEngineTicks = 5; // Amount of times to loop the movement function //this.moveEngineSpeed = 60; - + var index = gameServer.movingNodes.indexOf(this); if (index == -1) { gameServer.movingNodes.push(this); } }; -Brain.prototype.onEaten = function(consumer) { +Brain.prototype.onEaten = function (consumer) { // Called when the cell is consumed var client = consumer.owner; - // yummy! - + // yummy! + client.eatenBrainTimer = this.gameServer.gameMode.brainEffectDuration; - + // Boost speed this.gameServer.gameMode.boostSpeed(client); }; diff --git a/src/gamemodes/Teams.js b/src/gamemodes/Teams.js index eb71c74f8..816e4fa17 100644 --- a/src/gamemodes/Teams.js +++ b/src/gamemodes/Teams.js @@ -1,30 +1,30 @@ -var Mode = require('./Mode'); +var Mode = require('./Mode'); function Teams() { Mode.apply(this, Array.prototype.slice.call(arguments)); - + this.ID = 1; this.name = "Teams"; this.decayMod = 1.5; this.packetLB = 50; this.haveTeams = true; this.colorFuzziness = 32; - + // Special this.teamAmount = 3; // Amount of teams. Having more than 3 teams will cause the leaderboard to work incorrectly (client issue). this.colors = [{ - 'r': 223, - 'g': 0, - 'b': 0 - }, { - 'r': 0, - 'g': 223, - 'b': 0 - }, { - 'r': 0, - 'g': 0, - 'b': 223 - }, ]; // Make sure you add extra colors here if you wish to increase the team amount [Default colors are: Red, Green, Blue] + 'r': 223, + 'g': 0, + 'b': 0 + }, { + 'r': 0, + 'g': 223, + 'b': 0 + }, { + 'r': 0, + 'g': 0, + 'b': 223 + },]; // Make sure you add extra colors here if you wish to increase the team amount [Default colors are: Red, Green, Blue] this.nodes = []; // Teams } @@ -33,12 +33,12 @@ Teams.prototype = new Mode(); //Gamemode Specific Functions -Teams.prototype.fuzzColorComponent = function(component) { +Teams.prototype.fuzzColorComponent = function (component) { component += Math.random() * this.colorFuzziness >> 0; return component; }; -Teams.prototype.getTeamColor = function(team) { +Teams.prototype.getTeamColor = function (team) { var color = this.colors[team]; return { r: this.fuzzColorComponent(color.r), @@ -49,19 +49,19 @@ Teams.prototype.getTeamColor = function(team) { // Override -Teams.prototype.onPlayerSpawn = function(gameServer, player) { +Teams.prototype.onPlayerSpawn = function (gameServer, player) { // Random color based on team player.setColor(this.getTeamColor(player.team)); // Spawn player gameServer.spawnPlayer(player); }; -Teams.prototype.onServerInit = function(gameServer) { +Teams.prototype.onServerInit = function (gameServer) { // Set up teams for (var i = 0; i < this.teamAmount; i++) { this.nodes[i] = []; } - + // migrate current players to team mode for (var i = 0; i < gameServer.clients.length; i++) { var client = gameServer.clients[i].playerTracker; @@ -75,17 +75,17 @@ Teams.prototype.onServerInit = function(gameServer) { } }; -Teams.prototype.onPlayerInit = function(player) { +Teams.prototype.onPlayerInit = function (player) { // Get random team player.team = Math.floor(Math.random() * this.teamAmount); }; -Teams.prototype.onCellAdd = function(cell) { +Teams.prototype.onCellAdd = function (cell) { // Add to team list this.nodes[cell.owner.getTeam()].push(cell); }; -Teams.prototype.onCellRemove = function(cell) { +Teams.prototype.onCellRemove = function (cell) { // Remove from team list var index = this.nodes[cell.owner.getTeam()].indexOf(cell); if (index != -1) { @@ -93,19 +93,19 @@ Teams.prototype.onCellRemove = function(cell) { } }; -Teams.prototype.onCellMove = function(cell, gameServer) { +Teams.prototype.onCellMove = function (cell, gameServer) { var team = cell.owner.getTeam(); var r = cell.getSize(); - + // Find team for (var i = 0; i < cell.owner.visibleNodes.length; i++) { // Only collide with player cells var check = cell.owner.visibleNodes[i]; - + if ((check.getType() != 0) || (cell.owner == check.owner)) { continue; } - + // Collision with teammates if (check.owner.getTeam() == team) { @@ -118,7 +118,7 @@ Teams.prototype.onCellMove = function(cell, gameServer) { } }; -Teams.prototype.updateLB = function(gameServer) { +Teams.prototype.updateLB = function (gameServer) { gameServer.leaderboardType = this.packetLB; var total = 0; var teamMass = []; @@ -126,15 +126,15 @@ Teams.prototype.updateLB = function(gameServer) { for (var i = 0; i < this.teamAmount; i++) { // Set starting mass teamMass[i] = 0; - + // Loop through cells for (var j = 0; j < this.nodes[i].length; j++) { var cell = this.nodes[i][j]; - + if (!cell) { continue; } - + teamMass[i] += cell.getMass(); total += cell.getMass(); } diff --git a/src/gamemodes/Tournament.js b/src/gamemodes/Tournament.js index 1b622dbfb..8dd49c01c 100644 --- a/src/gamemodes/Tournament.js +++ b/src/gamemodes/Tournament.js @@ -1,248 +1,248 @@ -var Mode = require('./Mode'); - -function Tournament() { - Mode.apply(this, Array.prototype.slice.call(arguments)); - - this.ID = 10; - this.name = "Tournament"; - this.packetLB = 48; - - // Config (1 tick = 1000 ms) - this.prepTime = 5; // Amount of ticks after the server fills up to wait until starting the game - this.endTime = 15; // Amount of ticks after someone wins to restart the game - this.autoFill = false; - this.autoFillPlayers = 1; - this.dcTime = 0; - - // Gamemode Specific Variables - this.gamePhase = 0; // 0 = Waiting for players, 1 = Prepare to start, 2 = Game in progress, 3 = End - this.contenders = []; - this.maxContenders = 12; - - this.winner; - this.timer; - this.timeLimit = 3600; // in seconds -} - -module.exports = Tournament; -Tournament.prototype = new Mode(); - -// Gamemode Specific Functions - -Tournament.prototype.startGamePrep = function(gameServer) { - this.gamePhase = 1; - this.timer = this.prepTime; // 10 seconds -}; - -Tournament.prototype.startGame = function(gameServer) { - gameServer.run = true; - this.gamePhase = 2; - this.getSpectate(); // Gets a random person to spectate - gameServer.config.playerDisconnectTime = this.dcTime; // Reset config -}; - -Tournament.prototype.endGame = function(gameServer) { - this.winner = this.contenders[0]; - this.gamePhase = 3; - this.timer = this.endTime; // 30 Seconds -}; - -Tournament.prototype.endGameTimeout = function(gameServer) { - gameServer.run = false; - this.gamePhase = 4; - this.timer = this.endTime; // 30 Seconds -}; - -Tournament.prototype.fillBots = function(gameServer) { - // Fills the server with bots if there arent enough players - var fill = this.maxContenders - this.contenders.length; - for (var i = 0; i < fill; i++) { - gameServer.bots.addBot(); - } -}; - -Tournament.prototype.getSpectate = function() { - // Finds a random person to spectate - var index = Math.floor(Math.random() * this.contenders.length); - this.rankOne = this.contenders[index]; -}; - -Tournament.prototype.prepare = function(gameServer) { - // Remove all cells - var len = gameServer.nodes.length; - for (var i = 0; i < len; i++) { - var node = gameServer.nodes[0]; - - if (!node) { - continue; - } - - gameServer.removeNode(node); - } - - gameServer.bots.loadNames(); - - // Pauses the server - gameServer.run = false; - this.gamePhase = 0; - - // Get config values - if (gameServer.config.tourneyAutoFill > 0) { - this.timer = gameServer.config.tourneyAutoFill; - this.autoFill = true; - this.autoFillPlayers = gameServer.config.tourneyAutoFillPlayers; - } - // Handles disconnections - this.dcTime = gameServer.config.playerDisconnectTime; - gameServer.config.playerDisconnectTime = 0; - - this.prepTime = gameServer.config.tourneyPrepTime; - this.endTime = gameServer.config.tourneyEndTime; - this.maxContenders = gameServer.config.tourneyMaxPlayers; - - // Time limit - this.timeLimit = gameServer.config.tourneyTimeLimit * 60; // in seconds -}; - -Tournament.prototype.onPlayerDeath = function(gameServer) { - // Nothing -}; - -Tournament.prototype.formatTime = function(time) { - if (time < 0) { - return "0:00"; - } - // Format - var min = Math.floor(this.timeLimit / 60); - var sec = this.timeLimit % 60; - sec = (sec > 9) ? sec : "0" + sec.toString(); - return min + ":" + sec; -}; - -// Override - -Tournament.prototype.onServerInit = function(gameServer) { - this.prepare(gameServer); -}; - -Tournament.prototype.onPlayerSpawn = function(gameServer, player) { - // Only spawn players if the game hasnt started yet - if ((this.gamePhase == 0) && (this.contenders.length < this.maxContenders)) { - player.setColor(gameServer.getRandomColor()); // Random color - this.contenders.push(player); // Add to contenders list - gameServer.spawnPlayer(player); - - if (this.contenders.length == this.maxContenders) { - // Start the game once there is enough players - this.startGamePrep(gameServer); - } - } -}; - -Tournament.prototype.onCellRemove = function(cell) { - var owner = cell.owner, - human_just_died = false; - - if (owner.cells.length <= 0) { - // Remove from contenders list - var index = this.contenders.indexOf(owner); - if (index != -1) { - if ('_socket' in this.contenders[index].socket) { - human_just_died = true; - } - this.contenders.splice(index, 1); - } - - // Victory conditions - var humans = 0; - for (var i = 0; i < this.contenders.length; i++) { - if ('_socket' in this.contenders[i].socket) { - humans++; - } - } - - // the game is over if: - // 1) there is only 1 player left, OR - // 2) all the humans are dead, OR - // 3) the last-but-one human just died - if ((this.contenders.length == 1 || humans == 0 || (humans == 1 && human_just_died)) && this.gamePhase == 2) { - this.endGame(cell.owner.gameServer); - } else { - // Do stuff - this.onPlayerDeath(cell.owner.gameServer); - } - } -}; - -Tournament.prototype.updateLB = function(gameServer) { +var Mode = require('./Mode'); + +function Tournament() { + Mode.apply(this, Array.prototype.slice.call(arguments)); + + this.ID = 10; + this.name = "Tournament"; + this.packetLB = 48; + + // Config (1 tick = 1000 ms) + this.prepTime = 5; // Amount of ticks after the server fills up to wait until starting the game + this.endTime = 15; // Amount of ticks after someone wins to restart the game + this.autoFill = false; + this.autoFillPlayers = 1; + this.dcTime = 0; + + // Gamemode Specific Variables + this.gamePhase = 0; // 0 = Waiting for players, 1 = Prepare to start, 2 = Game in progress, 3 = End + this.contenders = []; + this.maxContenders = 12; + + this.winner; + this.timer; + this.timeLimit = 3600; // in seconds +} + +module.exports = Tournament; +Tournament.prototype = new Mode(); + +// Gamemode Specific Functions + +Tournament.prototype.startGamePrep = function (gameServer) { + this.gamePhase = 1; + this.timer = this.prepTime; // 10 seconds +}; + +Tournament.prototype.startGame = function (gameServer) { + gameServer.run = true; + this.gamePhase = 2; + this.getSpectate(); // Gets a random person to spectate + gameServer.config.playerDisconnectTime = this.dcTime; // Reset config +}; + +Tournament.prototype.endGame = function (gameServer) { + this.winner = this.contenders[0]; + this.gamePhase = 3; + this.timer = this.endTime; // 30 Seconds +}; + +Tournament.prototype.endGameTimeout = function (gameServer) { + gameServer.run = false; + this.gamePhase = 4; + this.timer = this.endTime; // 30 Seconds +}; + +Tournament.prototype.fillBots = function (gameServer) { + // Fills the server with bots if there arent enough players + var fill = this.maxContenders - this.contenders.length; + for (var i = 0; i < fill; i++) { + gameServer.bots.addBot(); + } +}; + +Tournament.prototype.getSpectate = function () { + // Finds a random person to spectate + var index = Math.floor(Math.random() * this.contenders.length); + this.rankOne = this.contenders[index]; +}; + +Tournament.prototype.prepare = function (gameServer) { + // Remove all cells + var len = gameServer.nodes.length; + for (var i = 0; i < len; i++) { + var node = gameServer.nodes[0]; + + if (!node) { + continue; + } + + gameServer.removeNode(node); + } + + gameServer.bots.loadNames(); + + // Pauses the server + gameServer.run = false; + this.gamePhase = 0; + + // Get config values + if (gameServer.config.tourneyAutoFill > 0) { + this.timer = gameServer.config.tourneyAutoFill; + this.autoFill = true; + this.autoFillPlayers = gameServer.config.tourneyAutoFillPlayers; + } + // Handles disconnections + this.dcTime = gameServer.config.playerDisconnectTime; + gameServer.config.playerDisconnectTime = 0; + + this.prepTime = gameServer.config.tourneyPrepTime; + this.endTime = gameServer.config.tourneyEndTime; + this.maxContenders = gameServer.config.tourneyMaxPlayers; + + // Time limit + this.timeLimit = gameServer.config.tourneyTimeLimit * 60; // in seconds +}; + +Tournament.prototype.onPlayerDeath = function (gameServer) { + // Nothing +}; + +Tournament.prototype.formatTime = function (time) { + if (time < 0) { + return "0:00"; + } + // Format + var min = Math.floor(this.timeLimit / 60); + var sec = this.timeLimit % 60; + sec = (sec > 9) ? sec : "0" + sec.toString(); + return min + ":" + sec; +}; + +// Override + +Tournament.prototype.onServerInit = function (gameServer) { + this.prepare(gameServer); +}; + +Tournament.prototype.onPlayerSpawn = function (gameServer, player) { + // Only spawn players if the game hasnt started yet + if ((this.gamePhase == 0) && (this.contenders.length < this.maxContenders)) { + player.setColor(gameServer.getRandomColor()); // Random color + this.contenders.push(player); // Add to contenders list + gameServer.spawnPlayer(player); + + if (this.contenders.length == this.maxContenders) { + // Start the game once there is enough players + this.startGamePrep(gameServer); + } + } +}; + +Tournament.prototype.onCellRemove = function (cell) { + var owner = cell.owner, + human_just_died = false; + + if (owner.cells.length <= 0) { + // Remove from contenders list + var index = this.contenders.indexOf(owner); + if (index != -1) { + if ('_socket' in this.contenders[index].socket) { + human_just_died = true; + } + this.contenders.splice(index, 1); + } + + // Victory conditions + var humans = 0; + for (var i = 0; i < this.contenders.length; i++) { + if ('_socket' in this.contenders[i].socket) { + humans++; + } + } + + // the game is over if: + // 1) there is only 1 player left, OR + // 2) all the humans are dead, OR + // 3) the last-but-one human just died + if ((this.contenders.length == 1 || humans == 0 || (humans == 1 && human_just_died)) && this.gamePhase == 2) { + this.endGame(cell.owner.gameServer); + } else { + // Do stuff + this.onPlayerDeath(cell.owner.gameServer); + } + } +}; + +Tournament.prototype.updateLB = function (gameServer) { gameServer.leaderboardType = this.packetLB; - var lb = gameServer.leaderboard; - - switch (this.gamePhase) { - case 0: - lb[0] = "Waiting for"; - lb[1] = "players: "; - lb[2] = this.contenders.length + "/" + this.maxContenders; - if (this.autoFill) { - if (this.timer <= 0) { - this.fillBots(gameServer); - } else if (this.contenders.length >= this.autoFillPlayers) { - this.timer--; - } - } - break; - case 1: - lb[0] = "Game starting in"; - lb[1] = this.timer.toString(); - lb[2] = "Good luck!"; - if (this.timer <= 0) { - // Reset the game - this.startGame(gameServer); - } else { - this.timer--; - } - break; - case 2: - lb[0] = "Players Remaining"; - lb[1] = this.contenders.length + "/" + this.maxContenders; - lb[2] = "Time Limit:"; - lb[3] = this.formatTime(this.timeLimit); - if (this.timeLimit < 0) { - // Timed out - this.endGameTimeout(gameServer); - } else { - this.timeLimit--; - } - break; - case 3: - lb[0] = "Congratulations"; - lb[1] = this.winner.getName(); - lb[2] = "for winning!"; - if (this.timer <= 0) { - // Reset the game - this.onServerInit(gameServer); - // Respawn starting food - gameServer.startingFood(); - } else { - lb[3] = "Game restarting in"; - lb[4] = this.timer.toString(); - this.timer--; - } - break; - case 4: - lb[0] = "Time Limit"; - lb[1] = "Reached!"; - if (this.timer <= 0) { - // Reset the game - this.onServerInit(gameServer); - // Respawn starting food - gameServer.startingFood(); - } else { - lb[2] = "Game restarting in"; - lb[3] = this.timer.toString(); - this.timer--; - } - default: - break; - } -}; + var lb = gameServer.leaderboard; + + switch (this.gamePhase) { + case 0: + lb[0] = "Waiting for"; + lb[1] = "players: "; + lb[2] = this.contenders.length + "/" + this.maxContenders; + if (this.autoFill) { + if (this.timer <= 0) { + this.fillBots(gameServer); + } else if (this.contenders.length >= this.autoFillPlayers) { + this.timer--; + } + } + break; + case 1: + lb[0] = "Game starting in"; + lb[1] = this.timer.toString(); + lb[2] = "Good luck!"; + if (this.timer <= 0) { + // Reset the game + this.startGame(gameServer); + } else { + this.timer--; + } + break; + case 2: + lb[0] = "Players Remaining"; + lb[1] = this.contenders.length + "/" + this.maxContenders; + lb[2] = "Time Limit:"; + lb[3] = this.formatTime(this.timeLimit); + if (this.timeLimit < 0) { + // Timed out + this.endGameTimeout(gameServer); + } else { + this.timeLimit--; + } + break; + case 3: + lb[0] = "Congratulations"; + lb[1] = this.winner.getName(); + lb[2] = "for winning!"; + if (this.timer <= 0) { + // Reset the game + this.onServerInit(gameServer); + // Respawn starting food + gameServer.startingFood(); + } else { + lb[3] = "Game restarting in"; + lb[4] = this.timer.toString(); + this.timer--; + } + break; + case 4: + lb[0] = "Time Limit"; + lb[1] = "Reached!"; + if (this.timer <= 0) { + // Reset the game + this.onServerInit(gameServer); + // Respawn starting food + gameServer.startingFood(); + } else { + lb[2] = "Game restarting in"; + lb[3] = this.timer.toString(); + this.timer--; + } + default: + break; + } +}; diff --git a/src/gamemodes/Zombie.js b/src/gamemodes/Zombie.js index af1e8b688..bb6a30dbd 100755 --- a/src/gamemodes/Zombie.js +++ b/src/gamemodes/Zombie.js @@ -1,8 +1,8 @@ -var Mode = require('./Mode'); +var Mode = require('./Mode'); function Zombie() { Mode.apply(this, Array.prototype.slice.call(arguments)); - + this.ID = 12; this.name = "Zombie FFA"; this.haveTeams = true; @@ -20,7 +20,7 @@ Zombie.prototype = new Mode(); // Gamemode Specific Functions -Zombie.prototype.leaderboardAddSort = function(player, leaderboard) { +Zombie.prototype.leaderboardAddSort = function (player, leaderboard) { // Adds the player and sorts the leaderboard var len = leaderboard.length - 1; var loop = true; @@ -38,7 +38,7 @@ Zombie.prototype.leaderboardAddSort = function(player, leaderboard) { } }; -Zombie.prototype.makeZombie = function(player) { +Zombie.prototype.makeZombie = function (player) { // turns a player into a zombie player.team = 0; player.setColor(this.zombieColor); @@ -57,7 +57,7 @@ Zombie.prototype.makeZombie = function(player) { // Override -Zombie.prototype.onPlayerSpawn = function(gameServer, player) { +Zombie.prototype.onPlayerSpawn = function (gameServer, player) { // make player a zombie if there are none if (this.zombies.length == 0) { player.team = 0; @@ -67,12 +67,12 @@ Zombie.prototype.onPlayerSpawn = function(gameServer, player) { player.team = player.pID; player.setColor(gameServer.getRandomColor()); } - + // Spawn player gameServer.spawnPlayer(player); }; -Zombie.prototype.onCellAdd = function(cell) { +Zombie.prototype.onCellAdd = function (cell) { // Add to team list if (cell.owner.getTeam() == 0) { this.zombies.push(cell); @@ -81,7 +81,7 @@ Zombie.prototype.onCellAdd = function(cell) { } }; -Zombie.prototype.onCellRemove = function(cell) { +Zombie.prototype.onCellRemove = function (cell) { // Remove from team list if (cell.owner.getTeam() == 0) { var index = this.zombies.indexOf(cell); @@ -100,16 +100,16 @@ Zombie.prototype.onCellRemove = function(cell) { Zombie.prototype.onCellMove = function (x1, y1, cell) { var team = cell.owner.getTeam(); var r = cell.getSize(); - + // Find team for (var i = 0; i < cell.owner.visibleNodes.length; i++) { // Only collide with player cells var check = cell.owner.visibleNodes[i]; - + if ((check.getType() != 0) || (cell.owner == check.owner)) { continue; } - + // Collision with zombies if (check.owner.getTeam() == team || check.owner.getTeam() == 0 || team == 0) { // Check if in collision range @@ -118,10 +118,10 @@ Zombie.prototype.onCellMove = function (x1, y1, cell) { // Skip continue; } - + // First collision check passed... now more precise checking dist = cell.getDist(cell.position.x, cell.position.y, check.position.x, check.position.y); - + // Calculations if (dist < collisionDist) { // Collided if (check.owner.getTeam() == 0 && team != 0) { @@ -135,7 +135,7 @@ Zombie.prototype.onCellMove = function (x1, y1, cell) { var newDeltaY = check.position.y - y1; var newDeltaX = check.position.x - x1; var newAngle = Math.atan2(newDeltaX, newDeltaY); - + var move = collisionDist - dist; check.setPosition({ @@ -147,7 +147,7 @@ Zombie.prototype.onCellMove = function (x1, y1, cell) { } }; -Zombie.prototype.updateLB = function(gameServer) { +Zombie.prototype.updateLB = function (gameServer) { gameServer.leaderboardType = this.packetLB; var lb = gameServer.leaderboard; // Loop through all clients @@ -155,13 +155,13 @@ Zombie.prototype.updateLB = function(gameServer) { if (typeof gameServer.clients[i] == "undefined" || gameServer.clients[i].playerTracker.team == 0) { continue; } - + var player = gameServer.clients[i].playerTracker; var playerScore = player.getScore(); if (player.cells.length <= 0) { continue; } - + if (lb.length == 0) { // Initial player lb.push(player); @@ -176,6 +176,6 @@ Zombie.prototype.updateLB = function(gameServer) { } } } - + this.rankOne = lb[0]; }; diff --git a/src/gamemodes/index.js b/src/gamemodes/index.js index 39758a9b4..25df2bdc3 100755 --- a/src/gamemodes/index.js +++ b/src/gamemodes/index.js @@ -1,4 +1,4 @@ -module.exports = { +module.exports = { Mode: require('./Mode'), FFA: require('./FFA'), Teams: require('./Teams'), @@ -11,34 +11,34 @@ module.exports = { TeamX: require('./TeamX.js') }; -var get = function(id) { +var get = function (id) { var mode; switch (id) { - case 1: // Teams + case 1:// Teams mode = new module.exports.Teams(); break; - case 2: // Experimental + case 2:// Experimental mode = new module.exports.Experimental(); break; - case 10: // Tournament + case 10:// Tournament mode = new module.exports.Tournament(); break; - case 11: // Hunger Games + case 11:// Hunger Games mode = new module.exports.HungerGames(); break; - case 12: // Zombie + case 12:// Zombie mode = new module.exports.Zombie(); break; - case 13: // Zombie Team + case 13:// Zombie Team mode = new module.exports.TeamZ(); break; - case 14: // Experimental Team + case 14:// Experimental Team mode = new module.exports.TeamX(); break; - case 20: // Rainbow + case 20:// Rainbow mode = new module.exports.Rainbow(); break; - default: // FFA is default + default:// FFA is default mode = new module.exports.FFA(); break; } diff --git a/src/index.js b/src/index.js index faf5a51d1..0eb9f5315 100644 --- a/src/index.js +++ b/src/index.js @@ -1,86 +1,86 @@ -// Imports +// Imports var pjson = require('../package.json'); -var Logger = require('./modules/Logger'); -var Commands = require('./modules/CommandList'); -var GameServer = require('./GameServer'); - -// Init variables -var showConsole = true; - -// Start msg -Logger.start(); - -process.on('exit', function (code) { - Logger.debug("process.exit(" + code + ")"); - Logger.shutdown(); -}); - -process.on('uncaughtException', function (err) { - Logger.fatal(err.stack); - process.exit(1); -}); - -Logger.info("\u001B[1m\u001B[32mMultiOgar " + pjson.version + "\u001B[37m - An open source multi-protocol ogar server\u001B[0m"); - - -// Handle arguments -process.argv.forEach(function(val) { - if (val == "--noconsole") { - showConsole = false; - } else if (val == "--help") { - console.log("Proper Usage: node index.js"); - console.log(" --noconsole Disables the console"); - console.log(" --help Help menu."); - console.log(""); - } -}); - -// Run Ogar -var gameServer = new GameServer(); -gameServer.start(); -// Add command handler -gameServer.commands = Commands.list; -// Initialize the server console -if (showConsole) { - var readline = require('readline'); - var in_ = readline.createInterface({ - input: process.stdin, - output: process.stdout - }); - setTimeout(prompt, 100); -} - -// Console functions - -function prompt() { - in_.question(">", function(str) { - try { - parseCommands(str); - } finally { - setTimeout(prompt, 0); - } - }); -} - -function parseCommands(str) { - // Log the string - Logger.write(">" + str); - - // Don't process ENTER - if (str === '') - return; - - // Splits the string - var split = str.split(" "); - - // Process the first string value - var first = split[0].toLowerCase(); - - // Get command function - var execute = gameServer.commands[first]; - if (typeof execute != 'undefined') { - execute(gameServer, split); - } else { - Logger.warn("Invalid Command!"); - } -} +var Logger = require('./modules/Logger'); +var Commands = require('./modules/CommandList'); +var GameServer = require('./GameServer'); + +// Init variables +var showConsole = true; + +// Start msg +Logger.start(); + +process.on('exit', function (code) { + Logger.debug("process.exit(" + code + ")"); + Logger.shutdown(); +}); + +process.on('uncaughtException', function (err) { + Logger.fatal(err.stack); + process.exit(1); +}); + +Logger.info("\u001B[1m\u001B[32mMultiOgar " + pjson.version + "\u001B[37m - An open source multi-protocol ogar server\u001B[0m"); + + +// Handle arguments +process.argv.forEach(function (val) { + if (val == "--noconsole") { + showConsole = false; + } else if (val == "--help") { + console.log("Proper Usage: node index.js"); + console.log(" --noconsole Disables the console"); + console.log(" --help Help menu."); + console.log(""); + } +}); + +// Run Ogar +var gameServer = new GameServer(); +gameServer.start(); +// Add command handler +gameServer.commands = Commands.list; +// Initialize the server console +if (showConsole) { + var readline = require('readline'); + var in_ = readline.createInterface({ + input: process.stdin, + output: process.stdout + }); + setTimeout(prompt, 100); +} + +// Console functions + +function prompt() { + in_.question(">", function (str) { + try { + parseCommands(str); + } finally { + setTimeout(prompt, 0); + } + }); +} + +function parseCommands(str) { + // Log the string + Logger.write(">" + str); + + // Don't process ENTER + if (str === '') + return; + + // Splits the string + var split = str.split(" "); + + // Process the first string value + var first = split[0].toLowerCase(); + + // Get command function + var execute = gameServer.commands[first]; + if (typeof execute != 'undefined') { + execute(gameServer, split); + } else { + Logger.warn("Invalid Command!"); + } +} diff --git a/src/modules/CommandList.js b/src/modules/CommandList.js index 827b0c734..000bc5996 100644 --- a/src/modules/CommandList.js +++ b/src/modules/CommandList.js @@ -1,615 +1,615 @@ -// Imports -var GameMode = require('../gamemodes'); -var Entity = require('../entity'); -var ini = require('./ini.js'); -var Logger = require('./Logger'); - -function Commands() { - this.list = {}; // Empty -} - -module.exports = Commands; - -// Utils -var fillChar = function(data, char, fieldLength, rTL) { - var result = data.toString(); - if (rTL === true) { - for (var i = result.length; i < fieldLength; i++) - result = char.concat(result); - } else { - for (var i = result.length; i < fieldLength; i++) - result = result.concat(char); - } - return result; -}; - -// Commands - -Commands.list = { - help: function(gameServer, split) { - console.log("======================== HELP ======================"); - console.log("addbot [number] : add bot to the server"); - console.log("kickbot [number] : kick a number of bots"); - console.log("ban [PlayerID | IP] : bans a(n) (player's) IP"); - console.log("banlist : get list of banned IPs."); - console.log("board [string] [string] ... : set scoreboard text"); - console.log("boardreset : reset scoreboard text"); - console.log("change [setting] [value] : change specified settings"); - console.log("clear : clear console output"); - console.log("color [PlayerID] [R] [G] [B] : set cell(s) color by client ID"); - console.log("exit : stop the server"); - console.log("food [X] [Y] [mass] : spawn food at specified Location"); - console.log("gamemode [id] : change server gamemode"); - console.log("kick [PlayerID] : kick player or bot by client ID"); - console.log("kickall : kick all players and bots"); - console.log("kill [PlayerID] : kill cell(s) by client ID"); - console.log("killall : kill everyone"); - console.log("mass [PlayerID] [mass] : set cell(s) mass by client ID"); - console.log("merge [PlayerID] : merge all client's cells once"); - console.log("name [PlayerID] [name] : change cell(s) name by client ID"); - console.log("playerlist : get list of players and bots"); - console.log("pause : pause game , freeze all cells"); - console.log("reload : reload config"); - console.log("status : get server status"); - console.log("tp [PlayerID] [X] [Y] : teleport player to specified location"); - console.log("unban [IP] : unban an IP"); - console.log("virus [X] [Y] [mass] : spawn virus at a specified Location"); - console.log("pl : alias for playerlist"); - console.log("st : alias for status"); - console.log("===================================================="); - }, - debug: function(gameServer, split) { - // Used for checking node lengths (for now) - - // Count client cells - var clientCells = 0; - for (var i in gameServer.clients) { - clientCells += gameServer.clients[i].playerTracker.cells.length; - } - // Output node information - console.log("Clients: " + fillChar(gameServer.clients.length, " ", 4, true) + " / " + gameServer.config.serverMaxConnections + " + bots"); - console.log("Total nodes:" + fillChar(gameServer.nodes.length, " ", 8, true)); - console.log("- Client cells: " + fillChar(clientCells, " ", 4, true) + " / " + (gameServer.clients.length * gameServer.config.playerMaxCells)); - console.log("- Ejected cells:" + fillChar(gameServer.nodesEjected.length, " ", 4, true)); - console.log("- Foods: " + fillChar(gameServer.currentFood, " ", 4, true) + " / " + gameServer.config.foodMaxAmount); - console.log("- Viruses: " + fillChar(gameServer.nodesVirus.length, " ", 4, true) + " / " + gameServer.config.virusMaxAmount); - console.log("Moving nodes: " + fillChar(gameServer.movingNodes.length, " ", 4, true)); - console.log("Quad nodes: " + fillChar(gameServer.quadTree.scanNodeCount(), " ", 4, true)); - console.log("Quad items: " + fillChar(gameServer.quadTree.scanItemCount(), " ", 4, true)); - }, - addbot: function(gameServer, split) { - var add = parseInt(split[1]); - if (isNaN(add)) { - add = 1; // Adds 1 bot if user doesnt specify a number - } - - for (var i = 0; i < add; i++) { - gameServer.bots.addBot(); - } - console.log("Added " + add + " player bots"); - }, - ban: function (gameServer, split) { - // Error message - var logInvalid = "Please specify a valid player ID or IP address!"; - - if (split[1] == null) { - // If no input is given; added to avoid error - Logger.warn(logInvalid); - return; - } - - if (split[1].indexOf(".") >= 0) { - // If input is an IP address - var ip = split[1]; - var ipParts = ip.split("."); - - // Check for invalid decimal numbers of the IP address - for (var i in ipParts) { - if (i > 1 && ipParts[i] == "*") { - // mask for sub-net - continue; - } - // If not numerical or if it's not between 0 and 255 - // TODO: Catch string "e" as it means "10^". - if (isNaN(ipParts[i]) || ipParts[i] < 0 || ipParts[i] >= 256) { - Logger.warn(logInvalid); - return; - } - } - - if (ipParts.length != 4) { - // an IP without 3 decimals - Logger.warn(logInvalid); - return; - } - - gameServer.banIp(ip); - return; - } - // if input is a Player ID - var id = parseInt(split[1]); - if (isNaN(id)) { - // If not numerical - Logger.warn(logInvalid); - return; - } - var ip = null; - for (var i in gameServer.clients) { - var client = gameServer.clients[i]; - if (client == null || !client.isConnected) - continue; - if (client.playerTracker.pID == id) { - ip = client._socket.remoteAddress; - break; - } - } - if (ip) - gameServer.banIp(ip); - else - Logger.warn("Player ID " + id + " not found!"); - }, - banlist: function(gameServer, split) { - Logger.print("Showing " + gameServer.ipBanList.length + " banned IPs: "); - Logger.print(" IP | IP "); - Logger.print("-----------------------------------"); - for (var i = 0; i < gameServer.ipBanList.length; i += 2) { - Logger.print(" " + fillChar(gameServer.ipBanList[i], " ", 15) + " | " - + (gameServer.ipBanList.length === i+1 ? "" : gameServer.ipBanList[i+1] ) - ); - } - }, - kickbot: function(gameServer, split) { - var toRemove = parseInt(split[1]); - if (isNaN(toRemove)) { - toRemove = -1; // Kick all bots if user doesnt specify a number - } - if (toRemove < 1) { - Logger.warn("Invalid argument!"); - return; - } - var removed = 0; - for (var i = 0; i < gameServer.clients.length; i++) { - var socket = gameServer.clients[i]; - if (socket.isConnected != null) continue; - socket.close(); - removed++; - if (removed >= toRemove) - break; - } - if (removed == 0) - Logger.warn("Cannot find any bots"); - else if (toRemove == removed) - Logger.warn("Kicked " + removed + " bots"); - else - Logger.warn("Only " + removed + " bots were kicked"); - }, - board: function(gameServer, split) { - var newLB = []; - for (var i = 1; i < split.length; i++) { - if (split[i]) { - newLB[i - 1] = split[i]; - } else { - newLB[i - 1] = " "; - } - } - - // Clears the update leaderboard function and replaces it with our own - gameServer.gameMode.packetLB = 48; - gameServer.gameMode.specByLeaderboard = false; - gameServer.gameMode.updateLB = function(gameServer) { - gameServer.leaderboard = newLB; - gameServer.leaderboardType = 48; - }; - console.log("Successfully changed leaderboard values"); - }, - boardreset: function(gameServer) { - // Gets the current gamemode - var gm = GameMode.get(gameServer.gameMode.ID); - - // Replace functions - gameServer.gameMode.packetLB = gm.packetLB; - gameServer.gameMode.updateLB = gm.updateLB; - console.log("Successfully reset leaderboard"); - }, - change: function (gameServer, split) { - if (split.length < 3) { - Logger.warn("Invalid command arguments"); - return; - } - var key = split[1]; - var value = split[2]; - - // Check if int/float - if (value.indexOf('.') != -1) { - value = parseFloat(value); - } else { - value = parseInt(value); - } - gameServer.changeConfig(key, value); - }, - clear: function() { - process.stdout.write("\u001b[2J\u001b[0;0H"); - }, - color: function(gameServer, split) { - // Validation checks - var id = parseInt(split[1]); - if (isNaN(id)) { - Logger.warn("Please specify a valid player ID!"); - return; - } - - var color = { - r: 0, - g: 0, - b: 0 - }; - color.r = Math.max(Math.min(parseInt(split[2]), 255), 0); - color.g = Math.max(Math.min(parseInt(split[3]), 255), 0); - color.b = Math.max(Math.min(parseInt(split[4]), 255), 0); - - // Sets color to the specified amount - for (var i in gameServer.clients) { - if (gameServer.clients[i].playerTracker.pID == id) { - var client = gameServer.clients[i].playerTracker; - client.setColor(color); // Set color - for (var j in client.cells) { - client.cells[j].setColor(color); - } - break; - } - } - }, - exit: function(gameServer, split) { - Logger.warn("Closing server..."); - gameServer.wsServer.close(); - process.exit(1); - }, - food: function(gameServer, split) { - var pos = { - x: parseInt(split[1]), - y: parseInt(split[2]) - }; - var mass = parseInt(split[3]); - - // Make sure the input values are numbers - if (isNaN(pos.x) || isNaN(pos.y)) { - Logger.warn("Invalid coordinates"); - return; - } - - var size = gameServer.config.foodMinMass; - if (!isNaN(mass)) { - size = Math.sqrt(mass * 100); - } - - // Spawn - var cell = new Entity.Food(gameServer, null, pos, size); - cell.setColor(gameServer.getRandomColor()); - gameServer.addNode(cell); - console.log("Spawned 1 food cell at (" + pos.x + " , " + pos.y + ")"); - }, - gamemode: function(gameServer, split) { - try { - var n = parseInt(split[1]); - var gm = GameMode.get(n); // If there is an invalid gamemode, the function will exit - gameServer.gameMode.onChange(gameServer); // Reverts the changes of the old gamemode - gameServer.gameMode = gm; // Apply new gamemode - gameServer.gameMode.onServerInit(gameServer); // Resets the server - console.log("Changed game mode to " + gameServer.gameMode.name); - } catch (err) { +// Imports +var GameMode = require('../gamemodes'); +var Entity = require('../entity'); +var ini = require('./ini.js'); +var Logger = require('./Logger'); + +function Commands() { + this.list = {}; // Empty +} + +module.exports = Commands; + +// Utils +var fillChar = function (data, char, fieldLength, rTL) { + var result = data.toString(); + if (rTL === true) { + for (var i = result.length; i < fieldLength; i++) + result = char.concat(result); + } else { + for (var i = result.length; i < fieldLength; i++) + result = result.concat(char); + } + return result; +}; + +// Commands + +Commands.list = { + help: function (gameServer, split) { + console.log("======================== HELP ======================"); + console.log("addbot [number] : add bot to the server"); + console.log("kickbot [number] : kick a number of bots"); + console.log("ban [PlayerID | IP] : bans a(n) (player's) IP"); + console.log("banlist : get list of banned IPs."); + console.log("board [string] [string] ... : set scoreboard text"); + console.log("boardreset : reset scoreboard text"); + console.log("change [setting] [value] : change specified settings"); + console.log("clear : clear console output"); + console.log("color [PlayerID] [R] [G] [B] : set cell(s) color by client ID"); + console.log("exit : stop the server"); + console.log("food [X] [Y] [mass] : spawn food at specified Location"); + console.log("gamemode [id] : change server gamemode"); + console.log("kick [PlayerID] : kick player or bot by client ID"); + console.log("kickall : kick all players and bots"); + console.log("kill [PlayerID] : kill cell(s) by client ID"); + console.log("killall : kill everyone"); + console.log("mass [PlayerID] [mass] : set cell(s) mass by client ID"); + console.log("merge [PlayerID] : merge all client's cells once"); + console.log("name [PlayerID] [name] : change cell(s) name by client ID"); + console.log("playerlist : get list of players and bots"); + console.log("pause : pause game , freeze all cells"); + console.log("reload : reload config"); + console.log("status : get server status"); + console.log("tp [PlayerID] [X] [Y] : teleport player to specified location"); + console.log("unban [IP] : unban an IP"); + console.log("virus [X] [Y] [mass] : spawn virus at a specified Location"); + console.log("pl : alias for playerlist"); + console.log("st : alias for status"); + console.log("===================================================="); + }, + debug: function (gameServer, split) { + // Used for checking node lengths (for now) + + // Count client cells + var clientCells = 0; + for (var i in gameServer.clients) { + clientCells += gameServer.clients[i].playerTracker.cells.length; + } + // Output node information + console.log("Clients: " + fillChar(gameServer.clients.length, " ", 4, true) + " / " + gameServer.config.serverMaxConnections + " + bots"); + console.log("Total nodes:" + fillChar(gameServer.nodes.length, " ", 8, true)); + console.log("- Client cells: " + fillChar(clientCells, " ", 4, true) + " / " + (gameServer.clients.length * gameServer.config.playerMaxCells)); + console.log("- Ejected cells:" + fillChar(gameServer.nodesEjected.length, " ", 4, true)); + console.log("- Foods: " + fillChar(gameServer.currentFood, " ", 4, true) + " / " + gameServer.config.foodMaxAmount); + console.log("- Viruses: " + fillChar(gameServer.nodesVirus.length, " ", 4, true) + " / " + gameServer.config.virusMaxAmount); + console.log("Moving nodes: " + fillChar(gameServer.movingNodes.length, " ", 4, true)); + console.log("Quad nodes: " + fillChar(gameServer.quadTree.scanNodeCount(), " ", 4, true)); + console.log("Quad items: " + fillChar(gameServer.quadTree.scanItemCount(), " ", 4, true)); + }, + addbot: function (gameServer, split) { + var add = parseInt(split[1]); + if (isNaN(add)) { + add = 1; // Adds 1 bot if user doesnt specify a number + } + + for (var i = 0; i < add; i++) { + gameServer.bots.addBot(); + } + console.log("Added " + add + " player bots"); + }, + ban: function (gameServer, split) { + // Error message + var logInvalid = "Please specify a valid player ID or IP address!"; + + if (split[1] == null) { + // If no input is given; added to avoid error + Logger.warn(logInvalid); + return; + } + + if (split[1].indexOf(".") >= 0) { + // If input is an IP address + var ip = split[1]; + var ipParts = ip.split("."); + + // Check for invalid decimal numbers of the IP address + for (var i in ipParts) { + if (i > 1 && ipParts[i] == "*") { + // mask for sub-net + continue; + } + // If not numerical or if it's not between 0 and 255 + // TODO: Catch string "e" as it means "10^". + if (isNaN(ipParts[i]) || ipParts[i] < 0 || ipParts[i] >= 256) { + Logger.warn(logInvalid); + return; + } + } + + if (ipParts.length != 4) { + // an IP without 3 decimals + Logger.warn(logInvalid); + return; + } + + gameServer.banIp(ip); + return; + } + // if input is a Player ID + var id = parseInt(split[1]); + if (isNaN(id)) { + // If not numerical + Logger.warn(logInvalid); + return; + } + var ip = null; + for (var i in gameServer.clients) { + var client = gameServer.clients[i]; + if (client == null || !client.isConnected) + continue; + if (client.playerTracker.pID == id) { + ip = client._socket.remoteAddress; + break; + } + } + if (ip) + gameServer.banIp(ip); + else + Logger.warn("Player ID " + id + " not found!"); + }, + banlist: function (gameServer, split) { + Logger.print("Showing " + gameServer.ipBanList.length + " banned IPs: "); + Logger.print(" IP | IP "); + Logger.print("-----------------------------------"); + for (var i = 0; i < gameServer.ipBanList.length; i += 2) { + Logger.print(" " + fillChar(gameServer.ipBanList[i], " ", 15) + " | " + + (gameServer.ipBanList.length === i + 1 ? "" : gameServer.ipBanList[i + 1]) + ); + } + }, + kickbot: function (gameServer, split) { + var toRemove = parseInt(split[1]); + if (isNaN(toRemove)) { + toRemove = -1; // Kick all bots if user doesnt specify a number + } + if (toRemove < 1) { + Logger.warn("Invalid argument!"); + return; + } + var removed = 0; + for (var i = 0; i < gameServer.clients.length; i++) { + var socket = gameServer.clients[i]; + if (socket.isConnected != null) continue; + socket.close(); + removed++; + if (removed >= toRemove) + break; + } + if (removed == 0) + Logger.warn("Cannot find any bots"); + else if (toRemove == removed) + Logger.warn("Kicked " + removed + " bots"); + else + Logger.warn("Only " + removed + " bots were kicked"); + }, + board: function (gameServer, split) { + var newLB = []; + for (var i = 1; i < split.length; i++) { + if (split[i]) { + newLB[i - 1] = split[i]; + } else { + newLB[i - 1] = " "; + } + } + + // Clears the update leaderboard function and replaces it with our own + gameServer.gameMode.packetLB = 48; + gameServer.gameMode.specByLeaderboard = false; + gameServer.gameMode.updateLB = function (gameServer) { + gameServer.leaderboard = newLB; + gameServer.leaderboardType = 48; + }; + console.log("Successfully changed leaderboard values"); + }, + boardreset: function (gameServer) { + // Gets the current gamemode + var gm = GameMode.get(gameServer.gameMode.ID); + + // Replace functions + gameServer.gameMode.packetLB = gm.packetLB; + gameServer.gameMode.updateLB = gm.updateLB; + console.log("Successfully reset leaderboard"); + }, + change: function (gameServer, split) { + if (split.length < 3) { + Logger.warn("Invalid command arguments"); + return; + } + var key = split[1]; + var value = split[2]; + + // Check if int/float + if (value.indexOf('.') != -1) { + value = parseFloat(value); + } else { + value = parseInt(value); + } + gameServer.changeConfig(key, value); + }, + clear: function () { + process.stdout.write("\u001b[2J\u001b[0;0H"); + }, + color: function (gameServer, split) { + // Validation checks + var id = parseInt(split[1]); + if (isNaN(id)) { + Logger.warn("Please specify a valid player ID!"); + return; + } + + var color = { + r: 0, + g: 0, + b: 0 + }; + color.r = Math.max(Math.min(parseInt(split[2]), 255), 0); + color.g = Math.max(Math.min(parseInt(split[3]), 255), 0); + color.b = Math.max(Math.min(parseInt(split[4]), 255), 0); + + // Sets color to the specified amount + for (var i in gameServer.clients) { + if (gameServer.clients[i].playerTracker.pID == id) { + var client = gameServer.clients[i].playerTracker; + client.setColor(color); // Set color + for (var j in client.cells) { + client.cells[j].setColor(color); + } + break; + } + } + }, + exit: function (gameServer, split) { + Logger.warn("Closing server..."); + gameServer.wsServer.close(); + process.exit(1); + }, + food: function (gameServer, split) { + var pos = { + x: parseInt(split[1]), + y: parseInt(split[2]) + }; + var mass = parseInt(split[3]); + + // Make sure the input values are numbers + if (isNaN(pos.x) || isNaN(pos.y)) { + Logger.warn("Invalid coordinates"); + return; + } + + var size = gameServer.config.foodMinMass; + if (!isNaN(mass)) { + size = Math.sqrt(mass * 100); + } + + // Spawn + var cell = new Entity.Food(gameServer, null, pos, size); + cell.setColor(gameServer.getRandomColor()); + gameServer.addNode(cell); + console.log("Spawned 1 food cell at (" + pos.x + " , " + pos.y + ")"); + }, + gamemode: function (gameServer, split) { + try { + var n = parseInt(split[1]); + var gm = GameMode.get(n); // If there is an invalid gamemode, the function will exit + gameServer.gameMode.onChange(gameServer); // Reverts the changes of the old gamemode + gameServer.gameMode = gm; // Apply new gamemode + gameServer.gameMode.onServerInit(gameServer); // Resets the server + console.log("Changed game mode to " + gameServer.gameMode.name); + } catch (err) { Logger.error(err.stack); - Logger.error("Invalid game mode selected"); - } - }, - kick: function(gameServer, split) { - var id = parseInt(split[1]); - if (isNaN(id)) { - Logger.warn("Please specify a valid player ID!"); - return; - } - gameServer.kickId(id); - }, - kickall: function (gameServer, split) { - gameServer.kickId(0); - }, - kill: function(gameServer, split) { - var id = parseInt(split[1]); - if (isNaN(id)) { - Logger.warn("Please specify a valid player ID!"); - return; - } - - var count = 0; - for (var i in gameServer.clients) { - if (gameServer.clients[i].playerTracker.pID == id) { - var client = gameServer.clients[i].playerTracker; - var len = client.cells.length; - for (var j = 0; j < len; j++) { - gameServer.removeNode(client.cells[0]); - count++; - } - - console.log("Removed " + count + " cells"); - break; - } - } - }, - killall: function(gameServer, split) { - var count = 0; - for (var i = 0; i < gameServer.clients.length; i++) { - var playerTracker = gameServer.clients[i].playerTracker; - while (playerTracker.cells.length > 0) { - gameServer.removeNode(playerTracker.cells[0]); - count++; - } - } - console.log("Removed " + count + " cells"); - }, - mass: function(gameServer, split) { - // Validation checks - var id = parseInt(split[1]); - if (isNaN(id)) { - Logger.warn("Please specify a valid player ID!"); - return; - } - - var amount = Math.max(parseInt(split[2]), 9); - if (isNaN(amount)) { - Logger.warn("Please specify a valid number"); - return; - } - var size = Math.sqrt(amount * 100); - - // Sets mass to the specified amount - for (var i in gameServer.clients) { - if (gameServer.clients[i].playerTracker.pID == id) { - var client = gameServer.clients[i].playerTracker; - for (var j in client.cells) { - client.cells[j].setSize(size); - } - - console.log("Set mass of " + client.getFriendlyName() + " to " + (size*size/100).toFixed(3)); - break; - } - } - }, - merge: function(gameServer, split) { - // Validation checks - var id = parseInt(split[1]); - var set = split[2]; - if (isNaN(id)) { - Logger.warn("Please specify a valid player ID!"); - return; - } - - // Find client with same ID as player entered - var client; - for (var i = 0; i < gameServer.clients.length; i++) { - if (id == gameServer.clients[i].playerTracker.pID) { - client = gameServer.clients[i].playerTracker; - break; - } - } - - if (!client) { - Logger.warn("Client is nonexistent!"); - return; - } - - if (client.cells.length == 1) { - Logger.warn("Client already has one cell!"); - return; - } - - // Set client's merge override - var state; - if (set == "true") { - client.mergeOverride = true; - client.mergeOverrideDuration = 100; - state = true; - } else if (set == "false") { - client.mergeOverride = false; - client.mergeOverrideDuration = 0; - state = false; - } else { - if (client.mergeOverride) { - client.mergeOverride = false; - client.mergeOverrideDuration = 0; - } else { - client.mergeOverride = true; - client.mergeOverrideDuration = 100; - } - - state = client.mergeOverride; - } - - // Log - if (state) console.log("Player " + id + " is now force merging"); - else console.log("Player " + id + " isn't force merging anymore"); - }, - name: function(gameServer, split) { - // Validation checks - var id = parseInt(split[1]); - if (isNaN(id)) { - Logger.warn("Please specify a valid player ID!"); - return; - } - - var name = split.slice(2, split.length).join(' '); - if (typeof name == 'undefined') { - Logger.warn("Please type a valid name"); - return; - } - - // Change name - for (var i = 0; i < gameServer.clients.length; i++) { - var client = gameServer.clients[i].playerTracker; - - if (client.pID == id) { - console.log("Changing " + client.getFriendlyName() + " to " + name); - client.setName(name); - return; - } - } - - // Error - Logger.warn("Player " + id + " was not found"); - }, - unban: function(gameServer, split) { - if (split.length < 2 || split[1] == null || split[1].trim().length < 1) { - Logger.warn("Please specify a valid IP!"); - return; - } - gameServer.unbanIp(split[1].trim()); - }, - playerlist: function(gameServer, split) { - Logger.print("Showing " + gameServer.clients.length + " players: "); - Logger.print(" ID | IP | P | " + fillChar('NICK', ' ', gameServer.config.playerMaxNickLength) + " | CELLS | SCORE | POSITION "); // Fill space - Logger.print(fillChar('', '-', ' ID | IP | | | CELLS | SCORE | POSITION '.length + gameServer.config.playerMaxNickLength)); - var sockets = gameServer.clients.slice(0); - sockets.sort(function (a, b) { return a.playerTracker.pID - b.playerTracker.pID; }); - for (var i = 0; i < sockets.length; i++) { - var socket = sockets[i]; - var client = socket.playerTracker; - - // ID with 3 digits length - var id = fillChar((client.pID), ' ', 6, true); - - // Get ip (15 digits length) - var ip = "[BOT]"; - if (socket.isConnected != null) { - ip = socket.remoteAddress; - } - ip = fillChar(ip, ' ', 15); - var protocol = gameServer.clients[i].packetHandler.protocol; - if (protocol == null) - protocol = "?" - // Get name and data - var nick = '', - cells = '', - score = '', - position = '', - data = ''; - if (socket.closeReason != null) { - // Disconnected - var reason = "[DISCONNECTED] "; - if (socket.closeReason.code) - reason += "[" + socket.closeReason.code + "] "; - if (socket.closeReason.message) - reason += socket.closeReason.message; - Logger.print(" " + id + " | " + ip + " | " + protocol + " | " + reason); - } else if (!socket.packetHandler.protocol && socket.isConnected) { - Logger.print(" " + id + " | " + ip + " | " + protocol + " | " + "[CONNECTING]"); - }else if (client.spectate) { - nick = "in free-roam"; - if (!client.freeRoam) { - var target = client.getSpectateTarget(); - if (target != null) { - nick = target.getFriendlyName(); - } - } - data = fillChar("SPECTATING: " + nick, '-', ' | CELLS | SCORE | POSITION '.length + gameServer.config.playerMaxNickLength, true); - Logger.print(" " + id + " | " + ip + " | " + protocol + " | " + data); - } else if (client.cells.length > 0) { - nick = fillChar(client.getFriendlyName(), ' ', gameServer.config.playerMaxNickLength); - cells = fillChar(client.cells.length, ' ', 5, true); - score = fillChar((client.getScore()/100) >> 0, ' ', 6, true); - position = fillChar(client.centerPos.x >> 0, ' ', 5, true) + ', ' + fillChar(client.centerPos.y >> 0, ' ', 5, true); - Logger.print(" " + id + " | " + ip + " | " + protocol + " | " + nick + " | " + cells + " | " + score + " | " + position); - } else { - // No cells = dead player or in-menu - data = fillChar('DEAD OR NOT PLAYING', '-', ' | CELLS | SCORE | POSITION '.length + gameServer.config.playerMaxNickLength, true); - Logger.print(" " + id + " | " + ip + " | " + protocol + " | " + data); - } - } - }, - pause: function(gameServer, split) { - gameServer.run = !gameServer.run; // Switches the pause state - var s = gameServer.run ? "Unpaused" : "Paused"; - console.log(s + " the game."); - }, - reload: function(gameServer) { - gameServer.loadConfig(); - gameServer.loadIpBanList(); - console.log("Reloaded the config file successfully"); - }, - status: function(gameServer, split) { - // Get amount of humans/bots - var humans = 0, - bots = 0; - for (var i = 0; i < gameServer.clients.length; i++) { - if ('_socket' in gameServer.clients[i]) { - humans++; - } else { - bots++; - } - } - - console.log("Connected players: " + gameServer.clients.length + "/" + gameServer.config.serverMaxConnections); - console.log("Players: " + humans + " - Bots: " + bots); - console.log("Server has been running for " + Math.floor(process.uptime()/60) + " minutes"); - console.log("Current memory usage: " + Math.round(process.memoryUsage().heapUsed / 1048576 * 10)/10 + "/" + Math.round(process.memoryUsage().heapTotal / 1048576 * 10)/10 + " mb"); - console.log("Current game mode: " + gameServer.gameMode.name); - console.log("Current update time: " + gameServer.updateTimeAvg.toFixed(3) + " [ms] (" + ini.getLagMessage(gameServer.updateTimeAvg) + ")"); - }, - tp: function(gameServer, split) { - var id = parseInt(split[1]); - if (isNaN(id)) { - Logger.warn("Please specify a valid player ID!"); - return; - } - - // Make sure the input values are numbers - var pos = { - x: parseInt(split[2]), - y: parseInt(split[3]) - }; - if (isNaN(pos.x) || isNaN(pos.y)) { - Logger.warn("Invalid coordinates"); - return; - } - - // Spawn - for (var i in gameServer.clients) { - if (gameServer.clients[i].playerTracker.pID == id) { - var client = gameServer.clients[i].playerTracker; - for (var j in client.cells) { - client.cells[j].setPosition(pos); - gameServer.updateNodeQuad(client.cells[j]); - } - - console.log("Teleported " + client.getFriendlyName() + " to (" + pos.x + " , " + pos.y + ")"); - break; - } - } - }, - virus: function(gameServer, split) { - var pos = { - x: parseInt(split[1]), - y: parseInt(split[2]) - }; - var mass = parseInt(split[3]); - - // Make sure the input values are numbers - if (isNaN(pos.x) || isNaN(pos.y)) { - Logger.warn("Invalid coordinates"); - return; - } - var size = gameServer.config.virusMinSize; - if (!isNaN(mass)) { - size = Math.sqrt(mass * 100); - } - - // Spawn - var v = new Entity.Virus(gameServer, null, pos, size); - gameServer.addNode(v); - console.log("Spawned 1 virus at (" + pos.x + " , " + pos.y + ")"); - }, - //Aliases - st: function (gameServer, split) { - Commands.list.status(gameServer, split); - }, - pl: function(gameServer, split){ - Commands.list.playerlist(gameServer, split); - } -}; + Logger.error("Invalid game mode selected"); + } + }, + kick: function (gameServer, split) { + var id = parseInt(split[1]); + if (isNaN(id)) { + Logger.warn("Please specify a valid player ID!"); + return; + } + gameServer.kickId(id); + }, + kickall: function (gameServer, split) { + gameServer.kickId(0); + }, + kill: function (gameServer, split) { + var id = parseInt(split[1]); + if (isNaN(id)) { + Logger.warn("Please specify a valid player ID!"); + return; + } + + var count = 0; + for (var i in gameServer.clients) { + if (gameServer.clients[i].playerTracker.pID == id) { + var client = gameServer.clients[i].playerTracker; + var len = client.cells.length; + for (var j = 0; j < len; j++) { + gameServer.removeNode(client.cells[0]); + count++; + } + + console.log("Removed " + count + " cells"); + break; + } + } + }, + killall: function (gameServer, split) { + var count = 0; + for (var i = 0; i < gameServer.clients.length; i++) { + var playerTracker = gameServer.clients[i].playerTracker; + while (playerTracker.cells.length > 0) { + gameServer.removeNode(playerTracker.cells[0]); + count++; + } + } + console.log("Removed " + count + " cells"); + }, + mass: function (gameServer, split) { + // Validation checks + var id = parseInt(split[1]); + if (isNaN(id)) { + Logger.warn("Please specify a valid player ID!"); + return; + } + + var amount = Math.max(parseInt(split[2]), 9); + if (isNaN(amount)) { + Logger.warn("Please specify a valid number"); + return; + } + var size = Math.sqrt(amount * 100); + + // Sets mass to the specified amount + for (var i in gameServer.clients) { + if (gameServer.clients[i].playerTracker.pID == id) { + var client = gameServer.clients[i].playerTracker; + for (var j in client.cells) { + client.cells[j].setSize(size); + } + + console.log("Set mass of " + client.getFriendlyName() + " to " + (size * size / 100).toFixed(3)); + break; + } + } + }, + merge: function (gameServer, split) { + // Validation checks + var id = parseInt(split[1]); + var set = split[2]; + if (isNaN(id)) { + Logger.warn("Please specify a valid player ID!"); + return; + } + + // Find client with same ID as player entered + var client; + for (var i = 0; i < gameServer.clients.length; i++) { + if (id == gameServer.clients[i].playerTracker.pID) { + client = gameServer.clients[i].playerTracker; + break; + } + } + + if (!client) { + Logger.warn("Client is nonexistent!"); + return; + } + + if (client.cells.length == 1) { + Logger.warn("Client already has one cell!"); + return; + } + + // Set client's merge override + var state; + if (set == "true") { + client.mergeOverride = true; + client.mergeOverrideDuration = 100; + state = true; + } else if (set == "false") { + client.mergeOverride = false; + client.mergeOverrideDuration = 0; + state = false; + } else { + if (client.mergeOverride) { + client.mergeOverride = false; + client.mergeOverrideDuration = 0; + } else { + client.mergeOverride = true; + client.mergeOverrideDuration = 100; + } + + state = client.mergeOverride; + } + + // Log + if (state) console.log("Player " + id + " is now force merging"); + else console.log("Player " + id + " isn't force merging anymore"); + }, + name: function (gameServer, split) { + // Validation checks + var id = parseInt(split[1]); + if (isNaN(id)) { + Logger.warn("Please specify a valid player ID!"); + return; + } + + var name = split.slice(2, split.length).join(' '); + if (typeof name == 'undefined') { + Logger.warn("Please type a valid name"); + return; + } + + // Change name + for (var i = 0; i < gameServer.clients.length; i++) { + var client = gameServer.clients[i].playerTracker; + + if (client.pID == id) { + console.log("Changing " + client.getFriendlyName() + " to " + name); + client.setName(name); + return; + } + } + + // Error + Logger.warn("Player " + id + " was not found"); + }, + unban: function (gameServer, split) { + if (split.length < 2 || split[1] == null || split[1].trim().length < 1) { + Logger.warn("Please specify a valid IP!"); + return; + } + gameServer.unbanIp(split[1].trim()); + }, + playerlist: function (gameServer, split) { + Logger.print("Showing " + gameServer.clients.length + " players: "); + Logger.print(" ID | IP | P | " + fillChar('NICK', ' ', gameServer.config.playerMaxNickLength) + " | CELLS | SCORE | POSITION "); // Fill space + Logger.print(fillChar('', '-', ' ID | IP | | | CELLS | SCORE | POSITION '.length + gameServer.config.playerMaxNickLength)); + var sockets = gameServer.clients.slice(0); + sockets.sort(function (a, b) { return a.playerTracker.pID - b.playerTracker.pID; }); + for (var i = 0; i < sockets.length; i++) { + var socket = sockets[i]; + var client = socket.playerTracker; + + // ID with 3 digits length + var id = fillChar((client.pID), ' ', 6, true); + + // Get ip (15 digits length) + var ip = "[BOT]"; + if (socket.isConnected != null) { + ip = socket.remoteAddress; + } + ip = fillChar(ip, ' ', 15); + var protocol = gameServer.clients[i].packetHandler.protocol; + if (protocol == null) + protocol = "?" + // Get name and data + var nick = '', + cells = '', + score = '', + position = '', + data = ''; + if (socket.closeReason != null) { + // Disconnected + var reason = "[DISCONNECTED] "; + if (socket.closeReason.code) + reason += "[" + socket.closeReason.code + "] "; + if (socket.closeReason.message) + reason += socket.closeReason.message; + Logger.print(" " + id + " | " + ip + " | " + protocol + " | " + reason); + } else if (!socket.packetHandler.protocol && socket.isConnected) { + Logger.print(" " + id + " | " + ip + " | " + protocol + " | " + "[CONNECTING]"); + } else if (client.spectate) { + nick = "in free-roam"; + if (!client.freeRoam) { + var target = client.getSpectateTarget(); + if (target != null) { + nick = target.getFriendlyName(); + } + } + data = fillChar("SPECTATING: " + nick, '-', ' | CELLS | SCORE | POSITION '.length + gameServer.config.playerMaxNickLength, true); + Logger.print(" " + id + " | " + ip + " | " + protocol + " | " + data); + } else if (client.cells.length > 0) { + nick = fillChar(client.getFriendlyName(), ' ', gameServer.config.playerMaxNickLength); + cells = fillChar(client.cells.length, ' ', 5, true); + score = fillChar((client.getScore() / 100) >> 0, ' ', 6, true); + position = fillChar(client.centerPos.x >> 0, ' ', 5, true) + ', ' + fillChar(client.centerPos.y >> 0, ' ', 5, true); + Logger.print(" " + id + " | " + ip + " | " + protocol + " | " + nick + " | " + cells + " | " + score + " | " + position); + } else { + // No cells = dead player or in-menu + data = fillChar('DEAD OR NOT PLAYING', '-', ' | CELLS | SCORE | POSITION '.length + gameServer.config.playerMaxNickLength, true); + Logger.print(" " + id + " | " + ip + " | " + protocol + " | " + data); + } + } + }, + pause: function (gameServer, split) { + gameServer.run = !gameServer.run; // Switches the pause state + var s = gameServer.run ? "Unpaused" : "Paused"; + console.log(s + " the game."); + }, + reload: function (gameServer) { + gameServer.loadConfig(); + gameServer.loadIpBanList(); + console.log("Reloaded the config file successfully"); + }, + status: function (gameServer, split) { + // Get amount of humans/bots + var humans = 0, + bots = 0; + for (var i = 0; i < gameServer.clients.length; i++) { + if ('_socket' in gameServer.clients[i]) { + humans++; + } else { + bots++; + } + } + + console.log("Connected players: " + gameServer.clients.length + "/" + gameServer.config.serverMaxConnections); + console.log("Players: " + humans + " - Bots: " + bots); + console.log("Server has been running for " + Math.floor(process.uptime() / 60) + " minutes"); + console.log("Current memory usage: " + Math.round(process.memoryUsage().heapUsed / 1048576 * 10) / 10 + "/" + Math.round(process.memoryUsage().heapTotal / 1048576 * 10) / 10 + " mb"); + console.log("Current game mode: " + gameServer.gameMode.name); + console.log("Current update time: " + gameServer.updateTimeAvg.toFixed(3) + " [ms] (" + ini.getLagMessage(gameServer.updateTimeAvg) + ")"); + }, + tp: function (gameServer, split) { + var id = parseInt(split[1]); + if (isNaN(id)) { + Logger.warn("Please specify a valid player ID!"); + return; + } + + // Make sure the input values are numbers + var pos = { + x: parseInt(split[2]), + y: parseInt(split[3]) + }; + if (isNaN(pos.x) || isNaN(pos.y)) { + Logger.warn("Invalid coordinates"); + return; + } + + // Spawn + for (var i in gameServer.clients) { + if (gameServer.clients[i].playerTracker.pID == id) { + var client = gameServer.clients[i].playerTracker; + for (var j in client.cells) { + client.cells[j].setPosition(pos); + gameServer.updateNodeQuad(client.cells[j]); + } + + console.log("Teleported " + client.getFriendlyName() + " to (" + pos.x + " , " + pos.y + ")"); + break; + } + } + }, + virus: function (gameServer, split) { + var pos = { + x: parseInt(split[1]), + y: parseInt(split[2]) + }; + var mass = parseInt(split[3]); + + // Make sure the input values are numbers + if (isNaN(pos.x) || isNaN(pos.y)) { + Logger.warn("Invalid coordinates"); + return; + } + var size = gameServer.config.virusMinSize; + if (!isNaN(mass)) { + size = Math.sqrt(mass * 100); + } + + // Spawn + var v = new Entity.Virus(gameServer, null, pos, size); + gameServer.addNode(v); + console.log("Spawned 1 virus at (" + pos.x + " , " + pos.y + ")"); + }, + //Aliases + st: function (gameServer, split) { + Commands.list.status(gameServer, split); + }, + pl: function (gameServer, split) { + Commands.list.playerlist(gameServer, split); + } +}; diff --git a/src/modules/Logger.js b/src/modules/Logger.js index 97c058e8e..fce97ab72 100644 --- a/src/modules/Logger.js +++ b/src/modules/Logger.js @@ -7,35 +7,35 @@ * */ -var fs = require("fs"); -var util = require('util'); -var EOL = require('os').EOL; +var fs = require("fs"); +var util = require('util'); +var EOL = require('os').EOL; var LogLevelEnum = require('../enum/LogLevelEnum'); - -module.exports.debug = debug; -module.exports.info = info; -module.exports.warn = warn; -module.exports.error = error; -module.exports.fatal = fatal; -module.exports.print = print; -module.exports.write = write; -module.exports.writeDebug = writeDebug; -module.exports.writeError = writeError; -module.exports.start = start; -module.exports.shutdown = shutdown; + +module.exports.debug = debug; +module.exports.info = info; +module.exports.warn = warn; +module.exports.error = error; +module.exports.fatal = fatal; +module.exports.print = print; +module.exports.write = write; +module.exports.writeDebug = writeDebug; +module.exports.writeError = writeError; +module.exports.start = start; +module.exports.shutdown = shutdown; module.exports.setVerbosity = function (level) { logVerbosity = level; -}; +}; module.exports.setFileVerbosity = function (level) { logFileVerbosity = level; -}; +}; module.exports.getVerbosity = function () { return logVerbosity; -}; +}; module.exports.getFileVerbosity = function () { return logFileVerbosity; -}; +}; var logVerbosity = LogLevelEnum.DEBUG; @@ -87,74 +87,74 @@ function writeError(message) { // --- utils --- function getDateTimeString() { - var date = new Date(); - var dy = date.getFullYear(); - var dm = date.getMonth() + 1; - var dd = date.getDate(); - var th = date.getHours(); - var tm = date.getMinutes(); - var ts = date.getSeconds(); - var tz = date.getMilliseconds(); - dy = ("0000" + dy).slice(-4); - dm = ("00" + dm).slice(-2); - dd = ("00" + dd).slice(-2); - th = ("00" + th).slice(-2); - tm = ("00" + tm).slice(-2); - ts = ("00" + ts).slice(-2); - tz = ("000" + tz).slice(-3); - return dy + "-" + dm + "-" + dd + "T" + th + "-" + tm + "-" + ts + "-" + tz; + var date = new Date(); + var dy = date.getFullYear(); + var dm = date.getMonth() + 1; + var dd = date.getDate(); + var th = date.getHours(); + var tm = date.getMinutes(); + var ts = date.getSeconds(); + var tz = date.getMilliseconds(); + dy = ("0000" + dy).slice(-4); + dm = ("00" + dm).slice(-2); + dd = ("00" + dd).slice(-2); + th = ("00" + th).slice(-2); + tm = ("00" + tm).slice(-2); + ts = ("00" + ts).slice(-2); + tz = ("000" + tz).slice(-3); + return dy + "-" + dm + "-" + dd + "T" + th + "-" + tm + "-" + ts + "-" + tz; }; function getTimeString() { - var date = new Date(); - var th = date.getHours(); - var tm = date.getMinutes(); - var ts = date.getSeconds(); - th = ("00" + th).slice(-2); - tm = ("00" + tm).slice(-2); - ts = ("00" + ts).slice(-2); - return th + ":" + tm + ":" + ts; + var date = new Date(); + var th = date.getHours(); + var tm = date.getMinutes(); + var ts = date.getSeconds(); + th = ("00" + th).slice(-2); + tm = ("00" + tm).slice(-2); + ts = ("00" + ts).slice(-2); + return th + ":" + tm + ":" + ts; }; function writeCon(color, level, message) { - if (level > logVerbosity) return; + if (level > logVerbosity) return; message = util.format(message); - var prefix = ""; - if (level == LogLevelEnum.DEBUG) - prefix = "[DEBUG] "; - else if (level == LogLevelEnum.INFO) - prefix = "[INFO ] "; - else if (level == LogLevelEnum.WARN) - prefix = "[WARN ] "; - else if (level == LogLevelEnum.ERROR) - prefix = "[ERROR] "; - else if (level == LogLevelEnum.FATAL) - prefix = "[FATAL] "; - process.stdout.write(color + prefix + message + "\u001B[0m" + EOL); + var prefix = ""; + if (level == LogLevelEnum.DEBUG) + prefix = "[DEBUG] "; + else if (level == LogLevelEnum.INFO) + prefix = "[INFO ] "; + else if (level == LogLevelEnum.WARN) + prefix = "[WARN ] "; + else if (level == LogLevelEnum.ERROR) + prefix = "[ERROR] "; + else if (level == LogLevelEnum.FATAL) + prefix = "[FATAL] "; + process.stdout.write(color + prefix + message + "\u001B[0m" + EOL); }; function writeLog(level, message) { - if (level > logFileVerbosity || writeError) - return; + if (level > logFileVerbosity || writeError) + return; message = util.format(message); - var prefix = ""; - if (level == LogLevelEnum.DEBUG) - prefix = "[DEBUG]"; - else if (level == LogLevelEnum.INFO) - prefix = "[INFO ]"; - else if (level == LogLevelEnum.WARN) - prefix = "[WARN ]"; - else if (level == LogLevelEnum.ERROR) - prefix = "[ERROR]"; - else if (level == LogLevelEnum.FATAL) - prefix = "[FATAL]"; - else if (level == LogLevelEnum.NONE) - prefix = "[NONE ]"; - prefix += "[" + getTimeString() + "] "; - - writeQueue.push(prefix + message + EOL); - if (writeShutdown) { - flushSync(); + var prefix = ""; + if (level == LogLevelEnum.DEBUG) + prefix = "[DEBUG]"; + else if (level == LogLevelEnum.INFO) + prefix = "[INFO ]"; + else if (level == LogLevelEnum.WARN) + prefix = "[WARN ]"; + else if (level == LogLevelEnum.ERROR) + prefix = "[ERROR]"; + else if (level == LogLevelEnum.FATAL) + prefix = "[FATAL]"; + else if (level == LogLevelEnum.NONE) + prefix = "[NONE ]"; + prefix += "[" + getTimeString() + "] "; + + writeQueue.push(prefix + message + EOL); + if (writeShutdown) { + flushSync(); } else { if (writeCounter == 0) { flushAsync(); @@ -166,88 +166,88 @@ var writeError = false; var writeCounter = 0; var writeShutdown = false; var writeStarted = false; -var writeQueue = []; +var writeQueue = []; function flushAsync() { if (writeShutdown || consoleLog == null || writeQueue.length == 0) return; - writeCounter++; - consoleLog.write(writeQueue.shift(), function () { writeCounter--; flushAsync(); }); + writeCounter++; + consoleLog.write(writeQueue.shift(), function () { writeCounter--; flushAsync(); }); }; function flushSync() { try { var tail = ""; while (writeQueue.length > 0) { - tail += writeQueue.shift(); + tail += writeQueue.shift(); } var fileName = logFolder + "/" + logFileName + ".log"; fs.appendFileSync(fileName, tail); } catch (err) { - writeError = true; - writeCon(colorRed + colorBright, LogLevelEnum.ERROR, err.message); - writeCon(colorRed + colorBright, LogLevelEnum.ERROR, "Failed to append log file!"); + writeError = true; + writeCon(colorRed + colorBright, LogLevelEnum.ERROR, err.message); + writeCon(colorRed + colorBright, LogLevelEnum.ERROR, "Failed to append log file!"); } }; function start() { - if (writeStarted) - return; - writeStarted = true; + if (writeStarted) + return; + writeStarted = true; try { - console.log = function (message) { print(message); }; - - var timeString = getDateTimeString(); + console.log = function (message) { print(message); }; + + var timeString = getDateTimeString(); var fileName = logFolder + "/" + logFileName + ".log"; - var fileName2 = logBackupFolder + "/" + logFileName + "-" + timeString + ".log"; + var fileName2 = logBackupFolder + "/" + logFileName + "-" + timeString + ".log"; if (!fs.existsSync(logFolder)) { - // Make log folder - fs.mkdirSync(logFolder); + // Make log folder + fs.mkdirSync(logFolder); } else if (fs.existsSync(fileName)) { if (!fs.existsSync(logBackupFolder)) { - // Make log backup folder - fs.mkdirSync(logBackupFolder); - } - // Backup previous log - fs.renameSync(fileName, fileName2); - } + // Make log backup folder + fs.mkdirSync(logBackupFolder); + } + // Backup previous log + fs.renameSync(fileName, fileName2); + } fs.writeFileSync(fileName, "=== Started " + timeString + " ===" + EOL); - var file = fs.createWriteStream(fileName, { flags: 'a' }); + var file = fs.createWriteStream(fileName, { flags: 'a' }); file.on('open', function () { if (writeShutdown) { - file.close(); - return; - } - consoleLog = file; - flushAsync(); - }); + file.close(); + return; + } + consoleLog = file; + flushAsync(); + }); file.on('error', function (err) { - writeError = true; - consoleLog = null; - writeCon(colorRed + colorBright, LogLevelEnum.ERROR, err.message); - }); + writeError = true; + consoleLog = null; + writeCon(colorRed + colorBright, LogLevelEnum.ERROR, err.message); + }); } catch (err) { - writeError = true; + writeError = true; consoleLog = null; - writeCon(colorRed + colorBright, LogLevelEnum.ERROR, err.message); - } -} - + writeCon(colorRed + colorBright, LogLevelEnum.ERROR, err.message); + } +} + function shutdown() { writeShutdown = true; if (writeError) return; if (consoleLog != null) { - consoleLog.end(); - consoleLog.close(); - consoleLog.destroy(); - consoleLog = null; - } - writeQueue.push("=== Shutdown " + getDateTimeString() + " ===" + EOL); - flushSync(); -}; - + consoleLog.end(); + consoleLog.close(); + consoleLog.destroy(); + consoleLog = null; + } + writeQueue.push("=== Shutdown " + getDateTimeString() + " ===" + EOL); + flushSync(); +}; + var logFolder = "./logs"; var logBackupFolder = "./logs/LogBackup"; diff --git a/src/modules/PlayerCommand.js b/src/modules/PlayerCommand.js index 3d92976cb..c9c78efbb 100644 --- a/src/modules/PlayerCommand.js +++ b/src/modules/PlayerCommand.js @@ -1,100 +1,100 @@ var Entity = require('../entity'); -var Logger = require('./Logger'); +var Logger = require('./Logger'); var UserRoleEnum = require("../enum/UserRoleEnum"); - -function PlayerCommand(gameServer, playerTracker) { - this.gameServer = gameServer; - this.playerTracker = playerTracker; -} - -module.exports = PlayerCommand; - -PlayerCommand.prototype.writeLine = function (text) { - this.gameServer.sendChatMessage(null, this.playerTracker, text); -}; - -PlayerCommand.prototype.executeCommandLine = function (commandLine) { - if (!commandLine) return; - var command = commandLine; - var args = ""; - var index = commandLine.indexOf(' '); - if (index >= 0) { - command = commandLine.slice(0, index); - args = commandLine.slice(index+1, commandLine.length); - } - command = command.trim().toLowerCase(); - var execute = playerCommands[command]; - if (typeof execute == 'function') { - execute.bind(this)(args); - } else { - this.writeLine("Unknown command, type /help for command list"); - } -}; - -var playerCommands = { - help: function (args) { - this.writeLine("/skin %shark - change skin"); - this.writeLine("/kill - self kill"); - this.writeLine("/help - this command list"); - }, - skin: function (args) { - if (this.playerTracker.cells.length > 0) { - this.writeLine("Cannot change skin while player in game!"); - return; - } - var skinName = ""; - if (args) skinName = args.trim(); - if (skinName.length > 16) - skinName = skinName.slice(0, 16); - this.playerTracker.setSkin(skinName); - if (skinName == "") - this.writeLine("Your skin was removed"); - else - this.writeLine("Your skin set to " + skinName); - }, - kill: function (args) { - if (this.playerTracker.cells.length < 1) { - this.writeLine("You cannot kill yourself, because you're still not joined to the game!"); - return; - } - while (this.playerTracker.cells.length > 0) { - var cell = this.playerTracker.cells[0]; - this.gameServer.removeNode(cell); + +function PlayerCommand(gameServer, playerTracker) { + this.gameServer = gameServer; + this.playerTracker = playerTracker; +} + +module.exports = PlayerCommand; + +PlayerCommand.prototype.writeLine = function (text) { + this.gameServer.sendChatMessage(null, this.playerTracker, text); +}; + +PlayerCommand.prototype.executeCommandLine = function (commandLine) { + if (!commandLine) return; + var command = commandLine; + var args = ""; + var index = commandLine.indexOf(' '); + if (index >= 0) { + command = commandLine.slice(0, index); + args = commandLine.slice(index + 1, commandLine.length); + } + command = command.trim().toLowerCase(); + var execute = playerCommands[command]; + if (typeof execute == 'function') { + execute.bind(this)(args); + } else { + this.writeLine("Unknown command, type /help for command list"); + } +}; + +var playerCommands = { + help: function (args) { + this.writeLine("/skin %shark - change skin"); + this.writeLine("/kill - self kill"); + this.writeLine("/help - this command list"); + }, + skin: function (args) { + if (this.playerTracker.cells.length > 0) { + this.writeLine("Cannot change skin while player in game!"); + return; + } + var skinName = ""; + if (args) skinName = args.trim(); + if (skinName.length > 16) + skinName = skinName.slice(0, 16); + this.playerTracker.setSkin(skinName); + if (skinName == "") + this.writeLine("Your skin was removed"); + else + this.writeLine("Your skin set to " + skinName); + }, + kill: function (args) { + if (this.playerTracker.cells.length < 1) { + this.writeLine("You cannot kill yourself, because you're still not joined to the game!"); + return; + } + while (this.playerTracker.cells.length > 0) { + var cell = this.playerTracker.cells[0]; + this.gameServer.removeNode(cell); // replace with food var food = new Entity.Food(this.gameServer, null, cell.position, this.gameServer.config.playerMinSize); food.setColor(this.gameServer.getGrayColor(cell.getColor())); this.gameServer.addNode(food); - } - this.writeLine("You killed yourself"); - }, + } + this.writeLine("You killed yourself"); + }, login: function (args) { - var password = (args || "").trim(); + var password = (args || "").trim(); if (password.length < 1) { - this.writeLine("ERROR: missing password argument!"); - return; - } - var user = this.gameServer.userLogin(this.playerTracker.socket.remoteAddress, password); + this.writeLine("ERROR: missing password argument!"); + return; + } + var user = this.gameServer.userLogin(this.playerTracker.socket.remoteAddress, password); if (!user) { - this.writeLine("ERROR: login failed!"); - return; - } - Logger.write("LOGIN " + this.playerTracker.socket.remoteAddress + ":" + this.playerTracker.socket.remotePort + " as \"" + user.name + "\""); - this.playerTracker.userRole = user.role; - this.playerTracker.userAuth = user.name; - this.writeLine("Login done as \"" + user.name + "\""); - return; - }, + this.writeLine("ERROR: login failed!"); + return; + } + Logger.write("LOGIN " + this.playerTracker.socket.remoteAddress + ":" + this.playerTracker.socket.remotePort + " as \"" + user.name + "\""); + this.playerTracker.userRole = user.role; + this.playerTracker.userAuth = user.name; + this.writeLine("Login done as \"" + user.name + "\""); + return; + }, logout: function (args) { if (this.playerTracker.userRole == UserRoleEnum.GUEST) { - this.writeLine("ERROR: not logged in"); - return; - } - Logger.write("LOGOUT " + this.playerTracker.socket.remoteAddress + ":" + this.playerTracker.socket.remotePort + " as \"" + this.playerTracker.userAuth + "\""); - this.playerTracker.userRole = UserRoleEnum.GUEST; - this.playerTracker.userAuth = null; - this.writeLine("Logout done"); - } -}; - - + this.writeLine("ERROR: not logged in"); + return; + } + Logger.write("LOGOUT " + this.playerTracker.socket.remoteAddress + ":" + this.playerTracker.socket.remotePort + " as \"" + this.playerTracker.userAuth + "\""); + this.playerTracker.userRole = UserRoleEnum.GUEST; + this.playerTracker.userAuth = null; + this.writeLine("Logout done"); + } +}; + + diff --git a/src/modules/ini.js b/src/modules/ini.js index 0e2e1a86f..5f277ed48 100644 --- a/src/modules/ini.js +++ b/src/modules/ini.js @@ -1,227 +1,227 @@ -exports.parse = exports.decode = decode; -exports.stringify = exports.encode = encode; - -exports.safe = safe; -exports.unsafe = unsafe; -exports.getLagMessage = getLagMessage; - -var eol = process.platform === "win32" ? "\r\n" : "\n"; - -function encode(obj, opt) { - var children = [], - out = ""; - - if (typeof opt === "string") { - opt = { - section: opt, - whitespace: false - }; - } else { - opt = opt || {}; - opt.whitespace = opt.whitespace === true; - } - - var separator = " = "; - - Object.keys(obj).forEach(function(k, _, __) { - var val = obj[k]; - if (val && Array.isArray(val)) { - val.forEach(function(item) { - out += safe(k + "[]") + separator + safe(item) + "\n"; - }); - } else if (val && typeof val === "object") { - children.push(k); - } else { - out += safe(k) + separator + safe(val) + eol; - } - }); - - if (opt.section && out.length) { - out = "[" + safe(opt.section) + "]" + eol + out; - } - - children.forEach(function(k, _, __) { - var nk = dotSplit(k).join('\\.'); - var section = (opt.section ? opt.section + "." : "") + nk; - var child = encode(obj[k], { - section: section, - whitespace: opt.whitespace - }); - if (out.length && child.length) { - out += eol; - } - out += child; - }); - - return out; -} - -function dotSplit(str) { - return str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002') - .replace(/\\\./g, '\u0001') - .split(/\./).map(function(part) { - return part.replace(/\1/g, '\\.') - .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001'); - }); -} - -function decode(str) { - var out = {}, - p = out, - state = "START", - // section |key = value - re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i, - lines = str.split(/[\r\n]+/g), - section = null; - - lines.forEach(function(line, _, __) { - var testLine = line.trim(); - - // skip empty lines or commented lines - if (!line || line.match(/^\s*[;#]/)) { - // skip commented lines - return; - } - // E.g. serverTimeout = 30 - // Returns ["serverTimeout = 30", undefined, "serverTimeout ", "= 30", "30"] - var match = line.match(re); - - if (!match) { - return; - } - - if (match[1] !== undefined) { - section = unsafe(match[1]); - p = out[section] = out[section] || {}; - return; - } - - var key = unsafe(match[2]), - value = match[3] ? unsafe((match[4] || "")) : true; - - // Convert keys with '[]' suffix to an array - if (key.length > 2 && key.slice(-2) === "[]") { - key = key.substring(0, key.length - 2); - if (!p[key]) { - p[key] = []; - } else if (!Array.isArray(p[key])) { - p[key] = [p[key]]; - } - } - - //// Mass to Size function catcher - if (startsWith(value, "massToSize(") && endsWith(value, ")")) { - // 11: length of "massToSize(" - var strValue = value.slice(11, value.length - 1).trim(); - value = Math.sqrt(parseFloat(strValue) * 100) + 0.5; - } - function startsWith(value, pattern) { - return value.length >= pattern.length && - value.indexOf(pattern) === 0; - }; - function endsWith(value, pattern) { - return value.length >= pattern.length && - value.lastIndexOf(pattern) === value.length - pattern.length; - }; - - // safeguard against resetting a previously defined - // array by accidentally forgetting the brackets - if (isNaN(value)) { +exports.parse = exports.decode = decode; +exports.stringify = exports.encode = encode; + +exports.safe = safe; +exports.unsafe = unsafe; +exports.getLagMessage = getLagMessage; + +var eol = process.platform === "win32" ? "\r\n" : "\n"; + +function encode(obj, opt) { + var children = [], + out = ""; + + if (typeof opt === "string") { + opt = { + section: opt, + whitespace: false + }; + } else { + opt = opt || {}; + opt.whitespace = opt.whitespace === true; + } + + var separator = " = "; + + Object.keys(obj).forEach(function (k, _, __) { + var val = obj[k]; + if (val && Array.isArray(val)) { + val.forEach(function (item) { + out += safe(k + "[]") + separator + safe(item) + "\n"; + }); + } else if (val && typeof val === "object") { + children.push(k); + } else { + out += safe(k) + separator + safe(val) + eol; + } + }); + + if (opt.section && out.length) { + out = "[" + safe(opt.section) + "]" + eol + out; + } + + children.forEach(function (k, _, __) { + var nk = dotSplit(k).join('\\.'); + var section = (opt.section ? opt.section + "." : "") + nk; + var child = encode(obj[k], { + section: section, + whitespace: opt.whitespace + }); + if (out.length && child.length) { + out += eol; + } + out += child; + }); + + return out; +} + +function dotSplit(str) { + return str.replace(/\1/g, '\u0002LITERAL\\1LITERAL\u0002') + .replace(/\\\./g, '\u0001') + .split(/\./).map(function (part) { + return part.replace(/\1/g, '\\.') + .replace(/\2LITERAL\\1LITERAL\2/g, '\u0001'); + }); +} + +function decode(str) { + var out = {}, + p = out, + state = "START", + // section |key = value + re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i, + lines = str.split(/[\r\n]+/g), + section = null; + + lines.forEach(function (line, _, __) { + var testLine = line.trim(); + + // skip empty lines or commented lines + if (!line || line.match(/^\s*[;#]/)) { + // skip commented lines + return; + } + // E.g. serverTimeout = 30 + // Returns ["serverTimeout = 30", undefined, "serverTimeout ", "= 30", "30"] + var match = line.match(re); + + if (!match) { + return; + } + + if (match[1] !== undefined) { + section = unsafe(match[1]); + p = out[section] = out[section] || {}; + return; + } + + var key = unsafe(match[2]), + value = match[3] ? unsafe((match[4] || "")) : true; + + // Convert keys with '[]' suffix to an array + if (key.length > 2 && key.slice(-2) === "[]") { + key = key.substring(0, key.length - 2); + if (!p[key]) { + p[key] = []; + } else if (!Array.isArray(p[key])) { + p[key] = [p[key]]; + } + } + + //// Mass to Size function catcher + if (startsWith(value, "massToSize(") && endsWith(value, ")")) { + // 11: length of "massToSize(" + var strValue = value.slice(11, value.length - 1).trim(); + value = Math.sqrt(parseFloat(strValue) * 100) + 0.5; + } + function startsWith(value, pattern) { + return value.length >= pattern.length && + value.indexOf(pattern) === 0; + }; + function endsWith(value, pattern) { + return value.length >= pattern.length && + value.lastIndexOf(pattern) === value.length - pattern.length; + }; + + // safeguard against resetting a previously defined + // array by accidentally forgetting the brackets + if (isNaN(value)) { p[key] = value; - } else if (isInt(value)) { - p[key] = parseInt(value); - } else { - p[key] = parseFloat(value); - } - }); - - // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}} - // use a filter to return the keys that have to be deleted. - Object.keys(out).filter(function(k, _, __) { - if (!out[k] || typeof out[k] !== "object" || Array.isArray(out[k])) return false; - // see if the parent section is also an object. - // if so, add it to that, and mark this one for deletion - var parts = dotSplit(k), - p = out, - l = parts.pop(), - nl = l.replace(/\\\./g, '.'); - parts.forEach(function(part, _, __) { - if (!p[part] || typeof p[part] !== "object") { - p[part] = {}; - } - p = p[part]; - }); - if (p === out && nl === l) { - return false; - } - p[nl] = out[k]; - return true; - }).forEach(function(del, _, __) { - delete out[del]; - }); - - return out; -} - -function isQuoted(val) { - return (val.charAt(0) === "\"" && val.slice(-1) === "\"") || (val.charAt(0) === "'" && val.slice(-1) === "'"); -} - -function safe(val) { - return (typeof val !== "string" || val.match(/[=\r\n]/) || val.match(/^\[/) || (val.length > 1 && isQuoted(val)) || val !== val.trim()) ? JSON.stringify(val) : val.replace(/;/g, '\\;').replace(/#/g, "\\#"); -} - -function unsafe(val, doUnesc) { - val = (val || "").trim(); - if (isQuoted(val)) { - // remove the single quotes before calling JSON.parse - if (val.charAt(0) === "'") { - val = val.substr(1, val.length - 2); - } - try { - val = JSON.parse(val); - } catch (err) { + } else if (isInt(value)) { + p[key] = parseInt(value); + } else { + p[key] = parseFloat(value); + } + }); + + // {a:{y:1},"a.b":{x:2}} --> {a:{y:1,b:{x:2}}} + // use a filter to return the keys that have to be deleted. + Object.keys(out).filter(function (k, _, __) { + if (!out[k] || typeof out[k] !== "object" || Array.isArray(out[k])) return false; + // see if the parent section is also an object. + // if so, add it to that, and mark this one for deletion + var parts = dotSplit(k), + p = out, + l = parts.pop(), + nl = l.replace(/\\\./g, '.'); + parts.forEach(function (part, _, __) { + if (!p[part] || typeof p[part] !== "object") { + p[part] = {}; + } + p = p[part]; + }); + if (p === out && nl === l) { + return false; + } + p[nl] = out[k]; + return true; + }).forEach(function (del, _, __) { + delete out[del]; + }); + + return out; +} + +function isQuoted(val) { + return (val.charAt(0) === "\"" && val.slice(-1) === "\"") || (val.charAt(0) === "'" && val.slice(-1) === "'"); +} + +function safe(val) { + return (typeof val !== "string" || val.match(/[=\r\n]/) || val.match(/^\[/) || (val.length > 1 && isQuoted(val)) || val !== val.trim()) ? JSON.stringify(val) : val.replace(/;/g, '\\;').replace(/#/g, "\\#"); +} + +function unsafe(val, doUnesc) { + val = (val || "").trim(); + if (isQuoted(val)) { + // remove the single quotes before calling JSON.parse + if (val.charAt(0) === "'") { + val = val.substr(1, val.length - 2); + } + try { + val = JSON.parse(val); + } catch (err) { Logger.error(err.stack); - } - } else { - // walk the val to find the first not-escaped ; character - var esc = false; - var unesc = ""; - for (var i = 0, l = val.length; i < l; i++) { - var c = val.charAt(i); - if (esc) { - if ("\\;#".indexOf(c) !== -1) - unesc += c; - else - unesc += "\\" + c; - esc = false; - } else if (";#".indexOf(c) !== -1) { - break; - } else if (c === "\\") { - esc = true; - } else { - unesc += c; - } - } - if (esc) - unesc += "\\"; - return unesc; - } - return val; -} - -var isInt = function(n) { - return parseInt(n) == n; -}; - -function getLagMessage(updateTimeAvg){ - if (updateTimeAvg < 20) - return "perfectly smooth"; - if (updateTimeAvg < 35) - return "good"; - if (updateTimeAvg < 40) - return "tiny lag"; - if (updateTimeAvg < 50) - return "lag"; - return "extremely high lag"; -} + } + } else { + // walk the val to find the first not-escaped ; character + var esc = false; + var unesc = ""; + for (var i = 0, l = val.length; i < l; i++) { + var c = val.charAt(i); + if (esc) { + if ("\\;#".indexOf(c) !== -1) + unesc += c; + else + unesc += "\\" + c; + esc = false; + } else if (";#".indexOf(c) !== -1) { + break; + } else if (c === "\\") { + esc = true; + } else { + unesc += c; + } + } + if (esc) + unesc += "\\"; + return unesc; + } + return val; +} + +var isInt = function (n) { + return parseInt(n) == n; +}; + +function getLagMessage(updateTimeAvg) { + if (updateTimeAvg < 20) + return "perfectly smooth"; + if (updateTimeAvg < 35) + return "good"; + if (updateTimeAvg < 40) + return "tiny lag"; + if (updateTimeAvg < 50) + return "lag"; + return "extremely high lag"; +} diff --git a/src/packet/AddNode.js b/src/packet/AddNode.js index a8539d7c1..7fe644109 100644 --- a/src/packet/AddNode.js +++ b/src/packet/AddNode.js @@ -1,11 +1,11 @@ -function AddNode(playerTracker, item) { +function AddNode(playerTracker, item) { this.playerTracker = playerTracker; this.item = item; } module.exports = AddNode; -AddNode.prototype.build = function(protocol) { +AddNode.prototype.build = function (protocol) { var buffer = new Buffer(5); buffer.writeUInt8(0x20, 0, true); // Packet ID buffer.writeUInt32LE((this.item.nodeId ^ this.playerTracker.scrambleId) >>> 0, 1, true); diff --git a/src/packet/BinaryReader.js b/src/packet/BinaryReader.js index 43567514e..bb2cb58e4 100644 --- a/src/packet/BinaryReader.js +++ b/src/packet/BinaryReader.js @@ -107,12 +107,12 @@ BinaryReader.prototype.readStringZeroUtf8 = function () { BinaryReader.prototype.readStringZeroUnicode = function () { var length = 0; var terminatorLength = ((this._buffer.length - this._offset) & 1) != 0 ? 1 : 0; - for (var i = this._offset; i+1 < this._buffer.length; i+=2) { + for (var i = this._offset; i + 1 < this._buffer.length; i += 2) { if (this._buffer.readUInt16LE(i) == 0) { terminatorLength = 2; break; } - length+=2; + length += 2; } var value = this.readStringUnicode(length); this._offset += terminatorLength; diff --git a/src/packet/ChatMessage.js b/src/packet/ChatMessage.js index b5e15a7f1..b3a5fdaea 100644 --- a/src/packet/ChatMessage.js +++ b/src/packet/ChatMessage.js @@ -27,7 +27,7 @@ ChatMessage.prototype.build = function (protocol) { color = this.sender.cells[0].getColor(); } } - + var writer = new BinaryWriter(); writer.writeUInt8(0x63); // message id (decimal 99) @@ -39,7 +39,7 @@ ChatMessage.prototype.build = function (protocol) { flags = 0x40; // admin message else if (this.sender.userRole == UserRoleEnum.MODER) flags = 0x20; // moder message - + writer.writeUInt8(flags); writer.writeUInt8(color.r >> 0); writer.writeUInt8(color.g >> 0); diff --git a/src/packet/ClearAll.js b/src/packet/ClearAll.js index 59c4f742f..cdc24a1ff 100644 --- a/src/packet/ClearAll.js +++ b/src/packet/ClearAll.js @@ -1,4 +1,4 @@ -function ClearAll() { } +function ClearAll() { } module.exports = ClearAll; diff --git a/src/packet/DrawLine.js b/src/packet/DrawLine.js index e78091c33..9114d9fcc 100644 --- a/src/packet/DrawLine.js +++ b/src/packet/DrawLine.js @@ -1,11 +1,11 @@ -function DrawLine(x, y) { +function DrawLine(x, y) { this.x = x; this.y = y; } module.exports = DrawLine; -DrawLine.prototype.build = function(protocol) { +DrawLine.prototype.build = function (protocol) { var buffer = new Buffer(5); buffer.writeUInt8(0x15, 0); buffer.writeInt16LE(this.x, 1, true); diff --git a/src/packet/SetBorder.js b/src/packet/SetBorder.js index b1b599304..b80454417 100644 --- a/src/packet/SetBorder.js +++ b/src/packet/SetBorder.js @@ -1,4 +1,4 @@ -// Import +// Import var BinaryWriter = require("./BinaryWriter"); diff --git a/src/packet/UpdateLeaderboard.js b/src/packet/UpdateLeaderboard.js index 530ffcc7d..509992069 100644 --- a/src/packet/UpdateLeaderboard.js +++ b/src/packet/UpdateLeaderboard.js @@ -1,4 +1,4 @@ -// Import +// Import var BinaryWriter = require("./BinaryWriter"); @@ -62,13 +62,13 @@ UpdateLeaderboard.prototype.buildFfa5 = function () { for (var i = 0; i < this.leaderboard.length; i++) { var item = this.leaderboard[i]; if (item == null) return null; // bad leaderboardm just don't send it - + var name = item.getNameUnicode(); var id = 0; if (item == player && item.cells.length > 0) { id = item.cells[0].nodeId ^ this.playerTracker.scrambleId; } - + writer.writeUInt32(id >>> 0); // Player cell Id if (name != null) writer.writeBytes(name); diff --git a/src/packet/UpdateNodes.js b/src/packet/UpdateNodes.js index ec155382c..401fe3327 100644 --- a/src/packet/UpdateNodes.js +++ b/src/packet/UpdateNodes.js @@ -1,9 +1,9 @@ -// Import +// Import var BinaryWriter = require("./BinaryWriter"); function UpdateNodes(playerTracker, addNodes, updNodes, eatNodes, delNodes) { - this.playerTracker = playerTracker; + this.playerTracker = playerTracker; this.addNodes = addNodes; this.updNodes = updNodes; this.eatNodes = eatNodes; @@ -18,11 +18,11 @@ UpdateNodes.prototype.build = function (protocol) { var writer = new BinaryWriter(); writer.writeUInt8(0x10); // Packet ID this.writeEatItems(writer); - + if (protocol < 5) this.writeUpdateItems4(writer); else if (protocol == 5) this.writeUpdateItems5(writer); else this.writeUpdateItems6(writer); - + this.writeRemoveItems(writer, protocol); return writer.toBuffer(); }; @@ -32,7 +32,7 @@ UpdateNodes.prototype.writeUpdateItems4 = function (writer) { var scrambleX = this.playerTracker.scrambleX; var scrambleY = this.playerTracker.scrambleY; var scrambleId = this.playerTracker.scrambleId; - + for (var i = 0; i < this.updNodes.length; i++) { var node = this.updNodes[i]; if (node.nodeId == 0) diff --git a/src/packet/UpdatePosition.js b/src/packet/UpdatePosition.js index 7a0b4c9b7..c92a1110a 100644 --- a/src/packet/UpdatePosition.js +++ b/src/packet/UpdatePosition.js @@ -1,4 +1,4 @@ -function UpdatePosition(playerTracker, x, y, scale) { +function UpdatePosition(playerTracker, x, y, scale) { this.playerTracker = playerTracker, this.x = x; this.y = y; @@ -7,7 +7,7 @@ function UpdatePosition(playerTracker, x, y, scale) { module.exports = UpdatePosition; -UpdatePosition.prototype.build = function(protocol) { +UpdatePosition.prototype.build = function (protocol) { var buffer = new Buffer(13); var offset = 0; buffer.writeUInt8(0x11, offset, true); diff --git a/src/packet/index.js b/src/packet/index.js index a78ad28f5..5f4003785 100644 --- a/src/packet/index.js +++ b/src/packet/index.js @@ -1,4 +1,4 @@ -module.exports = { +module.exports = { BinaryWriter: require('./BinaryWriter'), BinaryReader: require('./BinaryReader'), ChatMessage: require('./ChatMessage'), diff --git a/src/userRoles.json b/src/userRoles.json index cf59cba76..ccbd07562 100644 --- a/src/userRoles.json +++ b/src/userRoles.json @@ -1,20 +1,20 @@ [ - { - "ip":"127.0.0.1", - "password":"", - "role":"ADMIN", - "name":"Local Administrator" - }, - { - "ip":"127.0.0.1", - "password":"", - "role":"MODER", - "name":"Local Moderator" - }, - { - "ip":"127.0.0.1", - "password":"", - "role":"USER", - "name":"Local User" - } -] \ No newline at end of file + { + "ip":"127.0.0.1", + "password":"", + "role":"ADMIN", + "name":"Local Administrator" + }, + { + "ip":"127.0.0.1", + "password":"", + "role":"MODER", + "name":"Local Moderator" + }, + { + "ip":"127.0.0.1", + "password":"", + "role":"USER", + "name":"Local User" + } +]