More cleanup

This commit is contained in:
Zakary Timson 2022-03-15 22:05:34 -04:00
parent d699112d38
commit 3753ae02db
4 changed files with 86 additions and 97 deletions

View File

@ -1,4 +1,5 @@
import {ArgError, ArgParser} from './scripts/lib/arg-parser';
import {ArgError, ArgParser} from '/scripts/lib/arg-parser';
import {Logger} from '/scripts/lib/logger';
/**
* Buy, upgrade & manage Hacknet nodes automatically.
@ -11,13 +12,13 @@ export async function main(ns) {
{name: 'limit', desc: 'Limit the number of nodes the manager will buy, defaults to 8', optional: true, default: 8, type: 'num'},
{name: 'balance', desc: 'Prevent spending bellow point', flags: ['-b', '--balance'], type: 'num'},
{name: 'sleep', desc: 'Amount of time to wait between purchases, defaults to 1 (second)', flags: ['-s', '--sleep'], default: 1, type: 'num'}
]);
]);
try {
// Run
const args = argParser.parse(ns.args);
let nodeCount = ns.hacknet.numNodes();
const logger = new Logger(ns, () => [() => `Hacknet Manager: ${nodeCount}/${args['limit']}`]);
const logger = new Logger(ns, [() => `Hacknet Manager: ${nodeCount}/${args['limit']}`]);
while(true) {
const balance = ns.getServerMoneyAvailable('home');

View File

@ -2,29 +2,28 @@ export class Logger {
historyLen = 19;
history = [];
/**
* Create a nicer log with a banner.
* @param ns {NS} - BitBurner API
* @param lineFns {Function[]} - Functions to generate a line (Seperated by a linebreak)
*/
/**
* Create a nicer log with a banner.
* @param ns {NS} - BitBurner API
* @param lineFns {Function[]} - Functions to generate a line (Seperated by a linebreak)
*/
constructor(ns, lineFns = []) {
this.ns = ns;
this.fns = lineFns;
this.historyLen -= fns.length * 2;
this.historyLen -= lineFns.length * 2;
this.history = Array(this.historyLen).fill('');
this.log();
}
/**
* Add a linebreak
*/
/**
* Add a linebreak
*/
lineBreak() {
this.ns.print('===================================================');
}
/**
* Print the header using the provided functions
*/
/**
* Print the header using the provided functions
*/
header() {
this.lineBreak();
this.fns.forEach(fn => {
@ -33,9 +32,9 @@ export class Logger {
});
}
/**
* Add message to logs & output
*/
/**
* Add message to logs & output
*/
log(message) {
this.ns.clearLog();
this.header();

View File

@ -1,4 +1,14 @@
import {ArgError, ArgParser} from './scripts/lib/arg-parser';
import {ArgError, ArgParser} from '/scripts/lib/arg-parser';
import {Logger} from "/scripts/lib/logger";
/**
* BitBurner autocomplete
* @param data {server: string[], txts: string[], scripts: string[], flags: string[]} - Contextual information
* @returns {string[]} - Pool of autocomplete options
*/
export function autocomplete(data) {
return [...data.servers];
}
/**
* Weaken, Grow, Hack loop to "mine" target machine for money.
@ -7,64 +17,44 @@ import {ArgError, ArgParser} from './scripts/lib/arg-parser';
export async function main(ns) {
// Setup
ns.disableLog('ALL');
const historyLength = 15;
const messageHistory = Array(historyLength).fill('');
let maxBalance, balance, minSecurity, security;
const argParser = new ArgParser('miner.js', 'Weaken, Grow, Hack loop to "mine" machine for money. Tail for live updates', null, [
{name: 'device', desc: 'Device to mine, defaults to current machine', optional: true, default: ns.getHostname(), type: 'string'}
]);
let args;
try {
args = argParser.parse(ns.args);
// Run
const args = argParser.parse(ns.args);
let maxBalance, balance, minSecurity, security;
maxBalance = await ns.getServerMaxMoney(args['device']);
balance = await ns.getServerMoneyAvailable(args['device']);
minSecurity = await ns.getServerMinSecurityLevel(args['device']) + 2;
security = await ns.getServerSecurityLevel(args['device']);
const logger = new Logger(ns, [
() => `Mining: ${args['device']}`,
() => `Security: ${Math.round(security)}/${minSecurity}\tBalance: \$${Math.round(balance * 100) / 100}`
]);
while(true) {
// Update information
security = await ns.getServerSecurityLevel(args['device']);
balance = await ns.getServerMoneyAvailable(args['device']);
// Pick step
if(security > minSecurity) { // Weaken
logger.log('Attacking Security...');
const w = await ns.weaken(args['device']);
logger.log(`Security: -${w}`);
} else if(balance < maxBalance) { // Grow
logger.log('Spoofing Balance...');
const g = await ns.grow(args['device']);
logger.log(`Balance: +$${Math.round((g * balance - balance) * 100) / 100}`);
} else { // Hack
logger.log('Hacking Account...');
const h = await ns.hack(args['device']);
logger.log(`Balance: -$${h}`);
}
}
} catch(err) {
if(err instanceof ArgError) return ns.tprint(argParser.help(err.message));
throw err;
}
/**
* Print header with logs
* @param message - message to append to logs
*/
function log(message) {
const sec = `${Math.round(security)}/${minSecurity}`;
ns.clearLog();
ns.print('===================================================');
ns.print(`Mining: ${args['device']}`);
ns.print('===================================================');
ns.print(`Security: ${sec}${sec.length < 6 ? '\t' : ''}\tBalance: $${Math.round(balance * 100) / 100}`);
ns.print('===================================================');
if(message != null) messageHistory.push(message);
messageHistory.splice(0, messageHistory.length - historyLength);
messageHistory.forEach(m => ns.print(m));
}
log();
do {
// Update information
security = await ns.getServerSecurityLevel(args['device']);
balance = await ns.getServerMoneyAvailable(args['device']);
// Pick step
if(security > minSecurity) { // Weaken
log('Attacking Security...');
const w = await ns.weaken(args['device']);
log(`Security: -${w}`);
} else if(balance < maxBalance) { // Grow
log('Spoofing Balance...');
const g = await ns.grow(args['device']);
log(`Balance: +$${Math.round((g * balance - balance) * 100) / 100}`);
} else { // Hack
log('Hacking Account...');
const h = await ns.hack(args['device']);
log(`Balance: -$${h}`);
}
} while(true);
}
export function autocomplete(data) {
return [...data.servers];
}

View File

@ -15,25 +15,6 @@ export function autocomplete(data) {
* @param ns {NS} - BitBurner API
*/
export async function main(ns) {
// Setup
ns.disableLog('ALL');
const argParser = new ArgParser('network-graph.js', 'Scan the network for devices and display as an ASCII tree:\n home\n ├─ n00dles (ROOTED)\n | └─ max-hardware (80|1)\n | └─ neo-net (50|1)\n ├─ foodnstuff (ROOTED)\n └─ sigma-cosmetics (ROOTED)', null, [
{name: 'device', desc: 'Point to start scan from, defaults to current machine', optional: true, default: ns.getHostname(), type: 'string'},
{name: 'depth', desc: 'Depth to scan to, defaults is 3', flags: ['-d', '--depth'], default: Infinity, type: 'num'},
{name: 'filter', desc: 'Filter to device matching name', flags: ['-f', '--filter'], type: 'string'},
{name: 'regex', desc: 'Filter to devices matching pattern', flags: ['-e', '--regex'], type: 'string'},
{name: 'rooted', desc: 'Filter to devices that have been rooted', flags: ['-r', '--rooted'], type: 'bool'},
{name: 'notRooted', desc: 'Filter to devices that have not been rooted', flags: ['-n', '--not-rooted'], type: 'bool'},
{name: 'verbose', desc: 'Display the required hack level & number of ports to root: (level|port)', flags: ['-v', '--verbose'], type: 'bool'},
]);
let args;
try {
args = argParser.parse(ns.args);
} catch(err) {
if(err instanceof ArgError) return ns.tprint(argParser.help(err.message));
throw err;
}
/**
* Iterate tree & print to screen
* @param tree {Object} - Tree to parse
@ -51,14 +32,32 @@ export async function main(ns) {
});
}
// Run
const [devices, network] = scanNetwork(ns, args['device'], args['depth']);
const stats = devices.reduce((acc, d) => ({...acc, [d]: ns.getServer(d)}), {});
if(args['regex']) pruneTree(network, d => RegExp(args['regex']).test(d)); // Regex flag
else if(args['filter']) pruneTree(network, d => d == args['filter']); // Filter flag
if(args['rooted']) pruneTree(network, d => stats[d].hasAdminRights); // Rooted flag
else if(args['notRooted']) pruneTree(network, d => !stats[d].hasAdminRights); // Not rooted flag
ns.tprint(args['device']);
render(network, args['verbose'] ? stats : null);
ns.tprint('');
// Setup
ns.disableLog('ALL');
const argParser = new ArgParser('network-graph.js', 'Scan the network for devices and display as an ASCII tree:\n home\n ├─ n00dles (ROOTED)\n | └─ max-hardware (80|1)\n | └─ neo-net (50|1)\n ├─ foodnstuff (ROOTED)\n └─ sigma-cosmetics (ROOTED)', null, [
{name: 'device', desc: 'Point to start scan from, defaults to current machine', optional: true, default: ns.getHostname(), type: 'string'},
{name: 'depth', desc: 'Depth to scan to, defaults is 3', flags: ['-d', '--depth'], default: Infinity, type: 'num'},
{name: 'filter', desc: 'Filter to device matching name', flags: ['-f', '--filter'], type: 'string'},
{name: 'regex', desc: 'Filter to devices matching pattern', flags: ['-e', '--regex'], type: 'string'},
{name: 'rooted', desc: 'Filter to devices that have been rooted', flags: ['-r', '--rooted'], type: 'bool'},
{name: 'notRooted', desc: 'Filter to devices that have not been rooted', flags: ['-n', '--not-rooted'], type: 'bool'},
{name: 'verbose', desc: 'Display the required hack level & number of ports to root: (level|port)', flags: ['-v', '--verbose'], type: 'bool'},
]);
try {
// Run
const args = argParser.parse(ns.args);
const [devices, network] = scanNetwork(ns, args['device'], args['depth']);
const stats = devices.reduce((acc, d) => ({...acc, [d]: ns.getServer(d)}), {});
if(args['regex']) pruneTree(network, d => RegExp(args['regex']).test(d)); // Regex flag
else if(args['filter']) pruneTree(network, d => d == args['filter']); // Filter flag
if(args['rooted']) pruneTree(network, d => stats[d].hasAdminRights); // Rooted flag
else if(args['notRooted']) pruneTree(network, d => !stats[d].hasAdminRights); // Not rooted flag
ns.tprint(args['device']);
render(network, args['verbose'] ? stats : null);
ns.tprint('');
} catch(err) {
if(err instanceof ArgError) return ns.tprint(argParser.help(err.message));
throw err;
}
}