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

120 lines
4.7 KiB
PHP

<?php
namespace App\Engine;
use App\Game\Map\MapBounds;
use App\Game\Map\Season;
use App\Models\Village;
use App\Models\World;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
use Throwable;
/**
* Worlds as seasons (architecture.md, "Seasons"). The game:events worker ticks every
* loop: crowns appear when they are due, and a holder who kept them long enough wins.
* A conquest of a crown recounts who holds them.
*/
final class Seasons
{
public const CROWN_NAME = 'Crown fort';
/** Place crowns and end worlds that are due by $now. */
public static function tick(CarbonImmutable $now): void
{
foreach (World::whereNull('ended_at')->get() as $world) {
try {
$season = new Season($world->gameConfig());
$crownsAt = $season->crownsAt($world->started_at);
if (! $world->crowns_placed_at && $season->count() > 0 && $crownsAt->lessThanOrEqualTo($now)) {
self::placeCrowns($world->id, $crownsAt);
}
$world->refresh();
if ($world->holder_player_id && $world->ends_at?->lessThanOrEqualTo($now)) {
self::end($world->id, $world->ends_at);
}
} catch (Throwable $e) {
// One broken world must not stop the others or the worker.
report($e);
}
}
}
/** The crown forts appear on their ring, each on the free field nearest its spot. */
public static function placeCrowns(int $worldId, CarbonImmutable $at): void
{
DB::transaction(function () use ($worldId, $at) {
$world = World::whereKey($worldId)->lockForUpdate()->first();
if (! $world || $world->crowns_placed_at) {
return;
}
$config = $world->gameConfig();
$taken = VillageFactory::takenSpots($world);
$bounds = MapBounds::of($config);
foreach ((new Season($config))->spots() as [$x, $y]) {
[$x, $y] = self::nearestFree($x, $y, $taken, $bounds);
$taken["$x|$y"] = false;
$crown = app(VillageFactory::class)->create($world, null, self::CROWN_NAME, $x, $y, $config->get('world.season.buildings', []));
$crown->update(['crown' => true]);
Barbarians::of($crown)->fill();
}
$world->update(['crowns_placed_at' => $at]);
});
}
/**
* After a crown changed hands: whoever holds more than half of them now starts the
* clock (ends_at), or the clock stops. $changed carries its new owner, not saved yet.
*/
public static function recount(Village $changed, CarbonImmutable $at): void
{
$world = World::whereKey($changed->world_id)->lockForUpdate()->first();
if (! $world || $world->ended_at) {
return;
}
$season = new Season($world->gameConfig());
$owners = Village::where('world_id', $world->id)->where('crown', true)->pluck('player_id', 'id');
$owners[$changed->id] = $changed->player_id;
$holder = $season->holder($owners->all());
if ($holder !== $world->holder_player_id) {
$world->update(['holder_player_id' => $holder, 'ends_at' => $holder ? $at->addSeconds($season->holdSeconds()) : null]);
}
}
/** The holder wins: the world ends at $at and the next one opens with the same rules. */
public static function end(int $worldId, CarbonImmutable $at): void
{
DB::transaction(function () use ($worldId, $at) {
$world = World::whereKey($worldId)->lockForUpdate()->first();
if (! $world || $world->ended_at || ! $world->holder_player_id) {
return;
}
$world->update(['ended_at' => $at, 'winner_player_id' => $world->holder_player_id]);
$slug = Season::next($world->slug);
while (World::where('slug', $slug)->exists()) {
$slug = Season::next($slug);
}
World::create(['slug' => $slug, 'name' => Season::next($world->name), 'config' => $world->config, 'started_at' => $at]);
});
}
/**
* @param array<string, bool> $taken
* @return array{0: int, 1: int}
*/
private static function nearestFree(int $x, int $y, array $taken, MapBounds $bounds): array
{
for ($r = 0; $r <= $bounds->max(); $r++) {
for ($dy = -$r; $dy <= $r; $dy++) {
for ($dx = -$r; $dx <= $r; $dx++) {
if (max(abs($dx), abs($dy)) === $r && ! isset($taken[($x + $dx).'|'.($y + $dy)]) && $bounds->contains($x + $dx, $y + $dy)) {
return [$x + $dx, $y + $dy];
}
}
}
}
return [$x, $y];
}
}