processNext($villageId, $now)) { $count++; } return $count; } /** * Catch up a village and the targets of its own groups that are due: their arrival * runs on the target's queue, so the owner never sees a group that should be back. */ public function catchUpAround(int $villageId, CarbonImmutable $now): void { $targets = Movement::where('origin_id', $villageId) ->whereIn('type', [Movement::ATTACK, Movement::SUPPORT]) ->where('arrives_at', '<=', self::stamp($now)) ->distinct()->pluck('target_id'); foreach ($targets as $target) { $this->catchUp($target, $now); } $this->catchUp($villageId, $now); } /** 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 { // Other villages an event touched (an attacker's home, a supporter) hear about it after the commit. try { return $this->processLocked($villageId, $now); } finally { Push::flush(); } } private function processLocked(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); Starvation::of($village)->sync($event->fire_at); $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::BARBARIAN_REGROUPS => Barbarians::of($village)->regroup($event->fire_at), GameEvent::RECRUIT_FINISHED => Military::of($village)->settle($event->fire_at), GameEvent::LEVY_ENDS => Military::of($village)->endLevy($event->fire_at), // The stock just hit 0; the sync() after every event starts the grace timer. GameEvent::FOOD_RUNS_OUT => null, GameEvent::DESERTION => Starvation::of($village)->wave($event->fire_at), GameEvent::MOVEMENT_ARRIVES => Rally::of($village)->arrive((int) $event->subject_id, $event->fire_at), // The target starts to see an incoming group; the worker's push is all it takes. GameEvent::MOVEMENT_SPOTTED => null, GameEvent::SUPPORT_RECALLED => Rally::of($village)->sendHome((int) $event->subject_id, $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(); // A bigger village fields a bigger garrison. Barbarians::of($village, $sim)->scheduleRegroup($event->fire_at); 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, $event->fire_at); $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'); } }