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

136 lines
4.6 KiB
PHP

<?php
namespace App\Engine;
use App\Game\Map\BarbarianGrowth;
use App\Models\GameEvent;
use App\Models\Village;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
/**
* Runs due game_events in (fire_at, id) order, one transaction per event with the
* village row locked. Reads and actions call catchUp() first, so a lagging worker
* never shows stale state; the game:events worker does the same for idle villages.
*/
final class Engine
{
/** Process this village's events due by $now. Returns how many ran. */
public function catchUp(int $villageId, CarbonImmutable $now): int
{
$count = 0;
while ($this->processNext($villageId, $now)) {
$count++;
}
return $count;
}
/** The village with the oldest due event, for the worker. */
public function nextDueVillage(CarbonImmutable $now): ?int
{
return GameEvent::whereNull('processed_at')
->where('fire_at', '<=', self::stamp($now))
->orderBy('fire_at')->orderBy('id')
->value('village_id');
}
public function nextFireAt(): ?CarbonImmutable
{
return GameEvent::whereNull('processed_at')->orderBy('fire_at')->first()?->fire_at;
}
/**
* Give up on an event that keeps failing, so one broken row can't stall the
* village forever. It stays in the table with attempts set, for a look later.
*/
public function recordFailure(int $villageId, CarbonImmutable $now, int $maxAttempts = 3): void
{
$event = $this->due($villageId, $now)->first();
if (! $event) {
return;
}
$event->increment('attempts');
if ($event->attempts >= $maxAttempts) {
$event->update(['processed_at' => $now]);
}
}
private function processNext(int $villageId, CarbonImmutable $now): bool
{
return DB::transaction(function () use ($villageId, $now) {
$village = Village::whereKey($villageId)->lockForUpdate()->first();
$event = $village ? $this->due($villageId, $now)->first() : null;
if (! $event) {
return false;
}
$event->update(['processed_at' => $now]);
$this->handle($village, $event);
$village->save();
return true;
});
}
private function due(int $villageId, CarbonImmutable $now)
{
return GameEvent::where('village_id', $villageId)
->whereNull('processed_at')
->where('fire_at', '<=', self::stamp($now))
->orderBy('fire_at')->orderBy('id');
}
private function handle(Village $village, GameEvent $event): void
{
match ($event->type) {
GameEvent::BUILD_ORDER_FINISHED => $this->finishBuildOrder($village, $event),
GameEvent::BARBARIAN_GROWS => $this->growBarbarian($village, $event),
GameEvent::RECRUIT_FINISHED => Military::of($village)->settle($event->fire_at),
GameEvent::LEVY_ENDS => Military::of($village)->endLevy($event->fire_at),
};
}
/** One building of a barbarian village goes up a level; the next step is scheduled. */
private function growBarbarian(Village $village, GameEvent $event): void
{
if ($village->player_id !== null) {
return;
}
$sim = Simulation::of($village);
$growth = new BarbarianGrowth($sim->config());
// Seeded per event, so a replayed event picks the same building.
mt_srand($event->id);
$state = $growth->pick($sim->states(), mt_rand() / (mt_getrandmax() + 1));
if (! $state) {
return;
}
$sim->settle($event->fire_at);
$village->buildings->firstWhere('id', $state->id)->increment('level');
$village->points = $sim->points();
GameEvent::create([
'world_id' => $village->world_id,
'village_id' => $village->id,
'type' => GameEvent::BARBARIAN_GROWS,
'fire_at' => $event->fire_at->addSeconds($growth->interval()),
]);
}
private function finishBuildOrder(Village $village, GameEvent $event): void
{
$sim = Simulation::of($village);
$order = $village->orders->firstWhere('id', $event->subject_id);
if (! $order) {
return;
}
$sim->settle($event->fire_at);
$sim->finish($order);
$sim->startWaitingOrders($event->fire_at);
}
/** Milliseconds matter: fire_at is datetime(3) and the default binding drops them. */
public static function stamp(CarbonImmutable $at): string
{
return $at->format('Y-m-d H:i:s.v');
}
}