Compare commits

...

2 Commits

Author SHA1 Message Date
22ddbbde5d Reformat files 2023-11-03 18:42:37 -03:00
683daff911 Add project coding guidelines 2023-11-03 18:41:51 -03:00
10 changed files with 519 additions and 308 deletions

10
.editorconfig Normal file
View File

@ -0,0 +1,10 @@
# All files
[*]
end_of_line = lf
insert_final_newline = true
indent_style = tab
indent_size = 2
# Markup files
[*.{json,yml}]
indent_style = space

215
.gitattributes vendored Normal file
View File

@ -0,0 +1,215 @@
## GITATTRIBUTES FOR WEB PROJECTS
#
# These settings are for any web project.
#
# Details per file setting:
# text These files should be normalized (i.e. convert CRLF to LF).
# binary These files are binary and should be left untouched.
#
# Note that binary is a macro for -text -diff.
######################################################################
# Auto detect
## Handle line endings automatically for files detected as
## text and leave all files detected as binary untouched.
## This will handle all files NOT defined below.
* text=auto
# Source code
*.bash text eol=lf
*.bat text eol=crlf
*.cmd text eol=crlf
*.coffee text
*.css text diff=css
*.htm text diff=html
*.html text diff=html
*.inc text
*.ini text
*.js text
*.json text
*.jsx text
*.less text
*.ls text
*.map text -diff
*.od text
*.onlydata text
*.php text diff=php
*.pl text
*.ps1 text eol=crlf
*.py text diff=python
*.rb text diff=ruby
*.sass text
*.scm text
*.scss text diff=css
*.sh text eol=lf
.husky/* text eol=lf
*.sql text
*.styl text
*.tag text
*.ts text
*.tsx text
*.xml text
*.xhtml text diff=html
# Docker
Dockerfile text
# Documentation
*.ipynb text eol=lf
*.markdown text diff=markdown
*.md text diff=markdown
*.mdwn text diff=markdown
*.mdown text diff=markdown
*.mkd text diff=markdown
*.mkdn text diff=markdown
*.mdtxt text
*.mdtext text
*.txt text
AUTHORS text
CHANGELOG text
CHANGES text
CONTRIBUTING text
COPYING text
copyright text
*COPYRIGHT* text
INSTALL text
license text
LICENSE text
NEWS text
readme text
*README* text
TODO text
# Templates
*.dot text
*.ejs text
*.erb text
*.haml text
*.handlebars text
*.hbs text
*.hbt text
*.jade text
*.latte text
*.mustache text
*.njk text
*.phtml text
*.svelte text
*.tmpl text
*.tpl text
*.twig text
*.vue text
# Configs
*.cnf text
*.conf text
*.config text
.editorconfig text
.env text
.gitattributes text
.gitconfig text
.htaccess text
*.lock text -diff
package.json text eol=lf
package-lock.json text eol=lf -diff
pnpm-lock.yaml text eol=lf -diff
.prettierrc text
yarn.lock text -diff
*.toml text
*.yaml text
*.yml text
browserslist text
Makefile text
makefile text
# Fixes syntax highlighting on GitHub to allow comments
tsconfig.json linguist-language=JSON-with-Comments
# Heroku
Procfile text
# Graphics
*.ai binary
*.bmp binary
*.eps binary
*.gif binary
*.gifv binary
*.ico binary
*.jng binary
*.jp2 binary
*.jpg binary
*.jpeg binary
*.jpx binary
*.jxr binary
*.pdf binary
*.png binary
*.psb binary
*.psd binary
# SVG treated as an asset (binary) by default.
*.svg text
# If you want to treat it as binary,
# use the following line instead.
# *.svg binary
*.svgz binary
*.tif binary
*.tiff binary
*.wbmp binary
*.webp binary
# Audio
*.kar binary
*.m4a binary
*.mid binary
*.midi binary
*.mp3 binary
*.ogg binary
*.ra binary
# Video
*.3gpp binary
*.3gp binary
*.as binary
*.asf binary
*.asx binary
*.avi binary
*.fla binary
*.flv binary
*.m4v binary
*.mng binary
*.mov binary
*.mp4 binary
*.mpeg binary
*.mpg binary
*.ogv binary
*.swc binary
*.swf binary
*.webm binary
# Archives
*.7z binary
*.gz binary
*.jar binary
*.rar binary
*.tar binary
*.zip binary
# Fonts
*.ttf binary
*.eot binary
*.otf binary
*.woff binary
*.woff2 binary
# Executables
*.exe binary
*.pyc binary
# Prevents massive diffs caused by vendored, minified files
**/.yarn/releases/** binary
**/.yarn/plugins/** binary
# RC files (like .babelrc or .eslintrc)
*.*rc text
# Ignore files (like .npmignore or .gitignore)
*.*ignore text
# Prevents massive diffs from built files
dist/* binary

5
.idea/codeStyles/codeStyleConfig.xml generated Normal file
View File

@ -0,0 +1,5 @@
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>

View File

@ -1,4 +1,4 @@
export async function main(ns: NS) { export async function main(ns: NS) {
ns.run("watcher.js") ns.run('watcher.js')
ns.run("hacknet.js") ns.run('hacknet.js')
} }

View File

@ -1,23 +1,10 @@
export async function main(ns: NS) { export async function main(ns: NS) {
const server: string = <string>ns.args[0]; const server: string = <string> ns.args[0]
while (true) { while (true) {
/* This code checks conditions that are not needed with smart scheduling // Guide https://darktechnomancer.github.io/#glossary-of-terms
const moneyThresh: number = <number>ns.args[1]; await ns.weaken(server)
const securityThresh: number = <number>ns.args[2]; await ns.grow(server)
if (ns.getServerSecurityLevel(server) > securityThresh) { await ns.weaken(server)
await ns.weaken(server); await ns.hack(server)
} else if (ns.getServerMoneyAvailable(server) < moneyThresh) { }
await ns.grow(server); }
} else {
await ns.hack(server);
}
*/
// Guide
// https://darktechnomancer.github.io/#glossary-of-terms
await ns.weaken(server);
await ns.grow(server);
await ns.weaken(server);
await ns.hack(server);
}
}

