game-village-politics-backend/app/Game/Travel/TravelTime.php

91 lines
2.8 KiB
PHP
Raw Normal View History

<?php
namespace App\Game\Travel;
use App\Game\WorldConfig;
use InvalidArgumentException;
/**
* How long a group takes between two villages, and how early the target sees it.
* A group moves at its slowest unit's pace (minutes per field), sped up by the
* world speed, the world's unit speed and its travel mode.
*/
final class TravelTime
{
public function __construct(private readonly WorldConfig $config) {}
public static function distance(int $fromX, int $fromY, int $toX, int $toY): float
{
return sqrt(($toX - $fromX) ** 2 + ($toY - $fromY) ** 2);
}
/** @return list<string> */
public function modes(): array
{
return array_keys($this->config->get('movement.modes', []));
}
public function hasMode(string $mode): bool
{
return in_array($mode, $this->modes(), true);
}
public function defaultMode(): string
{
return $this->config->get('movement.default_mode', 'normal');
}
/** @return array{speed: float, visibility: float} */
public function mode(string $mode): array
{
$values = $this->config->get("movement.modes.$mode") ?? throw new InvalidArgumentException("Unknown travel mode [$mode].");
return ['speed' => (float) $values['speed'], 'visibility' => (float) $values['visibility']];
}
/**
* Minutes per field of the slowest unit in the group, at world speed 1.
*
* @param array<string, int> $units unit => count
*/
public function slowest(array $units): float
{
$minutes = 0.0;
foreach ($units as $unit => $count) {
if ($count > 0) {
$minutes = max($minutes, (float) $this->config->get("units.$unit.speed"));
}
}
return $minutes;
}
/**
* Seconds the group takes for $distance fields.
*
* @param array<string, int> $units
*/
public function seconds(array $units, float $distance, string $mode): int
{
$pace = $this->config->speed() * $this->config->get('movement.unit_speed', 1.0) * $this->mode($mode)['speed'];
return max(1, (int) round($this->slowest($units) * $distance * 60 / $pace));
}
/**
* Seconds before arrival at which the target spots the group: once it comes within
* the mode's visibility plus the target's detection radius. An unseen mode shows up
* only when it arrives; a group that starts within range is seen at once.
*/
public function warningSeconds(int $seconds, float $distance, string $mode, float $detection): int
{
$visibility = $this->mode($mode)['visibility'];
if ($visibility <= 0) {
return 0;
}
$range = $visibility + $detection;
return $range >= $distance ? $seconds : (int) floor($seconds * $range / $distance);
}
}