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

136 lines
5.2 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Engine;
use App\Actions\SpawnBarbarians;
use App\Game\Map\BarbarianWaves;
use App\Models\Player;
use App\Models\World;
use Carbon\CarbonImmutable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;
use Throwable;
/**
* Barbarian waves (architecture.md, "Map"): every few world days new barbarian villages
* settle near the active players, so a world with few players keeps moving. Each world
* keeps its next wave in `barbarians_at`; the game:events worker ticks every loop.
*/
final class Waves
{
/**
* Start the timer of every open world that has none, and run each world's wave once
* it is due.
*/
public static function tick(CarbonImmutable $now): void
{
foreach (World::whereNull('ended_at')->get() as $world) {
try {
if (! (new BarbarianWaves($world->gameConfig()))->enabled()) {
continue;
}
if (! $world->barbarians_at) {
self::start($world, $now);
} elseif ($world->barbarians_at->lessThanOrEqualTo($now)) {
Push::villages(self::wave($world->id, $now));
}
} catch (Throwable $e) {
// One broken world must not stop the others or the worker.
report($e);
}
}
}
/** A world without a next wave gets one an interval after $from. */
public static function start(World $world, CarbonImmutable $from): void
{
$waves = new BarbarianWaves($world->gameConfig());
if (! $waves->enabled() || $world->ended_at || $world->barbarians_at) {
return;
}
$at = $from->addSeconds($waves->interval(self::draw($world->id, $from)));
World::whereKey($world->id)->whereNull('barbarians_at')->update(['barbarians_at' => Engine::stamp($at)]);
$world->barbarians_at = $at;
}
/**
* The world's due wave: per_player new barbarian villages for every active player,
* each near a random village of theirs, then the next wave an interval after this one.
* Seeded per world and wave, so a replay draws the same; the moved timer keeps a
* second run from spawning again.
*
* @return list<int> the player villages that got new neighbours, for the push
*/
public static function wave(int $worldId, CarbonImmutable $now): array
{
return DB::transaction(function () use ($worldId, $now) {
$world = World::whereKey($worldId)->lockForUpdate()->first();
$at = $world?->barbarians_at;
if (! $world || $world->ended_at || ! $at || $at->greaterThan($now)) {
return [];
}
$waves = new BarbarianWaves($world->gameConfig());
mt_srand(self::seed($world->id, $at));
try {
$next = $at->addSeconds($waves->interval(VillageFactory::random()));
$taken = VillageFactory::takenSpots($world);
$spawn = app(SpawnBarbarians::class);
$neighbours = [];
foreach (self::activePlayers($world, $at) as $player) {
$villages = $player->villages;
for ($n = $waves->perPlayer(VillageFactory::random()); $n > 0; $n--) {
$home = $villages[(int) floor(VillageFactory::random() * $villages->count())];
if ($spawn->near($world, $home, $taken, $waves->near())) {
$neighbours[$home->id] = true;
}
}
}
} finally {
// Back to an unpredictable stream for everything after the wave.
mt_srand();
}
// A worker that was down runs one wave, not every one it missed.
if ($next->lessThanOrEqualTo($now)) {
$next = $now->addSeconds($next->getTimestamp() - $at->getTimestamp());
}
$world->update(['barbarians_at' => $next]);
return array_keys($neighbours);
});
}
/**
* Players with a village who were seen within world.inactive_days (real days) before
* the wave, or every player with a village when that rule is off.
*
* @return Collection<int, Player>
*/
private static function activePlayers(World $world, CarbonImmutable $at): Collection
{
$days = (float) $world->gameConfig()->get('world.inactive_days', 0);
$players = Player::where('world_id', $world->id)->whereHas('villages')
->with(['villages' => fn ($q) => $q->orderBy('id')])->orderBy('id');
if ($days > 0) {
$players->where('last_active_at', '>=', Engine::stamp($at->subSeconds((int) round($days * 86400))));
}
return $players->get();
}
/** Uniform in [0, 1), the same for one world and moment every time. */
private static function draw(int $worldId, CarbonImmutable $at): float
{
mt_srand(self::seed($worldId, $at));
try {
return VillageFactory::random();
} finally {
mt_srand();
}
}
private static function seed(int $worldId, CarbonImmutable $at): int
{
return crc32("barbarian.wave|$worldId|{$at->getTimestamp()}");
}
}