Refactored the hacking progress code into an action progress code so that it can be reused for analyze and anything else that requires an animated progress bar. Implemented analyze

This commit is contained in:
Daniel Xie 2016-11-01 00:30:59 -05:00
parent cc6b178a96
commit 6cf9339919
3 changed files with 161 additions and 68 deletions

@ -55,8 +55,8 @@ var Player = {
//Flag to let the engine know the player is starting a hack //Flag to let the engine know the player is starting a hack
startHack: false, startAction: false,
hackingTime: 0, actionTime: 0,
init: function() { init: function() {
@ -126,15 +126,19 @@ var Player = {
return Math.round(Player.currentServer.hackDifficulty * Player.currentServer.requiredHackingSkill * Player.hacking_exp_mult); return Math.round(Player.currentServer.hackDifficulty * Player.currentServer.requiredHackingSkill * Player.hacking_exp_mult);
}, },
//Hack a server. Return the amount of time the hack will take. This lets the Terminal object know how long to disable itself for //Hack/Analyze a server. Return the amount of time the hack will take. This lets the Terminal object know how long to disable itself for
//This assumes that the server being hacked is not purchased by the player, that the player's hacking skill is greater than the //This assumes that the server being hacked is not purchased by the player, that the player's hacking skill is greater than the
//required hacking skill and that the player has admin rights. //required hacking skill and that the player has admin rights.
hack: function() { hack: function() {
Player.hackingTime = Player.calculateHackingTime(); Player.actionTime = Player.calculateHackingTime();
console.log("Hacking time: " + Player.hackingTime); console.log("Hacking time: " + Player.actionTime);
//Set the startHack flag so the engine starts the hacking process //Set the startHack flag so the engine starts the hacking process
Player.startHack = true; Player.startAction = true;
},
return Player.hackingTime;
} analyze: function() {
//TODO Analyze only takes 5 seconds for now..maybe change this in the future?
Player.actionTime = 5;
Player.startAction = true;
}
}; };

