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

495 lines
18 KiB
PHP
Raw 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 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;
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']));
}
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);
}
return implode('|', $parts);
}
/**
* Food per hour eaten by troops standing here and by units still in training: a
* queued unit takes its villager's place at once.
*/
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));
return $standing + $training;
}
/** @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));
}
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
{
return $this->village->buildings->sum(fn (Building $b) => $this->rules->capacity($b->type, $b->level));
}
/** 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 index among same-type instances; 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) {
if ($this->indexes === null) {
$this->indexes = [];
$seen = [];
foreach ($this->village->buildings->sortBy('id') as $b) {
$this->indexes[$b->id] = $seen[$b->type] = ($seen[$b->type] ?? -1) + 1;
}
}
return $this->indexes[$building->id] ?? 0;
}
return $this->village->buildings->where('type', $type)->where('id', '<', $building->id)->count();
}
/** 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();
}
/** 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, blocked: 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()),
'blocked' => null,
];
}
/** @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',
default => null,
};
return [
'type' => $type,
'space' => $this->rules->space($type),
'target_level' => 1,
'cost' => $this->rules->cost($type, 1, $this->instanceIndex($type)),
'seconds' => $this->rules->buildSeconds($type, 1, $this->hqLevel(), $this->hqStaffing()),
'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());
}
}