game-village-politics-backend/app/Presenters/VillagePresenter.php

86 lines
3.4 KiB
PHP
Raw Normal View History

<?php
namespace App\Presenters;
use App\Engine\Simulation;
use App\Models\Building;
use App\Models\BuildOrder;
use App\Models\Village;
use Carbon\CarbonImmutable;
/**
* The `village.show` payload (VillageState in the client's app/types/game.ts).
* Every number is computed here; the client only projects resources and countdowns.
*/
final class VillagePresenter
{
public static function present(Village $village, CarbonImmutable $now): array
{
$sim = Simulation::of($village);
$sim->settle($now);
$workforce = $sim->workforce();
$rules = $sim->rules();
$position = 0;
return [
'id' => $village->id,
'name' => $village->name,
'x' => $village->x,
'y' => $village->y,
'grid' => ['w' => $village->grid_w, 'h' => $village->grid_h],
'resources' => array_map(fn (float $n) => round($n, 4), $village->resources()),
'resources_at' => self::iso($village->resources_at),
'rates' => array_map(fn (float $n) => round($n, 4), $sim->rates()),
'storage_cap' => round($sim->storageCap()),
'population' => [
'food_budget' => round($workforce->foodBudget, 2),
'upkeep' => round($workforce->upkeep, 2),
'villagers' => $workforce->villagers,
'workers' => $workforce->workers(),
'soldiers' => 0,
],
'builders' => $sim->builders(),
'buildings' => $village->buildings->map(function (Building $b) use ($sim, $workforce, $rules) {
$output = $sim->output($b, $workforce);
return [
'id' => $b->id,
'type' => $b->type,
'level' => $b->level,
'x' => $b->x,
'y' => $b->y,
'footprint' => $rules->footprint($b->type),
'priority' => $b->priority,
'workers' => ['assigned' => $workforce->assigned[$b->id] ?? 0, 'required' => $workforce->required[$b->id] ?? 0],
'staffing' => round($workforce->ratio($b->id), 4),
'production' => $output ? ['resource' => $output['resource'], 'per_hour' => round($output['per_hour'], 2)] : null,
'upgrade' => $sim->upgradeOffer($b),
'demolish' => $sim->demolishOffer($b),
];
})->values()->all(),
'queue' => $village->orders->map(fn (BuildOrder $o) => [
'id' => $o->id,
'building_id' => $o->building_id,
'type' => $o->type,
'action' => $o->action,
'target_level' => $o->target_level,
'x' => $o->x,
'y' => $o->y,
'footprint' => $rules->footprint($o->type),
'cost' => $o->cost,
'position' => ++$position,
'builder' => $o->builder,
'starts_at' => $o->starts_at ? self::iso($o->starts_at) : null,
'finishes_at' => $o->finishes_at ? self::iso($o->finishes_at) : null,
])->values()->all(),
'buildable' => $sim->buildOptions(),
'server_time' => self::iso($now),
];
}
private static function iso(CarbonImmutable $at): string
{
return $at->utc()->format('Y-m-d\TH:i:s.v\Z');
}
}