1
0
Fork 0

Another big refactoring

This commit is contained in:
Julien Dessaux 2023-06-01 01:11:21 +02:00
parent 61b5c8493e
commit 68c457964a
Signed by: adyxax
GPG key ID: F92E51B86E07177E
10 changed files with 79 additions and 83 deletions

26
automation/automation.js Normal file
View file

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

View file

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

20
automation/exploration.js Normal file
View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -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) {

View file

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

18
main.js
View file

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