game-village-politics-backend/app/Game/Military/UnitRules.php

88 lines
2.5 KiB
PHP
Raw Normal View History

<?php
namespace App\Game\Military;
use App\Game\Buildings\BuildingRules;
use App\Game\WorldConfig;
/** What units cost, eat and take to train, and where they are trained. */
final class UnitRules
{
public function __construct(private readonly WorldConfig $config) {}
/** @return list<string> */
public function units(): array
{
return array_keys($this->config->get('units', []));
}
public function exists(string $unit): bool
{
return array_key_exists($unit, $this->config->get('units', []));
}
/** @return list<string> units trained at this building type */
public function trainedAt(string $buildingType): array
{
return array_values(array_filter($this->units(), fn (string $u) => $this->unit($u)['building'] === $buildingType));
}
public function building(string $unit): string
{
return $this->unit($unit)['building'];
}
/** @return array{wood: int, clay: int, iron: int} */
public function cost(string $unit, int $count = 1): array
{
return array_map(fn (int $n) => $n * $count, $this->unit($unit)['cost']);
}
/** Food per hour one unit eats. */
public function upkeep(string $unit): float
{
return (float) $this->unit($unit)['upkeep'];
}
/**
* Seconds to train one unit, at world speed, sped up by the training building's
* level and slowed by its staffing (output factor 0..1).
*/
public function seconds(string $unit, int $buildingLevel, float $staffing): int
{
$seconds = $this->unit($unit)['build_time']
/ $this->config->speed()
/ (1 + $this->config->get('economy.recruit_speed_per_level', 0) * BuildingRules::above($buildingLevel))
/ max($staffing, 0.01);
return max(1, (int) ceil($seconds));
}
/** @return array<string, int> building type => minimum level of any instance */
public function requires(string $unit): array
{
return $this->unit($unit)['requires'] ?? [];
}
/**
* Food per hour these troops eat.
*
* @param array<string, int> $counts unit => count
*/
public function upkeepOf(array $counts): float
{
$total = 0.0;
foreach ($counts as $unit => $n) {
$total += $this->upkeep($unit) * $n;
}
return $total;
}
/** @return array<string, mixed> */
private function unit(string $unit): array
{
return $this->config->get("units.$unit") ?? throw new \InvalidArgumentException("Unknown unit [$unit].");
}
}