From 5f1b58fd8690f9dc867a515c6238d34f695051f9 Mon Sep 17 00:00:00 2001 From: Daniel Xie Date: Thu, 15 Dec 2016 16:22:42 -0600 Subject: [PATCH] Evaluator + Netscript should now properly handle errors in syntax/runtime errors (almost..still have to implement the properly closing down script when an error is thrown. Check file for TODO). Player skill level should now properly be updated --- README.md | 14 ++- src/Netscript/Evaluator.js | 162 +++++++++++++++++-------------- src/Netscript/NetscriptWorker.js | 18 +++- src/Player.js | 16 ++- src/Script.js | 2 + src/engine.js | 44 +++++---- utils/StringHelperFunctions.js | 20 ++++ 7 files changed, 172 insertions(+), 104 deletions(-) create mode 100644 utils/StringHelperFunctions.js diff --git a/README.md b/README.md index b10681ed3..7c5e3c9fe 100644 --- a/README.md +++ b/README.md @@ -13,16 +13,24 @@ TESTING TODO: Should work automatically...because your money gained percentage will be multiplied by 0 When the game is loaded re-load all of the scripts in runningScripts - Seems to be working + Update skill level on cycle + If a script has bad syntax...it fucks everything up when you try to run it so fix that + Try catch for script? + Check that killing scripts still works fine (TESTED - LOoks to work fine) + Check that if script has bad syntax it wont run at all and everthing works normally + Check if script throws during runtime it shuts down correctly + Tasks TODO: Script offline progress - If a script has bad syntax...it fucks everything up when you try to run it so fix that + + Scroll all the way down when something is post()ed Scripts tab that shows script stats Script logging functionality? Logs to internal "log file" (property of script itself) - Update skill level on cycle Parse script firs tot see if there are any syntax errors, and tell user if there are (when user calls "run") Tutorial and help Server growth Companies Factions - Update CONSTANTS.HelpText \ No newline at end of file + Update CONSTANTS.HelpText + Account for Max possible int when gaining exp \ No newline at end of file diff --git a/src/Netscript/Evaluator.js b/src/Netscript/Evaluator.js index 5f0f316eb..1c8d1e29f 100644 --- a/src/Netscript/Evaluator.js +++ b/src/Netscript/Evaluator.js @@ -28,15 +28,15 @@ function evaluate(exp, workerScript) { if (env.stopFlag) {reject(workerScript);} if (exp.left.type != "var") - throw new Error("Cannot assign to " + JSON.stringify(exp.left)); + throw new Error("|" + workerScript.serverIp + "|" + workerScript.name + "| Cannot assign to " + JSON.stringify(exp.left)); var p = new Promise(function(resolve, reject) { setTimeout(function() { var expRightPromise = evaluate(exp.right, workerScript); expRightPromise.then(function(expRight) { resolve(expRight); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }, CONSTANTS.CodeInstructionRunTime) }); @@ -46,8 +46,8 @@ function evaluate(exp, workerScript) { env.set(exp.left.value, expRight); console.log("Assign operation finished"); resolve("assignFinished"); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }); @@ -61,8 +61,8 @@ function evaluate(exp, workerScript) { var promise = evaluate(exp.left, workerScript); promise.then(function(valLeft) { resolve(valLeft); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }, CONSTANTS.CodeInstructionRunTime); }); @@ -73,20 +73,24 @@ function evaluate(exp, workerScript) { var promise = evaluate(exp.right, workerScript); promise.then(function(valRight) { resolve([valLeft, valRight]); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }, CONSTANTS.CodeInstructionRunTime); }); pRight.then(function(args) { console.log("Resolving binary operation"); - resolve(apply_op(exp.operator, args[0], args[1])); - }, function() { - reject(workerScript); + try { + resolve(apply_op(exp.operator, args[0], args[1])); + } catch (e) { + reject("|" + workerScript.serverIp + "|" + workerScript.name + "|" + e.toString()); + } + }, function(e) { + reject(e); }); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }); break; @@ -96,7 +100,7 @@ function evaluate(exp, workerScript) { var numConds = exp.cond.length; var numThens = exp.then.length; if (numConds == 0 || numThens == 0 || numConds != numThens) { - throw new Error ("Number of conds and thens in if structure don't match (or there are none)"); + throw new Error ("|" + workerScript.serverIp + "|" + workerScript.name + "|Number of conds and thens in if structure don't match (or there are none)"); } for (var i = 0; i < numConds; i++) { @@ -118,8 +122,8 @@ function evaluate(exp, workerScript) { var resInit = evaluate(exp.init, workerScript); resInit.then(function(foo) { resolve(resInit); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }, CONSTANTS.CodeInstructionRunTime); }); @@ -128,11 +132,11 @@ function evaluate(exp, workerScript) { var pForLoop = evaluateFor(exp, workerScript); pForLoop.then(function(forLoopRes) { resolve("forLoopDone"); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }); break; @@ -144,8 +148,8 @@ function evaluate(exp, workerScript) { var pEvaluateWhile = evaluateWhile(exp, workerScript); pEvaluateWhile.then(function(whileLoopRes) { resolve("whileLoopDone"); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }); break; @@ -156,8 +160,8 @@ function evaluate(exp, workerScript) { var evaluateProgPromise = evaluateProg(exp, workerScript, 0); evaluateProgPromise.then(function(w) { resolve(workerScript); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }); break; @@ -181,7 +185,7 @@ function evaluate(exp, workerScript) { if (exp.func.value == "hack") { console.log("Execute hack()"); if (exp.args.length != 1) { - throw new Error("Hack() call has incorrect number of arguments. Takes 1 argument"); + throw new Error("|" + workerScript.serverIp + "|" + workerScript.name + "|Hack() call has incorrect number of arguments. Takes 1 argument"); } //IP of server to hack @@ -194,8 +198,6 @@ function evaluate(exp, workerScript) { var hackingTime = scriptCalculateHackingTime(server); //This is in seconds console.log("Calculated hackingTime"); - //TODO Add a safeguard to prevent a script from hacking a Server that the player - //cannot hack if (server.hasAdminRights == false) { console.log("Cannot hack server " + server.hostname); resolve("Cannot hack"); @@ -203,7 +205,7 @@ function evaluate(exp, workerScript) { } var p = new Promise(function(resolve, reject) { - if (env.stopFlag) {console.log("rejected"); reject(workerScript);} + if (env.stopFlag) {reject(workerScript);} console.log("Hacking " + server.hostname + " after " + hackingTime.toString() + " seconds."); setTimeout(function() { var hackChance = scriptCalculateHackingChance(server); @@ -234,18 +236,17 @@ function evaluate(exp, workerScript) { p.then(function(res) { resolve("hackExecuted"); - }, function(reason) { - console.log("rejected. reason: " + reason); - reject(workerScript); + }, function(e) { + reject(e); }); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); } else if (exp.func.value == "sleep") { console.log("Execute sleep()"); if (exp.args.length != 1) { - throw new Error("Sleep() call has incorrect number of arguments. Takes 1 argument."); + throw new Error("|" + workerScript.serverIp + "|" + workerScript.name + "|Sleep() call has incorrect number of arguments. Takes 1 argument."); } var sleepTimePromise = evaluate(exp.args[0], workerScript); @@ -259,17 +260,17 @@ function evaluate(exp, workerScript) { p.then(function(res) { resolve("sleepExecuted"); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); - }, function() { - reject(workerScript) + }, function(e) { + reject(e) }); } else if (exp.func.value == "print") { if (exp.args.length != 1) { - throw new Error("Print() call has incorrect number of arguments. Takes 1 argument"); + throw new Error("|" + workerScript.serverIp + "|" + workerScript.name + "| Print() call has incorrect number of arguments. Takes 1 argument"); } var p = new Promise(function(resolve, reject) { @@ -277,8 +278,8 @@ function evaluate(exp, workerScript) { var evaluatePromise = evaluate(exp.args[0], workerScript); evaluatePromise.then(function(res) { resolve(res); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }, CONSTANTS.CodeInstructionRunTime); }); @@ -287,8 +288,8 @@ function evaluate(exp, workerScript) { post(res.toString()); console.log("Print call executed"); resolve("printExecuted"); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); } }, CONSTANTS.CodeInstructionRunTime); @@ -296,22 +297,25 @@ function evaluate(exp, workerScript) { break; default: - throw new Error("I don't know how to evaluate " + exp.type); + throw new Error("|" + workerScript.serverIp + "|" + workerScript.name + "| Can't evaluate type " + exp.type); } } //Evaluate the looping part of a for loop (Initialization block is NOT done in here) function evaluateFor(exp, workerScript) { + var env = workerScript.env; console.log("evaluateFor() called"); return new Promise(function(resolve, reject) { + if (env.stopFlag) {reject(workerScript);} + var pCond = new Promise(function(resolve, reject) { setTimeout(function() { var evaluatePromise = evaluate(exp.cond, workerScript); evaluatePromise.then(function(resCond) { console.log("Conditional evaluated to: " + resCond); resolve(resCond); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }, CONSTANTS.CodeInstructionRunTime); }); @@ -326,8 +330,8 @@ function evaluateFor(exp, workerScript) { evaluatePromise.then(function(resCode) { console.log("Evaluated an iteration of for loop code"); resolve(resCode); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }, CONSTANTS.CodeInstructionRunTime); }); @@ -340,8 +344,8 @@ function evaluateFor(exp, workerScript) { evaluatePromise.then(function(foo) { console.log("Evaluated for loop postloop"); resolve("postLoopFinished"); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }, CONSTANTS.CodeInstructionRunTime); }); @@ -350,37 +354,41 @@ function evaluateFor(exp, workerScript) { var recursiveCall = evaluateFor(exp, workerScript); recursiveCall.then(function(foo) { resolve("endForLoop"); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); } else { console.log("Cond is false, stopping for loop"); resolve("endForLoop"); //Doesn't need to resolve to any particular value } - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }); } function evaluateWhile(exp, workerScript) { + var env = workerScript.env; + console.log("evaluateWhile() called"); return new Promise(function(resolve, reject) { + if (env.stopFlag) {reject(workerScript);} + var pCond = new Promise(function(resolve, reject) { setTimeout(function() { var evaluatePromise = evaluate(exp.cond, workerScript); evaluatePromise.then(function(resCond) { console.log("Conditional evaluated to: " + resCond); resolve(resCond); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }, CONSTANTS.CodeInstructionRunTime); }); @@ -394,8 +402,8 @@ function evaluateWhile(exp, workerScript) { evaluatePromise.then(function(resCode) { console.log("Evaluated an iteration of while loop code"); resolve(resCode); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }, CONSTANTS.CodeInstructionRunTime); }); @@ -405,25 +413,29 @@ function evaluateWhile(exp, workerScript) { var recursiveCall = evaluateWhile(exp, workerScript); recursiveCall.then(function(foo) { resolve("endWhileLoop"); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); } else { console.log("Cond is false, stopping while loop"); resolve("endWhileLoop"); //Doesn't need to resolve to any particular value } - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }); } function evaluateProg(exp, workerScript, index) { + var env = workerScript.env; + console.log("evaluateProg() called"); return new Promise(function(resolve, reject) { + if (env.stopFlag) {reject(workerScript);} + if (index >= exp.prog.length) { console.log("Prog done. Resolving recursively"); resolve("progFinished"); @@ -434,8 +446,8 @@ function evaluateProg(exp, workerScript, index) { var evaluatePromise = evaluate(exp.prog[index], workerScript); evaluatePromise.then(function(evalRes) { resolve(evalRes); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); }, CONSTANTS.CodeInstructionRunTime); }); @@ -445,11 +457,11 @@ function evaluateProg(exp, workerScript, index) { var nextLine = evaluateProg(exp, workerScript, index + 1); nextLine.then(function(nextLineRes) { resolve(workerScript); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); - }, function() { - reject(workerScript); + }, function(e) { + reject(e); }); } }); diff --git a/src/Netscript/NetscriptWorker.js b/src/Netscript/NetscriptWorker.js index a75eb9bf5..d81a91683 100644 --- a/src/Netscript/NetscriptWorker.js +++ b/src/Netscript/NetscriptWorker.js @@ -24,7 +24,11 @@ function runScriptsLoop() { for (var i = 0; i < workerScripts.length; i++) { //If it isn't running, start the script if (workerScripts[i].running == false && workerScripts[i].env.stopFlag == false) { - var ast = Parser(Tokenizer(InputStream(workerScripts[i].code))); + try { + var ast = Parser(Tokenizer(InputStream(workerScripts[i].code))); + } catch (e) { + post("Syntax error in " + workerScript[i].name + ": " + e); + } console.log("Starting new script: " + workerScripts[i].name); console.log("AST of new script:"); @@ -39,9 +43,15 @@ function runScriptsLoop() { w.running = false; w.env.stopFlag = true; }, function(w) { - console.log("Stopping script" + w.name + " because it was manually stopped (rejected)") - w.running = false; - w.env.stopFlag = true; + if (w instanceof Error) { + console.log("Script threw an Error during runtime."); + //TODO Get the script based on the error. Format: |serverip|scriptname|error message| + //TODO Post the script error and stop the script + } else { + console.log("Stopping script" + w.name + " because it was manually stopped (rejected)") + w.running = false; + w.env.stopFlag = true; + } }); } } diff --git a/src/Player.js b/src/Player.js index 11f501f07..5ad8fa634 100644 --- a/src/Player.js +++ b/src/Player.js @@ -94,8 +94,17 @@ PlayerObject.prototype.getHomeComputer = function() { // At the maximum possible exp (MAX_INT = 9007199254740991), the hacking skill will be 1796 // Gets to level 1000 hacking skill at ~1,100,000,000 exp PlayerObject.prototype.calculateSkill = function(exp) { - return Math.max(Math.floor(50 * log(9007199254740991+ 2.270) - 40), 1); -}, + return Math.max(Math.floor(50 * Math.log(9007199254740991+ 2.270) - 40), 1); +} + +PlayerObject.prototype.updateSkillLevels = function() { + this.hacking_skill = this.calculateSkill(this.hacking_exp); + this.strength = this.calculateSkill(this.strength_exp); + this.defense = this.calculateSkill(this.defense_exp); + this.dexterity = this.calculateSkill(this.dexterity_exp); + this.agility = this.calculateSkill(this.agility_exp); + this.charisma = this.calculateSkill(this.charisma_exp); +} //Calculates the chance of hacking a server //The formula is: @@ -107,7 +116,7 @@ PlayerObject.prototype.calculateHackingChance = function() { var skillMult = (this.hacking_chance_multiplier * this.hacking_skill); var skillChance = (skillMult - this.getCurrentServer().requiredHackingSkill) / skillMult; return (skillChance * difficultyMult); -}, +} //Calculate the time it takes to hack a server in seconds. Returns the time //The formula is: @@ -151,6 +160,7 @@ PlayerObject.prototype.hack = function() { //Set the startAction flag so the engine starts the hacking process this.startAction = true; } + PlayerObject.prototype.analyze = function() { //TODO Analyze only takes 5 seconds for now..maybe change this in the future? this.actionTime = 5; diff --git a/src/Script.js b/src/Script.js index c2c318c9f..36c3cc012 100644 --- a/src/Script.js +++ b/src/Script.js @@ -124,6 +124,8 @@ Script.prototype.updateRamUsage = function() { //Every instruction takes a flat time of X seconds (defined in Constants.js) //Every hack instructions takes an ADDITIONAl time of however long it takes to hack that server Script.prototype.updateExecutionTime = function() { + //TODO Maybe do this based on the average production/s of the script( which I'm adding in + //as a property) /* var executionTime = 0; diff --git a/src/engine.js b/src/engine.js index 1ae63dd06..314e77f1f 100644 --- a/src/engine.js +++ b/src/engine.js @@ -161,10 +161,29 @@ var Engine = { window.requestAnimationFrame(Engine.idleTimer); }, + //TODO Account for numCycles in Code, hasn't been done yet + updateGame: function(numCycles = 1) { + //Manual hack + if (Player.startAction == true) { + Engine._totalActionTime = Player.actionTime; + Engine._actionTimeLeft = Player.actionTime; + Engine._actionInProgress = true; + Engine._actionProgressBarCount = 1; + Engine._actionProgressStr = "[ ]"; + Engine._actionTimeStr = "Time left: "; + Player.startAction = false; + } + Engine.decrementAllCounters(numCycles); + Engine.checkCounters(); + + Engine.updateHackProgress(numCycles); + }, + //Counters for the main event loop. Represent the number of game cycles are required //for something to happen. Counters: { - autoSaveCounter: 300, + autoSaveCounter: 300, //Autosave every minute + updateSkillLevelsCounter: 10, //Only update skill levels every 2 seconds. Might improve performance }, decrementAllCounters: function(numCycles = 1) { @@ -182,26 +201,13 @@ var Engine = { Engine.saveGame(); Engine.Counters.autoSaveCounter = 300; } + + if (Engine.Counters.updateSkillLevelsCounter <= 0) { + Player.updateSkillLevels(); + Engine.Counters.updateSkillLevelsCounter = 10; + } }, - //TODO Account for numCycles in Code, hasn't been done yet - updateGame: function(numCycles = 1) { - //Manual hack - if (Player.startAction == true) { - Engine._totalActionTime = Player.actionTime; - Engine._actionTimeLeft = Player.actionTime; - Engine._actionInProgress = true; - Engine._actionProgressBarCount = 1; - Engine._actionProgressStr = "[ ]"; - Engine._actionTimeStr = "Time left: "; - Player.startAction = false; - } - Engine.decrementAllCounters(numCycles); - Engine.checkCounters(); - - Engine.updateHackProgress(numCycles); - }, - /* Calculates the hack progress for a manual (non-scripted) hack and updates the progress bar/time accordingly */ _totalActionTime: 0, _actionTimeLeft: 0, diff --git a/utils/StringHelperFunctions.js b/utils/StringHelperFunctions.js new file mode 100644 index 000000000..9d6621bd2 --- /dev/null +++ b/utils/StringHelperFunctions.js @@ -0,0 +1,20 @@ +//Netscript String helper functions + +//Searches for every occurence of searchStr within str and returns an array of the indices of +//all these occurences +function getIndicesOf(searchStr, str, caseSensitive) { + var searchStrLen = searchStr.length; + if (searchStrLen == 0) { + return []; + } + var startIndex = 0, index, indices = []; + if (!caseSensitive) { + str = str.toLowerCase(); + searchStr = searchStr.toLowerCase(); + } + while ((index = str.indexOf(searchStr, startIndex)) > -1) { + indices.push(index); + startIndex = index + searchStrLen; + } + return indices; +} \ No newline at end of file