@ -1,6 +1,6 @@
//Terminal //Terminal
var post = function(input) { var post = function(input) {
$("#terminal-input").before('<tr class="posted"><td style="color: #66ff33;">' + input + '</td></tr>'); $("#terminal-input").before('<tr class="posted"><td style="color: #66ff33;">' + input.replace( / /g, "&nbsp;" ) + '</td></tr>');
window.scrollTo(0, document.body.scrollHeight); window.scrollTo(0, document.body.scrollHeight);
} }
@ -34,36 +34,92 @@ $(document).keyup(function(event) {
}); });
var Terminal = { var Terminal = {
//Flags to determine whether the player is currently running a hack or an analyze
hackFlag: false,
analyzeFlag: false,
finishAction: function() {
if (Terminal.hackFlag) {
Terminal.finishHack();
} else if (Terminal.analyzeFlag) {
Terminal.finishAnalyze();
}
},
//Complete the hack/analyze command
finishHack: function() { finishHack: function() {
console.log("Hack done. Determining success/failure of hack. Re-enabling terminal and changing the id of the hack progress bar"); console.log("Hack done. Determining success/failure of hack. Re-enabling terminal and changing the id of the hack progress bar");
//Calculate whether hack was successful //Calculate whether hack was successful
var hackChance = Player.calculateHackingChance(); var hackChance = Player.calculateHackingChance();
var rand = Math.random(); var rand = Math.random();
console.log("Hack success chance: " + hackChance + ", rand: " + rand); console.log("Hack success chance: " + hackChance + ", rand: " + rand);
var expGainedOnSuccess = Player.calculateExpGain(); var expGainedOnSuccess = Player.calculateExpGain();
var expGainedOnFailure = Math.round(expGainedOnSuccess / 4); var expGainedOnFailure = Math.round(expGainedOnSuccess / 4);
if (rand < hackChance) { //Success! if (rand < hackChance) { //Success!
var moneyGained = Player.calculatePercentMoneyHacked(); var moneyGained = Player.calculatePercentMoneyHacked();
moneyGained = Math.floor(Player.currentServer.moneyAvailable * moneyGained); moneyGained = Math.floor(Player.currentServer.moneyAvailable * moneyGained);
Player.currentServer.moneyAvailable -= moneyGained; Player.currentServer.moneyAvailable -= moneyGained;
Player.money += moneyGained; Player.money += moneyGained;
Player.hacking_exp += expGainedOnSuccess; Player.hacking_exp += expGainedOnSuccess;
post("Hack successful! Gained $" + moneyGained + "and " + expGainedOnSuccess + " hacking EXP"); post("Hack successful! Gained $" + moneyGained + " and " + expGainedOnSuccess + " hacking EXP");
} else { //Failure } else { //Failure
//Player only gains 25% exp for failure? TODO Can change this later to balance //Player only gains 25% exp for failure? TODO Can change this later to balance
Player.hacking_exp += expGainedOnFailure; Player.hacking_exp += expGainedOnFailure;
post("Failed to hack " + Player.currentServer.hostname + ". Gained " + expGainedOnFailure + " hacking EXP"); post("Failed to hack " + Player.currentServer.hostname + ". Gained " + expGainedOnFailure + " hacking EXP");
} }
$("#hack-progress-bar").attr('id', "old-hack-progress-bar"); //Rename the progress bar so that the next hacks dont trigger it. Re-enable terminal
$("#hack-progress").attr('id', "old-hack-progress"); $("#hack-progress-bar").attr('id', "old-hack-progress-bar");
document.getElementById("terminal-input-td").innerHTML = '$ <input type="text" class="terminal-input"/>'; $("#hack-progress").attr('id', "old-hack-progress");
$('input[class=terminal-input]').prop('disabled', false); document.getElementById("terminal-input-td").innerHTML = '$ <input type="text" class="terminal-input"/>';
$('input[class=terminal-input]').prop('disabled', false);
Terminal.hackFlag = false;
}, },
finishAnalyze: function() {
post(Player.currentServer.hostname + ": ");
post("Required hacking skill: " + Player.currentServer.requiredHackingSkill);
//TODO Make these actual estimates by adding a random offset to result?
//TODO Change the text to sound better
post("Estimated chance to hack: " + Math.round(Player.calculateHackingChance() * 100) + "%");
post("Estimated time to hack: " + Math.round(Player.calculateHackingTime()) + " seconds");
post("Required number of open ports for PortHack: " +Player.currentServer.numOpenPortsRequired);
if (Player.currentServer.sshPortOpen) {
post("SSH port: Open")
} else {
post("SSH port: Closed")
}
if (Player.currentServer.ftpPortOpen) {
post("FTP port: Open")
} else {
post("FTP port: Closed")
}
if (Player.currentServer.smtpPortOpen) {
post("SMTP port: Open")
} else {
post("SMTP port: Closed")
}
if (Player.currentServer.httpPortOpen) {
post("HTTP port: Open")
} else {
post("HTTP port: Closed")
}
if (Player.currentServer.sqlPortOpen) {
post("SQL port: Open")
} else {
post("SQL port: Closed")
}
Terminal.analyzeFlag = false;
},
executeCommand: function(command) { executeCommand: function(command) {
var commandArray = command.split(" "); var commandArray = command.split(" ");
@ -74,7 +130,18 @@ var Terminal = {
switch (commandArray[0]) { switch (commandArray[0]) {
case "analyze": case "analyze":
//TODO Analyze the system for ports //Analyze the current server for information
console.log("analyze terminal command called");
Terminal.analyzeFlag = true;
post("Analyzing system...");
hackProgressPost("Time left:");
hackProgressBarPost("[");
Player.analyze();
//Disable terminal
console.log("Disabling terminal");
document.getElementById("terminal-input-td").innerHTML = '<input type="text" class="terminal-input"/>';
$('input[class=terminal-input]').prop('disabled', true);
break; break;
case "clear": case "clear":
case "cls": case "cls":
@ -119,9 +186,10 @@ var Terminal = {
} else if (Player.currentServer.requiredHackingSkill > Player.hacking_skill) { } else if (Player.currentServer.requiredHackingSkill > Player.hacking_skill) {
post("Your hacking skill is not high enough to attempt hacking this machine. Try analyzing the machine to determine the required hacking skill"); post("Your hacking skill is not high enough to attempt hacking this machine. Try analyzing the machine to determine the required hacking skill");
} else { } else {
Terminal.hackFlag = true;
hackProgressPost("Time left:"); hackProgressPost("Time left:");
hackProgressBarPost("["); hackProgressBarPost("[");
var timeToHack = Player.hack(); Player.hack();
//Disable terminal //Disable terminal
console.log("Disabling terminal"); console.log("Disabling terminal");
@ -170,9 +238,29 @@ var Terminal = {
} }
//Displays available network connections using TCP //Displays available network connections using TCP
console.log("netstat/scan terminal command called"); console.log("netstat/scan terminal command called");
post("Hostname IP"); post("Hostname IP Root Access");
for (var i = 0; i < Player.currentServer.serversOnNetwork.length; i++) { for (var i = 0; i < Player.currentServer.serversOnNetwork.length; i++) {
post(Player.currentServer.serversOnNetwork[i].hostname + " " + Player.currentServer.serversOnNetwork[i].ip); //Add hostname
var entry = Player.currentServer.serversOnNetwork[i].hostname;
//Calculate padding and add IP
var numSpaces = 21 - entry.length;
var spaces = Array(numSpaces+1).join(" ");
entry += spaces;
entry += Player.currentServer.serversOnNetwork[i].ip;
//Calculate padding and add root access info
var hasRoot;
if (Player.currentServer.serversOnNetwork[i].hasAdminRights) {
hasRoot = 'Y';
} else {
hasRoot = 'N';
}
numSpaces = 21 - Player.currentServer.serversOnNetwork[i].ip.length;
spaces = Array(numSpaces+1).join(" ");
entry += spaces;
entry += hasRoot;
post(entry);
} }
case "ps": case "ps":
//TODO //TODO

@ -113,7 +113,8 @@ var Engine = {
'Defense: ' + Player.defense + '<br><br>' + 'Defense: ' + Player.defense + '<br><br>' +
'Dexterity: ' + Player.dexterity + '<br><br>' + 'Dexterity: ' + Player.dexterity + '<br><br>' +
'Agility: ' + Player.agility + '<br><br>' + 'Agility: ' + Player.agility + '<br><br>' +
'Servers owned: ' + Player.purchasedServers.length + '<br><br>'; 'Servers owned: ' + Player.purchasedServers.length + '<br><br>' +
'Hacking Experience: ' + Player.hacking_exp + '<br><br>';
}, },
/* Main Event Loop */ /* Main Event Loop */
@ -135,14 +136,14 @@ var Engine = {
var idleTime = Engine._idleSpeed - timeDifference; var idleTime = Engine._idleSpeed - timeDifference;
//Manual hack //Manual hack
if (Player.startHack == true) { if (Player.startAction == true) {
Engine._totalHackTime = Player.hackingTime; Engine._totalActionTime = Player.actionTime;
Engine._hackTimeLeft = Player.hackingTime; Engine._actionTimeLeft = Player.actionTime;
Engine._manualHackInProgress = true; Engine._actionInProgress = true;
Engine._hackProgressBarCount = 1; Engine._actionProgressBarCount = 1;
Engine._hackProgressStr = "[ ]"; Engine._actionProgressStr = "[ ]";
Engine._hackTimeStr = "Time left: "; Engine._actionTimeStr = "Time left: ";
Player.startHack = false; Player.startAction = false;
//document.getElementById("hack-progress-bar").style.whiteSpace = "pre"; //document.getElementById("hack-progress-bar").style.whiteSpace = "pre";
} }
@ -157,36 +158,36 @@ var Engine = {
}, },
/* Calculates the hack progress for a manual (non-scripted) hack and updates the progress bar/time accordingly */ /* Calculates the hack progress for a manual (non-scripted) hack and updates the progress bar/time accordingly */
_totalHackTime: 0, _totalActionTime: 0,
_hackTimeLeft: 0, _actionTimeLeft: 0,
_hackTimeStr: "Time left: ", _actionTimeStr: "Time left: ",
_hackProgressStr: "[ ]", _actionProgressStr: "[ ]",
_hackProgressBarCount: 1, _actionProgressBarCount: 1,
_manualHackInProgress: false, _actionInProgress: false,
updateHackProgress: function() { updateHackProgress: function() {
if (Engine._manualHackInProgress == true) { if (Engine._actionInProgress == true) {
Engine._hackTimeLeft -= (Engine._idleSpeed/ 1000); //Substract idle speed (ms) Engine._actionTimeLeft -= (Engine._idleSpeed/ 1000); //Substract idle speed (ms)
//Calculate percent filled //Calculate percent filled
var percent = Math.round((1 - Engine._hackTimeLeft / Engine._totalHackTime) * 100); var percent = Math.round((1 - Engine._actionTimeLeft / Engine._totalActionTime) * 100);
//Update progress bar //Update progress bar
while (Engine._hackProgressBarCount * 2 <= percent) { while (Engine._actionProgressBarCount * 2 <= percent) {
Engine._hackProgressStr = Engine._hackProgressStr.replaceAt(Engine._hackProgressBarCount, "|"); Engine._actionProgressStr = Engine._actionProgressStr.replaceAt(Engine._actionProgressBarCount, "|");
Engine._hackProgressBarCount += 1; Engine._actionProgressBarCount += 1;
} }
//Update hack time remaining //Update hack time remaining
Engine._hackTimeStr = "Time left: " + Math.max(0, Math.round(Engine._hackTimeLeft)).toString() + "s"; Engine._actionTimeStr = "Time left: " + Math.max(0, Math.round(Engine._actionTimeLeft)).toString() + "s";
document.getElementById("hack-progress").innerHTML = Engine._hackTimeStr; document.getElementById("hack-progress").innerHTML = Engine._actionTimeStr;
//Dynamically update progress bar //Dynamically update progress bar
document.getElementById("hack-progress-bar").innerHTML = Engine._hackProgressStr.replace( / /g, "&nbsp;" ); document.getElementById("hack-progress-bar").innerHTML = Engine._actionProgressStr.replace( / /g, "&nbsp;" );
//Once percent is 100, the hack is completed //Once percent is 100, the hack is completed
if (percent >= 100) { if (percent >= 100) {
Engine._manualHackInProgress = false; Engine._actionInProgress = false;
Terminal.finishHack(); Terminal.finishAction();
} }
} }