aslobot-matrix/src/services/game/location.ts
2026-01-21 15:45:41 -05:00

104 lines
2.5 KiB
TypeScript

import type { MatrixClient } from "matrix-js-sdk";
import {
Location,
locationFarlands,
locations,
type ILocation,
} from "./structures/locations.js";
import type { IPlayer } from "./structures/entities.js";
import { getSpeed } from "./entity.js";
const getLocation = (id: Location): ILocation => {
const location = locations.find((location) => location.id === id);
return location ? location : locationFarlands;
};
const getLocationByName = (name: string): ILocation => {
const location = locations.find(
(location) => location.name.toLowerCase() === name.toLowerCase(),
);
return location ? location : locationFarlands;
};
const getLocationDistance = (
locationA: ILocation,
locationB: ILocation,
): number => {
const deltaX = Math.abs(locationA.X - locationB.X);
const deltaY = Math.abs(locationA.Y - locationB.Y);
const deltaPow = Math.pow(deltaX, 2) + Math.pow(deltaY, 2);
return Math.sqrt(deltaPow);
};
const getParentLocation = (childLocation: Location): ILocation => {
const parentLocation = locations.find((location) =>
location.childLocations.includes(childLocation),
);
return parentLocation ? parentLocation : locationFarlands;
};
const hasLocation = (
locationParent: Location,
locationChild: Location,
): boolean => {
const childLocations = getLocation(locationParent).childLocations;
return childLocations.includes(locationChild);
};
const getTravelTimeInHours = (
player: IPlayer,
locationA: ILocation,
locationB: ILocation,
) => {
const distance = getLocationDistance(locationA, locationB);
return (distance / getSpeed(player)) * 3600000;
};
const startTravel = (
player: IPlayer,
location: Location,
client: MatrixClient,
roomId: string,
) => {
const currentLocation = getLocation(player.location);
const newLocation = getLocation(location);
setTimeout(
() => {
finishTravel(player, newLocation, client, roomId);
},
getTravelTimeInHours(player, currentLocation, newLocation),
);
};
const finishTravel = (
player: IPlayer,
location: ILocation,
client: MatrixClient,
roomId: string,
) => {
player.location = location.id;
client.sendTextMessage(
roomId,
`${player.name} has arrived to ${location.name}`,
);
};
export {
getLocation,
getLocationByName,
getLocationDistance,
getParentLocation,
hasLocation,
getTravelTimeInHours,
startTravel,
finishTravel,
};