game-village-politics-backend/app/Engine/Simulation.php

556 lines
21 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
namespace App\Engine;
use App\Game\Buildings\BuildingRules;
use App\Game\Buildings\BuildingState;
use App\Game\Buildings\BuildQueue;
use App\Game\Buildings\Specialisation;
use App\Game\Economy\Population;
use App\Game\Economy\Production;
use App\Game\Economy\Settle;
use App\Game\Economy\Workforce;
use App\Game\GameRuleViolation;
use App\Game\Military\UnitRules;
use App\Game\WorldConfig;
use App\Models\Building;
use App\Models\BuildOrder;
use App\Models\GameEvent;
use App\Models\RecruitOrder;
use App\Models\UnitStack;
use App\Models\Village;
use App\Models\Wounded;
use Carbon\CarbonImmutable;
/**
* Applies the pure rules in app/Game to one village and its rows. Callers hold the
* village lock; this class changes the loaded models and their relations in step.
*/
final class Simulation
{
private WorldConfig $config;
private BuildingRules $rules;
private Population $population;
private Production $production;
private ?Workforce $workforce = null;
/** Set while a payload is built: nothing changes, so derived values are computed once. */
private bool $frozen = false;
private ?float $hqStaffing = null;
/** @var array<int, int>|null building id => its index among its type */
private ?array $indexes = null;
/** @var array<int, float>|null building id => the share its instance works at */
private ?array $shares = null;
private ?string $workforceFor = null;
private function __construct(private readonly Village $village)
{
$this->config = $village->world->gameConfig();
$this->rules = new BuildingRules($this->config);
$this->population = new Population($this->config);
$this->production = new Production($this->config);
}
/** For reading only (the village payload): workforce, staffing and indexes are computed once. */
public function freeze(): self
{
$this->frozen = true;
return $this;
}
public static function of(Village $village): self
{
return new self($village->loadMissing(['world', 'buildings', 'orders', 'troops', 'recruits', 'wounded']));
}
public function config(): WorldConfig
{
return $this->config;
}
public function rules(): BuildingRules
{
return $this->rules;
}
// Economy
/** @return list<BuildingState> */
public function states(): array
{
return $this->village->buildings->map(fn (Building $b) => $b->state())->values()->all();
}
public function workforce(): Workforce
{
// One village state, one workforce: a payload asks for it dozens of times.
if ($this->frozen && $this->workforce) {
return $this->workforce;
}
$key = $this->workforceKey();
if ($key !== $this->workforceFor) {
$this->workforce = $this->population->workforce($this->states(), $this->soldierUpkeep(), (int) $this->village->militia);
$this->workforceFor = $key;
}
return $this->workforce;
}
/** What the workforce depends on: buildings with their levels and priorities, troops, training, militia. */
private function workforceKey(): string
{
$parts = [(string) (int) $this->village->militia];
foreach ($this->village->buildings as $b) {
$parts[] = "$b->id:$b->level:$b->priority";
}
foreach ($this->village->troops as $s) {
$parts[] = "t$s->id:$s->unit:$s->count";
}
foreach ($this->village->recruits as $o) {
$parts[] = "r$o->id:".($o->count - $o->done);
}
foreach ($this->village->wounded as $w) {
$parts[] = "w$w->id";
}
return implode('|', $parts);
}
/**
* Heads (food per hour at world speed 1) eaten by troops standing here, by units still
* in training and by the wounded: a queued unit takes its villager's place at once, a
* wounded one keeps it.
*/
public function soldierUpkeep(): float
{
$units = new UnitRules($this->config);
$standing = $this->village->troops->mapWithKeys(fn (UnitStack $s) => [$s->id => $units->upkeep($s->unit) * $s->count])->sum();
$training = $this->village->recruits->sum(fn (RecruitOrder $o) => $units->upkeep($o->unit) * ($o->count - $o->done));
$wounded = $this->village->wounded->sum(fn (Wounded $w) => array_sum(array_map(
fn (string $unit, int $count) => $units->exists($unit) ? $units->upkeep($unit) * $count : 0,
array_keys($w->units), $w->units,
)));
return $standing + $training + $wounded;
}
/** @return array{wood: float, clay: float, iron: float, food: float} */
public function rates(): array
{
return $this->production->rates($this->states(), $this->workforce());
}
/** @return array{resource: string, per_hour: float}|null */
public function output(Building $building, Workforce $workforce): ?array
{
return $this->production->output($building->state(), $workforce, $this->specialisation()->productionBonus($this->role(), $building->type), $this->share($building));
}
/**
* The share each standing instance works at: copies of a type give less, ranked by
* level (BuildingRules::instanceShares).
*
* @return array<int, float> building id => share
*/
public function shares(): array
{
if ($this->frozen && $this->shares !== null) {
return $this->shares;
}
return $this->shares = $this->rules->instanceShares($this->states());
}
public function share(Building $building): float
{
return $this->shares()[$building->id] ?? 1.0;
}
public function specialisation(): Specialisation
{
return new Specialisation($this->config);
}
/** The village's role from the buildings standing, or null. */
public function role(): ?string
{
return $this->specialisation()->role($this->village->buildings->pluck('type'));
}
public function staffingFactor(float $ratio): float
{
return $this->production->staffingFactor($ratio);
}
public function storageCap(): float
{
$shares = $this->shares();
return $this->village->buildings->sum(fn (Building $b) => $this->rules->capacity($b->type, $b->level) * ($shares[$b->id] ?? 1.0));
}
/** Write stored + rate × elapsed up to $at into the village. Call before any change. */
public function settle(CarbonImmutable $at): void
{
$from = $this->village->resources_at;
if ($at->lessThanOrEqualTo($from)) {
return;
}
$hours = ($at->getTimestampMs() - $from->getTimestampMs()) / 3_600_000;
$this->village->fill(Settle::advance($this->village->resources(), $this->rates(), $this->storageCap(), $hours));
$this->village->resources_at = $at;
}
/** @param array{wood: int, clay: int, iron: int} $cost */
public function canPay(array $cost): bool
{
return $this->village->wood >= $cost['wood']
&& $this->village->clay >= $cost['clay']
&& $this->village->iron >= $cost['iron'];
}
/** @param array{wood: int, clay: int, iron: int} $cost */
public function pay(array $cost): void
{
if (! $this->canPay($cost)) {
throw new GameRuleViolation('resources', 'Not enough resources.');
}
foreach ($cost as $resource => $amount) {
$this->village->{$resource} -= $amount;
}
}
/** @param array<string, int> $amount */
public function refund(array $amount): void
{
$cap = $this->storageCap();
foreach ($amount as $resource => $n) {
$this->village->{$resource} = min($cap, $this->village->{$resource} + $n);
}
}
// Buildings
public function hqLevel(): int
{
return $this->village->buildings->firstWhere('type', 'headquarters')?->level ?? 0;
}
/** Output factor of the headquarters' staffing; it scales build speed. */
public function hqStaffing(): float
{
if ($this->frozen && $this->hqStaffing !== null) {
return $this->hqStaffing;
}
$hq = $this->village->buildings->firstWhere('type', 'headquarters');
return $this->hqStaffing = $hq ? $this->production->staffingFactor($this->workforce()->ratio($hq->id)) : $this->production->staffingFactor(0);
}
public function builders(): int
{
return $this->rules->builders($this->hqLevel());
}
/** Instances of a type, counting new ones still in the queue. */
public function instances(string $type): int
{
return $this->village->buildings->where('type', $type)->count()
+ $this->village->orders->where('action', BuildOrder::BUILD)->where('type', $type)->count();
}
/**
* 0-based rank among same-type instances, by level like the share (BuildingRules::
* instanceRanks), so the copy that works at less is also the one that pays more;
* a new instance comes after all of them.
*/
public function instanceIndex(string $type, ?Building $building = null): int
{
if (! $building) {
return $this->instances($type);
}
if (! $this->frozen || $this->indexes === null) {
$this->indexes = $this->rules->instanceRanks($this->states());
}
return $this->indexes[$building->id] ?? 0;
}
/** Level after everything already queued for this instance; 0 if it is being removed. */
public function queuedLevel(Building $building): int
{
return $this->village->orders->where('building_id', $building->id)->last()?->target_level ?? $building->level;
}
/** Building space taken by buildings and by new buildings in the queue. */
public function spaceUsed(): int
{
return $this->rules->spaceUsed([
...$this->village->buildings->pluck('type'),
...$this->village->orders->where('action', BuildOrder::BUILD)->pluck('type'),
]);
}
/**
* The village's building space, from its headquarters level. A queued demolition of
* the headquarters counts already, so nothing can be queued into space that goes away.
*/
public function spaceMax(): int
{
$hq = $this->village->buildings->firstWhere('type', 'headquarters');
$level = $hq ? min($hq->level, $this->queuedLevel($hq)) : 0;
return $this->rules->spaceMax($this->village->space, $level);
}
public function spaceFits(string $type): bool
{
return $this->spaceUsed() + $this->rules->space($type) <= $this->spaceMax();
}
/**
* Workers the queued orders add when they finish: every new instance and upgrade
* reserves its extra workers, the way a new instance reserves its space. A demolition
* frees its workers when it finishes.
*/
public function reservedWorkers(): int
{
return (int) $this->village->orders
->where('action', '!=', BuildOrder::DEMOLISH)
->sum(fn (BuildOrder $o) => $this->rules->extraWorkers($o->type, $o->target_level));
}
/** Villagers free for a new building level: not drafted, not working, not reserved by the queue. */
public function idleVillagers(): int
{
return $this->workforce()->idle($this->reservedWorkers());
}
/** Whether enough idle villagers stand ready for the workers this level adds (farms always). */
public function villagersFit(string $type, int $level): bool
{
return $this->rules->extraWorkers($type, $level) <= $this->idleVillagers();
}
/** The headquarters, and the last storage or farm, never go below level 1. */
public function isCore(Building $building): bool
{
if ($building->type === 'headquarters') {
return true;
}
return in_array($building->type, $this->config->get('world.village.start_buildings', []), true)
&& $this->village->buildings->where('type', $building->type)->count() === 1;
}
public function meetsRequirements(string $type): bool
{
return $this->missingRequirements($type) === [];
}
/**
* Requirements of a type that no building in the village meets yet.
*
* @return list<array{type: string, level: int}>
*/
public function missingRequirements(string $type): array
{
$missing = [];
foreach ($this->rules->requires($type) as $needed => $level) {
if (! $this->village->buildings->where('type', $needed)->where('level', '>=', $level)->count()) {
$missing[] = ['type' => $needed, 'level' => $level];
}
}
return $missing;
}
/** @return array{target_level: int, cost: array<string, int>, seconds: int, villagers: int, blocked: 'villagers'|null}|null */
public function upgradeOffer(Building $building): ?array
{
$current = $this->queuedLevel($building);
if ($current < 1 || $current >= $this->rules->maxLevel($building->type)) {
return null;
}
$target = $current + 1;
return [
'target_level' => $target,
'cost' => $this->rules->cost($building->type, $target, $this->instanceIndex($building->type, $building)),
'seconds' => $this->rules->buildSeconds($building->type, $target, $this->hqLevel(), $this->hqStaffing()),
// Idle villagers the level needs as extra workers, 0 for farms.
'villagers' => $this->rules->extraWorkers($building->type, $target),
'blocked' => $this->villagersFit($building->type, $target) ? null : 'villagers',
];
}
/** @return array{target_level: int, refund: array<string, int>, seconds: int}|null */
public function demolishOffer(Building $building): ?array
{
$current = $this->queuedLevel($building);
if ($current < 1 || ($current === 1 && $this->isCore($building))) {
return null;
}
return [
'target_level' => $current - 1,
'refund' => $this->rules->demolishRefund($building->type, $current, $this->instanceIndex($building->type, $building)),
'seconds' => $this->rules->demolishSeconds($building->type, $current, $this->hqLevel(), $this->hqStaffing()),
];
}
/** New instances the player could queue, with why not where they can't. */
public function buildOptions(): array
{
return array_map(function (string $type) {
$max = $this->rules->maxPerVillage($type);
$blocked = match (true) {
$max !== null && $this->instances($type) >= $max => 'max_per_village',
$this->missingRequirements($type) !== [] => 'requires',
! $this->spaceFits($type) => 'no_space',
! $this->villagersFit($type, 1) => 'villagers',
default => null,
};
return [
'type' => $type,
'space' => $this->rules->space($type),
'target_level' => 1,
'cost' => $this->rules->cost($type, 1, $this->instanceIndex($type)),
// A new instance ranks after all of its type, standing or queued.
'instance_share' => $this->rules->instanceShare($this->instances($type)),
'seconds' => $this->rules->buildSeconds($type, 1, $this->hqLevel(), $this->hqStaffing()),
// Idle villagers a new instance needs as workers, 0 for farms.
'villagers' => $this->rules->extraWorkers($type, 1),
'blocked' => $blocked,
// What is still missing, for the "not yet available" list.
'requires' => $this->missingRequirements($type),
];
}, $this->config->buildingTypes());
}
// Build queue
/** @param array<string, mixed> $attributes */
public function enqueue(array $attributes, CarbonImmutable $now): BuildOrder
{
$order = $this->village->orders()->create($attributes);
$this->village->orders->push($order);
$this->startWaitingOrders($now);
return $order;
}
/** Hand free builders their next orders, timed from $at, and schedule when they finish. */
public function startWaitingOrders(CarbonImmutable $at): void
{
$queue = $this->village->orders
->map(fn (BuildOrder $o) => ['id' => $o->id, 'building_id' => $o->building_id, 'builder' => $o->builder])
->values()->all();
foreach (BuildQueue::startable($queue, $this->builders()) as $orderId => $slot) {
$order = $this->village->orders->firstWhere('id', $orderId);
$finishes = $at->addSeconds($this->orderSeconds($order));
$order->update(['builder' => $slot, 'starts_at' => $at, 'finishes_at' => $finishes]);
GameEvent::create([
'world_id' => $this->village->world_id,
'village_id' => $this->village->id,
'type' => GameEvent::BUILD_ORDER_FINISHED,
'subject_id' => $order->id,
'fire_at' => $finishes,
]);
}
}
private function orderSeconds(BuildOrder $order): int
{
return $order->action === BuildOrder::DEMOLISH
? $this->rules->demolishSeconds($order->type, $order->target_level + 1, $this->hqLevel(), $this->hqStaffing())
: $this->rules->buildSeconds($order->type, $order->target_level, $this->hqLevel(), $this->hqStaffing());
}
/**
* Apply a finished order, drop it from the queue and recount the village's points. A
* level reached for the first time leaves a level reward for the player.
*/
public function finish(BuildOrder $order, CarbonImmutable $at): void
{
$this->applyFinished($order);
$this->village->points = $this->points();
if ($order->action !== BuildOrder::DEMOLISH) {
Quests::reached($this->village, $order->type, $order->target_level, $order->cost, $at);
}
}
/** Points shown on the map: the sum over buildings of their level's points. */
public function points(): int
{
return $this->village->buildings->sum(fn (Building $b) => $this->rules->points($b->type, $b->level));
}
private function applyFinished(BuildOrder $order): void
{
$this->removeOrder($order);
if ($order->action === BuildOrder::BUILD) {
$building = $this->village->buildings()->create(['type' => $order->type, 'level' => 1]);
$this->village->buildings->push($building->refresh());
return;
}
$building = $this->village->buildings->firstWhere('id', $order->building_id);
if (! $building) {
return;
}
if ($order->action === BuildOrder::DEMOLISH) {
$this->refund($this->rules->demolishRefund($building->type, $building->level, $this->instanceIndex($building->type, $building)));
}
$building->level = $order->target_level;
if ($building->level < 1) {
// Units still in training there go back to being villagers, with a refund.
foreach ($this->village->recruits->where('building_id', $building->id) as $order) {
$this->refund(array_map(fn (int $n) => $n * ($order->count - $order->done), $order->cost));
GameEvent::where('type', GameEvent::RECRUIT_FINISHED)->where('subject_id', $order->id)->whereNull('processed_at')->delete();
}
$this->village->setRelation('recruits', $this->village->recruits->reject(fn (RecruitOrder $o) => $o->building_id === $building->id)->values());
$building->delete();
$this->village->setRelation('buildings', $this->village->buildings->reject(fn (Building $b) => $b->is($building))->values());
} else {
$building->save();
}
}
/** Cancel an order with a full refund, plus later orders on the same instance that build on it. */
public function cancel(BuildOrder $order): void
{
$cancelled = $this->village->orders->filter(fn (BuildOrder $o) => $o->is($order)
|| ($order->building_id !== null && $o->building_id === $order->building_id && $o->id > $order->id));
foreach ($cancelled as $o) {
$this->refund($o->cost);
$this->removeOrder($o);
}
}
/** Drops the order and its pending finish event (the engine marks a running one processed first). */
private function removeOrder(BuildOrder $order): void
{
GameEvent::where('type', GameEvent::BUILD_ORDER_FINISHED)
->where('subject_id', $order->id)
->whereNull('processed_at')
->delete();
$order->delete();
$this->village->setRelation('orders', $this->village->orders->reject(fn (BuildOrder $o) => $o->is($order))->values());
}
}