diff options
author | Julien Dessaux | 2023-06-01 01:11:21 +0200 |
---|---|---|
committer | Julien Dessaux | 2023-06-01 01:11:21 +0200 |
commit | 68c457964a02d290f3fe225b090c549d664bb836 (patch) | |
tree | 4b63ee97f5439621536594c59f25b1c35c353b37 | |
parent | Reworked the systems handling and caching with sqlite (diff) | |
download | spacetraders-68c457964a02d290f3fe225b090c549d664bb836.tar.gz spacetraders-68c457964a02d290f3fe225b090c549d664bb836.tar.bz2 spacetraders-68c457964a02d290f3fe225b090c549d664bb836.zip |
Another big refactoring
-rw-r--r-- | automation/automation.js | 26 | ||||
-rw-r--r-- | automation/contracting.js | 6 | ||||
-rw-r--r-- | automation/exploration.js | 20 | ||||
-rw-r--r-- | automation/mining.js | 7 | ||||
-rw-r--r-- | database/config.js | 10 | ||||
-rw-r--r-- | database/systems.js | 6 | ||||
-rw-r--r-- | lib/agent.js | 34 | ||||
-rw-r--r-- | lib/ships.js | 16 | ||||
-rw-r--r-- | lib/systems.js | 19 | ||||
-rwxr-xr-x | main.js | 18 |
10 files changed, 79 insertions, 83 deletions
diff --git a/automation/automation.js b/automation/automation.js new file mode 100644 index 0000000..c7fa6f7 --- /dev/null +++ b/automation/automation.js @@ -0,0 +1,26 @@ +import * as dbConfig from '../database/config.js'; +import * as dbShips from '../database/ships.js'; +import * as exploration from './exploration.js'; + +// This function registers then inits the database +export async function register(symbol, faction) { + const response = await fetch('https://api.spacetraders.io/v2/register', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ + symbol: symbol, + faction: faction, + }), + }); + const json = await response.json(); + console.log(JSON.stringify(response, null, 2)); + if (response.error !== undefined) { + throw response; + } + dbConfig.registerAgent(json.data); + exploration.init(); + // TODO ship + // TODO contract +} diff --git a/automation/contracting.js b/automation/contracting.js index aebb265..b5c7292 100644 --- a/automation/contracting.js +++ b/automation/contracting.js @@ -34,14 +34,14 @@ export async function auto(ctx) { await ships.navigate({ship: ctx.ship, waypoint: deliveryPoint}); break; case deliveryPoint: - await ships.dock({ship: ctx.ship}); + await ships.dock({symbol: ctx.ship}); await ships.refuel({ship: ctx.ship}); console.log(`delivering ${goodCargo.units} of ${good}`); await contracts.deliver({contract: contract.id, ship: ctx.ship, good: good, units: goodCargo.units }); await ships.navigate({ship: ctx.ship, waypoint: asteroidField}); - await ships.dock({ship: ctx.ship}); + await ships.dock({symbol: ctx.ship}); await ships.refuel({ship: ctx.ship}); - await ships.orbit({ship: ctx.ship}); + await ships.orbit({symbol: ctx.ship}); break; default: throw `where is the ship?`; diff --git a/automation/exploration.js b/automation/exploration.js new file mode 100644 index 0000000..9ea5bf8 --- /dev/null +++ b/automation/exploration.js @@ -0,0 +1,20 @@ +import * as db from '../database/systems.js'; + +// Retrieves all systems information, should be called only once after registering +export async function init() { + if (db.isInit()) { + return; + } + for (let page=1; true; ++page) { + const response = await api.send({endpoint: `/systems?limit=20&page=${page}`, priority:100}); + if (response.error !== undefined) { + throw response; + } + response.data.forEach(system => db.setSystem(system)); + if (response.meta.total <= response.meta.limit * page) { + break; + } + } + console.log('Finished retrieving all systems information'); + db.init(); +} diff --git a/automation/mining.js b/automation/mining.js index bdd89ac..a719bff 100644 --- a/automation/mining.js +++ b/automation/mining.js @@ -13,13 +13,13 @@ export async function mineUntilFullOf(ctx) { if (good?.units + (antimatter?.units ?? 0) >= response.data.cargo.capacity * 0.9) { // > 90% full of the valuable goods return good.units; } else { // we are full but need to sell junk - await ships.dock({ship: ctx.ship}); + await ships.dock({symbol: ctx.ship}); for (let i=0; i<inventory.length; ++i) { if (inventory[i].symbol === 'ANTIMATTER') continue; //console.log(`selling ${inventory[i].units} of ${inventory[i].symbol}`); await ships.sell({ship: ctx.ship, good: inventory[i].symbol, units: inventory[i].units}); } - await ships.orbit({ship: ctx.ship}); + await ships.orbit({symbol: ctx.ship}); } } } @@ -31,7 +31,8 @@ async function mineUntilFull(ctx) { const response = await ships.extract(ctx); if (response === null) return null; //console.log(`${ctx.ship}: extracted ${response.data.extraction.yield.units} of ${response.data.extraction.yield.symbol}`); - await api.sleep(response.data.cooldown.remainingSeconds*1000); if (response.data.cargo.units >= response.data.cargo.capacity * 0.9) return response; } } + +// TODO surveying the asteroid field diff --git a/database/config.js b/database/config.js index 6db856e..4a86cb6 100644 --- a/database/config.js +++ b/database/config.js @@ -1,20 +1,20 @@ import db from './db.js'; -const getTokenStatement = db.prepare(`SELECT value from config where key = 'token';`); -const registerAgentStatement = db.prepare(`INSERT INTO config(key, value) VALUES ('symbol', ?), ('faction', ?), ('token', ?);`); +const getTokenStatement = db.prepare(`SELECT json_extract(value, '$.token') as token from config where key = 'register_data';`); +const registerAgentStatement = db.prepare(`INSERT INTO config(key, value) VALUES ('register_data', json(?));`); export function getToken() { try { - return getTokenStatement.get().value; + return getTokenStatement.get().token; } catch (err) { console.log(err); return null; } } -export function registerAgent(symbol, faction, token) { +export function registerAgent(data) { try { - registerAgentStatement.run(symbol, faction, token); + registerAgentStatement.run(JSON.stringify(data)); return true; } catch (err) { console.log(err); diff --git a/database/systems.js b/database/systems.js index e3822d3..337126c 100644 --- a/database/systems.js +++ b/database/systems.js @@ -1,7 +1,7 @@ import db from './db.js'; -const getSystemStatement = db.prepare(`SELECT data from systems where json_extract(data, '$.symbol') = ?;`); -const getSystemUpdatedStatement = db.prepare(`SELECT updated from systems where json_extract(data, '$.symbol') = ?;`); +const getSystemStatement = db.prepare(`SELECT data FROM systems WHERE json_extract(data, '$.symbol') = ?;`); +const getSystemUpdatedStatement = db.prepare(`SELECT updated FROM systems WHERE json_extract(data, '$.symbol') = ?;`); const setSystemStatement = db.prepare(`INSERT INTO systems(data) VALUES (json(?));`); const setSystemWaypointsStatement = db.prepare(`UPDATE systems SET data = (SELECT json_set(data, '$.waypoints', json(:waypoints)) FROM systems WHERE json_extract(data, '$.symbol') = :symbol), updated = :date WHERE json_extract(data, '$.symbol') = :symbol;`); @@ -61,7 +61,7 @@ export function setSystemWaypoints(symbol, waypoints) { date: new Date().toISOString(), symbol: symbol, waypoints: JSON.stringify(waypoints), - }); + }).changes; } catch (err) { console.log(err); return null; diff --git a/lib/agent.js b/lib/agent.js deleted file mode 100644 index bf27e85..0000000 --- a/lib/agent.js +++ /dev/null @@ -1,34 +0,0 @@ -import { registerAgent } from '../database/config.js'; - -// This function inits the database in case we have an already registered game -export function init(symbol, faction, token) { - registerAgent(symbol, faction, token); - // TODO ships - // TODO contract - // TODO agent -} - -// This function registers then inits the database -export function register(symbol, faction) { - fetch( - 'https://api.spacetraders.io/v2/register', - { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - }, - body: JSON.stringify({ - symbol: symbol, - faction: faction, - }), - }) - .then(response => response.json()) - .then(response => { - console.log(JSON.stringify(response, null, 2)); - init(symbol, faction, response.data.token); - // TODO ship - // TODO contract - // TODO agent - }) - .catch(err => console.error(err)); -} diff --git a/lib/ships.js b/lib/ships.js index 109054c..55ee585 100644 --- a/lib/ships.js +++ b/lib/ships.js @@ -12,12 +12,14 @@ export async function extract(ctx) { default: // yet unhandled error throw response; } + } else { + await api.sleep(response.data.cooldown.remainingSeconds*1000); } return response; } export async function dock(ctx) { - const response = await api.send({endpoint: `/my/ships/${ctx.ship}/dock`, method: 'POST'}); + const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/dock`, method: 'POST'}); if (response.error !== undefined) { switch(response.error.code) { case 4214: // ship is in transit @@ -48,7 +50,17 @@ export async function negotiate(ctx) { } export async function orbit(ctx) { - return await api.send({endpoint: `/my/ships/${ctx.ship}/orbit`, method: 'POST'}); + const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/orbit`, method: 'POST'}); + if (response.error !== undefined) { + switch(response.error.code) { + case 4214: // ship is in transit + await api.sleep(response.error.data.secondsToArrival * 1000); + return orbit(ctx); + default: // yet unhandled error + throw response; + } + } + return response; } export async function purchase(ctx) { diff --git a/lib/systems.js b/lib/systems.js index 3cc7c7a..fcbf41a 100644 --- a/lib/systems.js +++ b/lib/systems.js @@ -1,25 +1,6 @@ import * as api from './api.js'; import * as db from '../database/systems.js'; -// Retrieves all systems information, should be called only once after registering -export async function init(ctx) { - if (db.isInit()) { - return; - } - for (let page=1; true; ++page) { - const response = await api.send({endpoint: `/systems?limit=20&page=${page}`, priority:100}); - if (response.error !== undefined) { - throw response; - } - response.data.forEach(system => db.setSystem(system)); - if (response.meta.total <= response.meta.limit * page) { - break; - } - } - console.log('Finished retrieving all systems information'); - db.init(); -} - // Retrieves a shipyard's information for ctx.symbol export async function shipyard(ctx) { const systemSymbol = ctx.symbol.match(/([^-]+-[^-]+)/)[1]; // TODO generalise this extraction @@ -1,6 +1,6 @@ +import * as automation from './automation/automation.js'; import * as autoContracting from './automation/contracting.js'; import * as autoMining from './automation/mining.js'; -import * as agent from './lib/agent.js'; import * as api from './lib/api.js'; import * as contracts from './lib/contracts.js'; import * as ships from './lib/ships.js'; @@ -23,19 +23,12 @@ case 'autoContractForShip': case 'autoMiningForShip': await autoMining.mineUntilFullOf({ship: process.argv[3], good: 'NON_EXISTENT'}); break; -case 'init': - if (process.argv[3] !== undefined && process.argv[4] !== undefined && process.argv[5] !== undefined) { - agent.init(process.argv[3], process.argv[4], process.argv[5]); - } else { - usage(); - } - break; case 'my-agent': api.debugLog(await api.send({endpoint: '/my/agent'})); break; case 'register': if (process.argv[3] !== undefined && process.argv[4] !== undefined) { - agent.register(process.argv[3], process.argv[4]); + automation.register(process.argv[3], process.argv[4]); } else { usage(); } @@ -59,7 +52,7 @@ default: api.debugLog(await contracts.fulfill({contract: process.argv[3]})); break; case 'ships.dock': - api.debugLog(await ships.dock({ship: process.argv[3]})); + api.debugLog(await ships.dock({symbol: process.argv[3]})); break; case 'ships.extract': api.debugLog(await ships.extract({ship: process.argv[3]})); @@ -80,7 +73,7 @@ default: api.debugLog(await ships.navigate({ship: process.argv[3], waypoint: process.argv[4]})); break; case 'ships.orbit': - api.debugLog(await ships.orbit({ship: process.argv[3]})); + api.debugLog(await ships.orbit({symbol: process.argv[3]})); break; case 'ships.purchase': api.debugLog(await ships.purchase({shipType: process.argv[3], waypoint: process.argv[4]})); @@ -109,9 +102,6 @@ default: case 'systems.shipyards': api.debugLog(await systems.trait({symbol: process.argv[3], trait: 'SHIPYARD'})); break; - case 'systems.init': - await systems.init(); - break; case 'systems.system': api.debugLog(await systems.system({symbol: process.argv[3]})); break; |