View File

@ -1,15 +1,11 @@
import {recursiveScan} from "./utils"; import { executeScriptOnServerFromAnother, recursiveScan } from './utils'
import {executeScriptOnServerFromAnother} from "./utils";
export async function main(ns: NS) { export async function main(ns: NS) {
let servers: string[] = recursiveScan(ns); let servers: string[] = recursiveScan(ns)
for (const server of servers) { for (const server of servers) {
// Commented out code is not needed with smart scheduling let numThreads = ns.getServerMaxRam(server) / ns.getScriptRam('hack.js')
//let moneyThresh = ns.getServerMaxMoney(server) * 0.75; numThreads = Math.floor(numThreads)
//let securityThresh = ns.getServerMinSecurityLevel(server) + 5; executeScriptOnServerFromAnother(ns, server, 'hack.js', numThreads, [server])
let numThreads = ns.getServerMaxRam(server) / ns.getScriptRam("hack.js") }
numThreads = Math.floor(numThreads); }
//executeScriptOnServerFromAnother(ns, server, "hack.js", numThreads, [server, moneyThresh, securityThresh])
executeScriptOnServerFromAnother(ns, server, "hack.js", numThreads, [server])
}
}

View File

@ -1,103 +1,100 @@
/* /*
* TODO: * TODO:
* The current solution is not optimal, as it's preferable to buy new nodes, even if upgrading is cheaper. * The current solution is not optimal, as it's preferable to buy new nodes, even if upgrading is cheaper.
* TODO: * TODO:
* It may be helpful to calculate the money per second of each node on average, (total mps / total nodes) and compare * It may be helpful to calculate the money per second of each node on average, (total mps / total nodes) and compare
* it to the time it would take to purchase the next cheapest upgrade, and if the average mps is greater than the * it to the time it would take to purchase the next cheapest upgrade, and if the average mps is greater than the
* negative mps of the upgrade cost, then buy a new node. * negative mps of the upgrade cost, then buy a new node.
* TODO: * TODO:
* Potential Ideas: * Potential Ideas:
* Find a way to calculate how much mps an individual upgrade would give, and compare it to the average mps of the node. * Find a way to calculate how much mps an individual upgrade would give, and compare it to the average mps of the node.
* ns.hacknet.getNodeStats(0).production * ns.hacknet.getNodeStats(0).production
* If the upgrade mps is greater than the average mps, then buy the upgrade. * If the upgrade mps is greater than the average mps, then buy the upgrade.
* If the upgrade mps is less than the average mps, then buy a new node. * If the upgrade mps is less than the average mps, then buy a new node.
*/ */
enum Type { enum Type {
newNode = "node", newNode = 'node', level = 'level', ram = 'ram', core = 'code',
level = "level", }
ram = "ram",
core = "code" export async function main(ns: NS) {
} let timeout: number = <number> ns.args[0]
export async function main(ns: NS) { let nodes = ns.hacknet.numNodes()
let timeout: number = <number>ns.args[0] let costs: { type: Type, cost: number }[] = []
while (true) {
let nodes = ns.hacknet.numNodes() costs = []
let costs: {type: Type, cost: number}[] = [] // Go through each node and get the cheapest upgrade
while (true) { for (let i = 0; i < nodes; i++) {
costs = [] costs.push(getCheapestCost(ns, i))
// Go through each node and get the cheapest upgrade }
for (let i = 0; i < nodes; i++) { // Buy the cheapest upgrade from all nodes
costs.push(getCheapestCost(ns, i)) let cheapest = Math.min(...costs.map(c => c.cost))
} // Find the index of the cheapest cost in the list
// Buy the cheapest upgrade from all nodes let index = costs.findIndex(c => c.cost === cheapest)
let cheapest = Math.min(...costs.map(c => c.cost)) // Wait to buy the cheapest upgrade
// Find the index of the cheapest cost in the list try {
let index = costs.findIndex(c => c.cost === cheapest) await buy(ns, costs[index].type, costs[index].cost, index, timeout)
// Wait to buy the cheapest upgrade } catch (e) {
try { ns.tprint(e)
await buy(ns, costs[index].type, costs[index].cost, index, timeout) ns.exit()
} catch (e) { }
ns.tprint(e) // Make sure that the number of nodes is up-to-date
ns.exit() nodes = ns.hacknet.numNodes()
} }
// Make sure that the number of nodes is up-to-date }
nodes = ns.hacknet.numNodes()
} /**
} * Wait until the player has enough money to buy something
* @param ns Global NS object
/** * @param money Amount of money to wait for
* Wait until the player has enough money to buy something * @param timeout=-1 Number of seconds to wait before timing out.
* @param ns Global NS object * @throws Error if the timeout is reached
* @param money Amount of money to wait for * @note This function will wait forever by default
* @param timeout=-1 Number of seconds to wait before timing out. */
* @throws Error if the timeout is reached async function waitUntilMoney(ns: NS, money: number, timeout: number = -1) {
* @note This function will wait forever by default while (ns.getServerMoneyAvailable('home') < money) {
*/ await ns.sleep(1000)
async function waitUntilMoney(ns: NS, money: number, timeout: number = -1) { if (timeout == 0) {
while (ns.getServerMoneyAvailable("home") < money) { throw new Error('Timed out waiting for money')
await ns.sleep(1000) } else if (timeout > -1) {
if (timeout == 0) { timeout--
throw new Error("Timed out waiting for money") }
} else if (timeout > -1) { }
timeout--; }
}
} async function buy(ns: NS, type: Type, cost: number, node: number, timeout: number) {
} await waitUntilMoney(ns, cost, timeout)
switch (type) {
async function buy(ns: NS, type: Type, cost: number, node: number, timeout: number) { case Type.newNode:
await waitUntilMoney(ns, cost, timeout) ns.hacknet.purchaseNode()
switch (type) { break
case Type.newNode: case Type.level:
ns.hacknet.purchaseNode() ns.hacknet.upgradeLevel(node)
break break
case Type.level: case Type.ram:
ns.hacknet.upgradeLevel(node) ns.hacknet.upgradeRam(node)
break break
case Type.ram: case Type.core:
ns.hacknet.upgradeRam(node) ns.hacknet.upgradeCore(node)
break break
case Type.core: }
ns.hacknet.upgradeCore(node) }
break
} function getCheapestCost(ns: NS, node: number) {
} let nodeCost = ns.hacknet.getPurchaseNodeCost()
let levelCost = ns.hacknet.getLevelUpgradeCost(node)
function getCheapestCost(ns: NS, node: number) { let ramCost = ns.hacknet.getRamUpgradeCost(node)
let nodeCost = ns.hacknet.getPurchaseNodeCost() let coreCost = ns.hacknet.getCoreUpgradeCost(node)
let levelCost = ns.hacknet.getLevelUpgradeCost(node) let cheapest = Math.min(nodeCost, levelCost, ramCost, coreCost)
let ramCost = ns.hacknet.getRamUpgradeCost(node) switch (cheapest) {
let coreCost = ns.hacknet.getCoreUpgradeCost(node) case nodeCost:
let cheapest = Math.min(nodeCost, levelCost, ramCost, coreCost) return { type: Type.newNode, cost: nodeCost }
switch (cheapest) { case levelCost:
case nodeCost: return { type: Type.level, cost: levelCost }
return {type: Type.newNode, cost: nodeCost} case ramCost:
case levelCost: return { type: Type.ram, cost: ramCost }
return {type: Type.level, cost: levelCost} case coreCost:
case ramCost: return { type: Type.core, cost: coreCost }
return {type: Type.ram, cost: ramCost} }
case coreCost: }
return {type: Type.core, cost: coreCost}
}
}

View File

@ -1,7 +1,8 @@
import {recursiveScan} from "./utils"; import { recursiveScan } from './utils'
export async function main(ns: NS) {
let servers: string[] = recursiveScan(ns) export async function main(ns: NS) {
for (const server of servers) { let servers: string[] = recursiveScan(ns)
ns.killall(server) for (const server of servers) {
} ns.killall(server)
} }
}

View File

@ -1,141 +1,140 @@
// noinspection JSUnusedGlobalSymbols // noinspection JSUnusedGlobalSymbols
/**
* Recursively scans all servers connected to the current server, excluding home /**
* @param ns global NS object * Recursively scans all servers connected to the current server, excluding home
* @returns A list of all servers connected to the current server * @param ns global NS object
*/ * @returns A list of all servers connected to the current server
export function recursiveScan(ns: NS) { */
// Starting case export function recursiveScan(ns: NS) {
let servers = ns.scan("home"); // Starting case
// Add all servers to the list let servers = ns.scan('home')
let allServers: string[] = []; // Add all servers to the list
while (servers.length > 0) { let allServers: string[] = []
let server = servers.shift(); while (servers.length > 0) {
if(server) { let server = servers.shift()
let newServers = ns.scan(server); if (server) {
for (let newServer of newServers) { let newServers = ns.scan(server)
if (!allServers.includes(newServer)) { for (let newServer of newServers) {
allServers.push(newServer); if (!allServers.includes(newServer)) {
servers.push(newServer); allServers.push(newServer)
} servers.push(newServer)
} }
} }
} }
// Remove the current server }
allServers.splice(allServers.indexOf("home"), 1); // Remove the current server
// Print all servers allServers.splice(allServers.indexOf('home'), 1)
return allServers; // Print all servers
} return allServers
}
/**
* Removes files passed in from all servers /**
* @param ns Global NS object * Removes files passed in from all servers
* @param files The files to remove * @param ns Global NS object
* @returns void * @param files The files to remove
* @example Removes all files from the folder "no-ports" from all servers. * @returns void
* removeFilesOnAllServers(ns, ns.ls("home", "no-ports")); * @example Removes all files from the folder "no-ports" from all servers.
* @note ns.ls() returns the full path of every file, so if the file is not in the same place in every server, * removeFilesOnAllServers(ns, ns.ls("home", "no-ports"));
* you will need to modify each file path to match the server you are removing it from. * @note ns.ls() returns the full path of every file, so if the file is not in the same place in every server,
*/ * you will need to modify each file path to match the server you are removing it from.
export function removeFilesOnAllServers(ns: NS, files: string[]) { */
let hosts = recursiveScan(ns); export function removeFilesOnAllServers(ns: NS, files: string[]) {
for(const host of hosts) { let hosts = recursiveScan(ns)
for (const file of files) { for (const host of hosts) {
ns.rm(file, host) for (const file of files) {
} ns.rm(file, host)
} }
} }
}
/**
* Tries to gain root access to a server /**
* @param ns Global NS object * Tries to gain root access to a server
* @param server The server to gain root access to * @param ns Global NS object
* @returns The number of programs used to gain root access * @param server The server to gain root access to
*/ * @returns The number of programs used to gain root access
export function rootServer(ns: NS, server: string) { */
let counter = 0; export function rootServer(ns: NS, server: string) {
if (ns.fileExists("BruteSSH.exe", "home")) { let counter = 0
ns.brutessh(server); if (ns.fileExists('BruteSSH.exe', 'home')) {
counter++; ns.brutessh(server)
} counter++
if (ns.fileExists("FTPCrack.exe", "home")) { }
ns.ftpcrack(server); if (ns.fileExists('FTPCrack.exe', 'home')) {
counter++; ns.ftpcrack(server)
} counter++
if (ns.fileExists("SMTPCrack.exe", "home")) { }
ns.relaysmtp(server); if (ns.fileExists('SMTPCrack.exe', 'home')) {
counter++; ns.relaysmtp(server)
} counter++
if (ns.fileExists("HTTPWorm.exe", "home")) { }
ns.httpworm(server); if (ns.fileExists('HTTPWorm.exe', 'home')) {
counter++; ns.httpworm(server)
} counter++
if (ns.fileExists("SQLInject.exe", "home")) { }
ns.sqlinject(server); if (ns.fileExists('SQLInject.exe', 'home')) {
counter++; ns.sqlinject(server)
} counter++
ns.nuke(server) }
return counter; ns.nuke(server)
} return counter
}
/**
* Performs a function on a server if the player is capable of doing so, otherwise returns false /**
* @param ns Global NS object * Performs a function on a server if the player is capable of doing so, otherwise returns false
* @param server The server to perform the function on * @param ns Global NS object
* @param func The function to perform * @param server The server to perform the function on
* @param args The arguments to pass to the function * @param func The function to perform
* @returns The result of the function if it is performed or true if the function does not return anything, otherwise false * @param args The arguments to pass to the function
*/ * @returns The result of the function if it is performed or true if the function does not return anything, otherwise false
export function performFunctionIfCapable(ns: NS, server: string, func: CallableFunction, args: any[]) { */
if (ns.getHackingLevel() < ns.getServerRequiredHackingLevel(server)) { export function performFunctionIfCapable(ns: NS, server: string, func: CallableFunction, args: any[]) {
return false; if (ns.getHackingLevel() < ns.getServerRequiredHackingLevel(server)) {
} return false
if (ns.getServerNumPortsRequired(server) < ns.getServer(server).openPortCount) { }
if (rootServer(ns, server) < ns.getServerNumPortsRequired(server)) { if (ns.getServerNumPortsRequired(server) < ns.getServer(server).openPortCount) {
return false; if (rootServer(ns, server) < ns.getServerNumPortsRequired(server)) {
} return false
} }
if (!ns.hasRootAccess(server)) { }
return false; if (!ns.hasRootAccess(server)) {
return false
}
let result = func(...args); }
if (result === undefined) { let result = func(...args)
return true; if (result === undefined) {
} else { return true
return result; } else {
} return result
} }
}
/**
* Executes a script on a server from another server /**
* @param ns Global NS object * Executes a script on a server from another server
* @param server The server to execute the script on * @param ns Global NS object
* @param script The file path of the script to execute * @param server The server to execute the script on
* @param threads The number of threads to use * @param script The file path of the script to execute
* @param args The arguments to pass to the script * @param threads The number of threads to use
*/ * @param args The arguments to pass to the script
export function executeScriptOnServerFromAnother(ns: NS, server: string, script: string, threads: number = 1, args: any[]) { */
ns.scp(script, server); export function executeScriptOnServerFromAnother(ns: NS, server: string, script: string, threads: number = 1, args: any[]) {
performFunctionIfCapable(ns, server, ns.exec, [script, server, threads, ...args]) ns.scp(script, server)
ns.atExit( performFunctionIfCapable(ns, server, ns.exec, [script, server, threads, ...args])
() => { ns.atExit(() => {
ns.rm(script, server); ns.rm(script, server)
} })
) }
}
/**
/** * Calculates the money per second the player is making
* Calculates the money per second the player is making * @param ns Global NS object
* @param ns Global NS object * @param time=5 The number of seconds to calculate the MPS over
* @param time=5 The number of seconds to calculate the MPS over */
*/ export async function calculateMPS(ns: NS, time: number = 5) {
export async function calculateMPS(ns: NS, time: number = 5) { let start = ns.getServerMoneyAvailable('home')
let start = ns.getServerMoneyAvailable("home"); let data: number[] = []
let data: number[] = []; for (let i = 0; i < time; i++) {
for (let i = 0; i < time; i++) { await ns.sleep(1000)
await ns.sleep(1000); data.push(ns.getServerMoneyAvailable('home') - start)
data.push(ns.getServerMoneyAvailable("home") - start); }
} return data.reduce((a, b) => a + b, 0) / time
return data.reduce((a, b) => a + b, 0) / time; }
}

View File

@ -1,15 +1,16 @@
export async function main(ns: NS) { export async function main(ns: NS) {
let hackingLevel = ns.getHackingLevel(); ns.run('hackallservers.js')
while (hackingLevel < 9999) { let hackingLevel = ns.getHackingLevel()
let oldHackingLevel = hackingLevel; while (hackingLevel < 9999) {
hackingLevel = ns.getHackingLevel(); let oldHackingLevel = hackingLevel
if(oldHackingLevel !== hackingLevel) { hackingLevel = ns.getHackingLevel()
ns.tprint(`Hacking level increased from ${oldHackingLevel} to ${hackingLevel}`); if (oldHackingLevel !== hackingLevel) {
ns.run("killall.js"); ns.tprint(`Hacking level increased from ${oldHackingLevel} to ${hackingLevel}`)
await ns.sleep(1000) // 1 second ns.run('killall.js')
ns.run("hackallservers.js"); await ns.sleep(1000) // 1 second
} ns.run('hackallservers.js')
// Wait 1 second before checking again }
await ns.sleep(1000) // Wait 1 second before checking again
} await ns.sleep(1000)
} }
}