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

This commit is contained in:
Daniel Xie 2016-12-15 16:22:42 -06:00
parent 96fb37c6d1
commit 5f1b58fd86
7 changed files with 172 additions and 104 deletions

@ -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
Update CONSTANTS.HelpText
Account for Max possible int when gaining exp

@ -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);
});
}
});

@ -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;
}
});
}
}

@ -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;

@ -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;

@ -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,

@ -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;
}