48 lines
1.5 KiB
PHP
48 lines
1.5 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
namespace App\Game\Combat;
|
||
|
|
|
||
|
|
use App\Game\WorldConfig;
|
||
|
|
|
||
|
|
/** What surviving attackers carry home: wood, clay and iron above what is hidden, split evenly. */
|
||
|
|
final class LootCalculator
|
||
|
|
{
|
||
|
|
public function __construct(private readonly WorldConfig $config) {}
|
||
|
|
|
||
|
|
/** @param array<string, int> $units */
|
||
|
|
public function capacity(array $units): int
|
||
|
|
{
|
||
|
|
$carry = 0;
|
||
|
|
foreach ($units as $unit => $count) {
|
||
|
|
$carry += $count * (int) $this->config->get("units.$unit.carry", 0);
|
||
|
|
}
|
||
|
|
|
||
|
|
return $carry;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Take up to $capacity from the stock, the same from each resource as far as it
|
||
|
|
* goes; what one resource lacks, the others make up. $hidden is kept back from each.
|
||
|
|
*
|
||
|
|
* @param array{wood: float, clay: float, iron: float} $stock
|
||
|
|
* @return array{wood: int, clay: int, iron: int}
|
||
|
|
*/
|
||
|
|
public static function take(array $stock, float $hidden, int $capacity): array
|
||
|
|
{
|
||
|
|
$available = array_map(fn (float $n) => max(0, (int) floor($n - $hidden)), $stock);
|
||
|
|
$loot = array_map(fn () => 0, $available);
|
||
|
|
$left = $capacity;
|
||
|
|
while ($left > 0 && ($open = array_keys(array_filter($available)))) {
|
||
|
|
$share = max(1, intdiv($left, count($open)));
|
||
|
|
foreach ($open as $resource) {
|
||
|
|
$take = min($share, $available[$resource], $left);
|
||
|
|
$loot[$resource] += $take;
|
||
|
|
$available[$resource] -= $take;
|
||
|
|
$left -= $take;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return $loot;
|
||
|
|
}
|
||
|
|
}
|