Add ability to revert fleet manually

This commit is contained in:
Aelita4 2025-01-09 18:15:25 +01:00
parent 4fb4a19b0b
commit 14f399659e
Signed by: Aelita4
GPG Key ID: E44490C2025906C1
4 changed files with 112 additions and 15 deletions

View File

@ -2,13 +2,13 @@ import { ObjectId } from "mongodb";
import MissionType from "../../../types/MissionType";
import DBFleet from "../../../types/db/DBFleet";
import { updateFleet } from "../../db/fleet";
import { Planet } from "./PlanetManager";
import SystemManager, { System } from "./SystemManager";
import { sendMail } from "../../db/mails";
import { Sector } from "./LocationManager";
import { getRandomInRange, weightedRandom } from "../../utils/math";
import { getAllShips } from "../../db/ships";
import FleetShip from "../FleetShip";
import getDistanceBetween from "../../utils/getDistanceBetween";
import { getRandomInRange, weightedRandom } from "../../utils/math";
import { Sector } from "./LocationManager";
import { Planet } from "./PlanetManager";
import SystemManager from "./SystemManager";
export type Fleet = {
id: ObjectId,
@ -152,10 +152,12 @@ export default class FleetManager {
}
}
async initiateReturn() {
async initiateReturn(isByPlayer: boolean = false) {
this.data.returning = true;
this.data.departureTime = new Date(this.data.arrivalTime);
this.data.arrivalTime = new Date(this.data.departureTime.getTime() + 1000 * 30);
const elapsedTime = Date.now() - this.data.departureTime.getTime();
this.data.departureTime = isByPlayer ? new Date() : new Date(this.data.arrivalTime);
const travelTime = getDistanceBetween(this.data.destination, this.data.source);
this.data.arrivalTime = new Date(this.data.departureTime.getTime() + (isByPlayer ? elapsedTime : 1000 * travelTime));
await this.sync();
}

View File

@ -47,13 +47,13 @@ export default function getDistanceBetween(a: Planet | SystemManager | Sector, b
// b is planet
if("fields" in b) {
// same system
if(a.data._id.equals(b.system.data._id)) return BETWEEN_PLANETS;
if(a.data._id.equals(b.system.data._id)) return PLANET_TO_SYSTEM;
// same sector
if(a.data.sector._id.equals(b.system.data.sector._id)) return BETWEEN_PLANETS + BETWEEN_SYSTEMS;
if(a.data.sector._id.equals(b.system.data.sector._id)) return PLANET_TO_SYSTEM + BETWEEN_SYSTEMS;
// same galaxy
if(a.data.sector.galaxy._id.equals(b.system.data.sector.galaxy._id)) return BETWEEN_PLANETS + BETWEEN_SYSTEMS + BETWEEN_SECTORS;
if(a.data.sector.galaxy._id.equals(b.system.data.sector.galaxy._id)) return PLANET_TO_SYSTEM + BETWEEN_SYSTEMS + BETWEEN_SECTORS;
// different galaxy
return BETWEEN_PLANETS + BETWEEN_SYSTEMS + BETWEEN_SECTORS + BETWEEN_GALAXIES;
return PLANET_TO_SYSTEM + BETWEEN_SYSTEMS + BETWEEN_SECTORS + BETWEEN_GALAXIES;
}
// b is system
else if("planets" in b) {

View File

@ -0,0 +1,78 @@
import { APIRoute } from "astro";
import { ObjectId } from "mongodb";
import locationManager from "../../../lib/classes/managers/LocationManager";
import { getUserByAccessToken } from "../../../lib/db/users";
import validateAccessToken from "../../../lib/utils/validateAccessToken";
export const POST: APIRoute = async({ request }) => {
const response = await validateAccessToken(request);
if(response instanceof Response) return response;
const userDB = await getUserByAccessToken(response);
if(userDB === null) {
return new Response(
JSON.stringify({
code: 401,
message: "Unauthorized"
}), { status: 401 }
)
}
const user = locationManager.getUser(userDB._id);
if(!user) {
return new Response(
JSON.stringify({
code: 401,
message: "Unauthorized"
}), { status: 401 }
)
}
let body: { id: string };
try {
body = await request.json()
} catch(e) {
return new Response(
JSON.stringify({
code: 400,
message: "Bad Request",
error: "Invalid JSON body"
}), { status: 400 }
)
}
let id;
try {
id = new ObjectId(body.id);
} catch(e) {
return new Response(
JSON.stringify({
code: 400,
message: "Bad Request",
error: "Invalid ID format"
}), { status: 400 }
)
}
const fleet = locationManager.fleet.find(fleet => fleet.data.id.equals(id));
if(!fleet) {
return new Response(
JSON.stringify({
code: 404,
message: "Not Found",
error: "Fleet not found"
}), { status: 404 }
)
}
fleet.data.arrivalTime = new Date();
await fleet.initiateReturn(true);
await fleet.sync();
return new Response(
JSON.stringify({
code: 200,
message: "OK"
}), { status: 200 }
)
}

View File

@ -11,6 +11,7 @@ const { token, user, lang } = Astro.locals;
const active: SystemManager | Planet = Astro.locals.active;
const ships = await getAllShips();
const url = Astro.url.origin;
if(Astro.request.method === "POST") {
const form = await Astro.request.formData();
@ -132,7 +133,8 @@ const sectorsList = galaxies.map(galaxy => {
}).join(', ')} <br />
Cargo: {typeof f.cargo === "undefined" || f.cargo.length === 0 ? <>None</> : f.cargo.map(c => `${c.amount} ${getName(lang, 'resources', c.id)}`).join(', ')} <br />
Departured at: {f.departureTime.toISOString()} <br />
Arrives: {f.arrivalTime.toISOString()} ({Math.floor((f.arrivalTime.getTime() - new Date().getTime()) / 1000)})
Arrives: {f.arrivalTime.toISOString()} ({Math.floor((f.arrivalTime.getTime() - new Date().getTime()) / 1000)}) <br />
<button class="revert" style={`${f.returning && "display: none;"}`} data-id={f._id.toString()}>Revert</button>
</div>
</li>)
})}
@ -324,7 +326,8 @@ label {
color: black;
}
</style>
<script define:vars={{ lang, sectorsList }}>
<script define:vars={{ lang, sectorsList, url }}>
const revertButtons = document.querySelectorAll('.revert');
const destinationGalaxy = document.getElementById('destination-galaxy');
const destinationSector = document.getElementById('destination-sector');
const destinationSystem = document.getElementById('destination-system');
@ -332,10 +335,24 @@ label {
const toSystemCheckbox = document.querySelector('input[name="toSystem"]');
const sendAllButtons = document.querySelectorAll('.cargo-sendall');
if(!destinationGalaxy || !destinationSector || !destinationSystem || !destinationPlanet || !toSystemCheckbox || !sendAllButtons) {
if(!revertButtons || !destinationGalaxy || !destinationSector || !destinationSystem || !destinationPlanet || !toSystemCheckbox || !sendAllButtons) {
console.error('Could not find all elements');
return;
};
revertButtons.forEach(revBut => revBut.addEventListener('click', async evt => {
await fetch(`${url}/api/fleet/revert`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: evt.target.dataset.id
})
});
window.location.reload();
}));
destinationGalaxy.addEventListener('change', () => {
const galaxy = sectorsList.find(galaxy => galaxy._id === destinationGalaxy.value);