404 lines
15 KiB
PHP
404 lines
15 KiB
PHP
<?php
|
||
|
||
namespace App\Engine;
|
||
|
||
use App\Game\Buildings\BuildingRules;
|
||
use App\Game\Buildings\BuildingState;
|
||
use App\Game\Buildings\BuildQueue;
|
||
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 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);
|
||
}
|
||
|
||
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
|
||
{
|
||
return $this->population->workforce($this->states(), $this->soldierUpkeep());
|
||
}
|
||
|
||
/**
|
||
* 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);
|
||
}
|
||
|
||
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
|
||
{
|
||
$hq = $this->village->buildings->firstWhere('type', 'headquarters');
|
||
|
||
return $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);
|
||
}
|
||
|
||
return $this->village->buildings->where('type', $type)->where('id', '<', $building->id)->count();
|
||
}
|
||
|
||
/** Level after everything already queued for this instance; -1 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'),
|
||
]);
|
||
}
|
||
|
||
public function spaceFits(string $type): bool
|
||
{
|
||
return $this->spaceUsed() + $this->rules->space($type) <= $this->village->space;
|
||
}
|
||
|
||
/** The headquarters, and the last storage or farm, never go below level 0. */
|
||
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 < 0 || $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 < 0 || ($current === 0 && $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' => 0,
|
||
'cost' => $this->rules->cost($type, 0, $this->instanceIndex($type)),
|
||
'seconds' => $this->rules->buildSeconds($type, 0, $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. */
|
||
public function finish(BuildOrder $order): void
|
||
{
|
||
$this->applyFinished($order);
|
||
$this->village->points = $this->points();
|
||
}
|
||
|
||
/** 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' => 0]);
|
||
$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 < 0) {
|
||
// 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());
|
||
}
|
||
}
|