feat: data model, event engine and village actions with feature tests

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-28 19:17:34 +01:00
parent a8b3ea78d2
commit 301f718639
24 changed files with 1528 additions and 0 deletions

View File

@ -0,0 +1,23 @@
<?php
namespace App\Actions;
use App\Engine\Simulation;
use App\Game\GameRuleViolation;
use App\Models\User;
use App\Models\Village;
use Carbon\CarbonImmutable;
/** Cancel an order (and later ones on the same instance) with a full refund. */
final class CancelOrder extends VillageAction
{
public function __invoke(User $user, int $villageId, int $orderId): Village
{
return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($orderId) {
$order = $village->orders->firstWhere('id', $orderId)
?? throw new GameRuleViolation('not_found', 'Order not found.');
$sim->cancel($order);
$sim->startWaitingOrders($now);
});
}
}

83
app/Actions/JoinWorld.php Normal file
View File

@ -0,0 +1,83 @@
<?php
namespace App\Actions;
use App\Game\Buildings\BuildingRules;
use App\Game\Buildings\VillageGrid;
use App\Game\GameRuleViolation;
use App\Game\WorldConfig;
use App\Models\Player;
use App\Models\User;
use App\Models\Village;
use App\Models\World;
use Illuminate\Support\Facades\DB;
/** Join a world (or come back to it): a player and a start village with HQ, storage and farm at 0. */
final class JoinWorld
{
public function __invoke(User $user, int $worldId): Village
{
$world = World::find($worldId) ?? throw new GameRuleViolation('not_found', 'World not found.');
return DB::transaction(function () use ($user, $world) {
$player = Player::firstOrCreate(['user_id' => $user->id, 'world_id' => $world->id], ['name' => $user->name]);
if ($village = $player->villages()->orderBy('id')->first()) {
return $village;
}
$config = $world->gameConfig();
[$x, $y] = $this->spawnPoint($world, $config);
[$w, $h] = $config->get('world.village.grid');
$village = Village::create([
'world_id' => $world->id,
'player_id' => $player->id,
'name' => "{$user->name}'s village",
'x' => $x,
'y' => $y,
'grid_w' => $w,
'grid_h' => $h,
...$config->get('world.village.start_resources'),
'resources_at' => now()->toImmutable(),
]);
$rules = new BuildingRules($config);
$grid = new VillageGrid($w, $h);
foreach ($config->get('world.village.start_buildings') as $type) {
[$fw, $fh] = $rules->footprint($type);
$at = $grid->freeSlot($fw, $fh);
$grid->take($at['x'], $at['y'], $fw, $fh);
$village->buildings()->create(['type' => $type, 'level' => 0, 'x' => $at['x'], 'y' => $at['y']]);
}
return $village;
});
}
/**
* First free coordinate on rings around the map centre. Stand-in until M2's
* spawn ring that moves outward as the world fills.
*
* @return array{0: int, 1: int}
*/
private function spawnPoint(World $world, WorldConfig $config): array
{
$centre = intdiv($config->get('world.map.size', 1000), 2);
$taken = $world->villages()->get(['x', 'y'])->mapWithKeys(fn ($v) => ["{$v->x}|{$v->y}" => true])->all();
for ($r = 0; $r <= $centre; $r++) {
for ($dy = -$r; $dy <= $r; $dy++) {
for ($dx = -$r; $dx <= $r; $dx++) {
if (max(abs($dx), abs($dy)) !== $r) {
continue;
}
$x = $centre + $dx * 2;
$y = $centre + $dy * 2;
if (! isset($taken["$x|$y"])) {
return [$x, $y];
}
}
}
}
throw new GameRuleViolation('world_full', 'This world is full.');
}
}

View File

@ -0,0 +1,25 @@
<?php
namespace App\Actions;
use App\Models\Player;
use App\Models\User;
use App\Models\World;
final class ListWorlds
{
/** @return list<array{id: int, name: string, slug: string, speed: float, village_id: int|null}> */
public function __invoke(User $user): array
{
$villageIds = Player::where('user_id', $user->id)->with('villages:id,player_id')->get()
->mapWithKeys(fn (Player $p) => [$p->world_id => $p->villages->min('id')]);
return World::orderBy('id')->get()->map(fn (World $world) => [
'id' => $world->id,
'name' => $world->name,
'slug' => $world->slug,
'speed' => $world->gameConfig()->speed(),
'village_id' => $villageIds[$world->id] ?? null,
])->all();
}
}

View File

@ -0,0 +1,53 @@
<?php
namespace App\Actions;
use App\Engine\Simulation;
use App\Game\GameRuleViolation;
use App\Models\BuildOrder;
use App\Models\User;
use App\Models\Village;
use Carbon\CarbonImmutable;
/** Queue a new instance at level 0, at (x, y) or the first free slot. Pays up front. */
final class QueueBuild extends VillageAction
{
public function __invoke(User $user, int $villageId, string $type, ?int $x = null, ?int $y = null): Village
{
return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($type, $x, $y) {
if (! $sim->config()->hasBuilding($type)) {
throw new GameRuleViolation('not_found', "Unknown building type [$type].");
}
$rules = $sim->rules();
$max = $rules->maxPerVillage($type);
if ($max !== null && $sim->instances($type) >= $max) {
throw new GameRuleViolation('max_per_village', 'Only one of these per village.');
}
if (! $sim->meetsRequirements($type)) {
throw new GameRuleViolation('requires', 'Requirements not met.');
}
[$w, $h] = $rules->footprint($type);
$grid = $sim->grid();
if ($w === 0 || $h === 0) {
$at = ['x' => 0, 'y' => 0];
} elseif ($x !== null && $y !== null) {
$at = $grid->fits($w, $h, $x, $y) ? ['x' => $x, 'y' => $y] : throw new GameRuleViolation('no_space', 'That spot is taken.');
} else {
$at = $grid->freeSlot($w, $h) ?? throw new GameRuleViolation('no_space', 'No free space.');
}
$cost = $rules->cost($type, 0, $sim->instanceIndex($type));
$sim->pay($cost);
$sim->enqueue([
'building_id' => null,
'type' => $type,
'action' => BuildOrder::BUILD,
'target_level' => 0,
'x' => $at['x'],
'y' => $at['y'],
'cost' => $cost,
], $now);
});
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace App\Actions;
use App\Engine\Simulation;
use App\Game\GameRuleViolation;
use App\Models\BuildOrder;
use App\Models\User;
use App\Models\Village;
use Carbon\CarbonImmutable;
/** Queue taking an instance down one level; below 0 it is removed. Refunds on finish. */
final class QueueDemolish extends VillageAction
{
public function __invoke(User $user, int $villageId, int $buildingId): Village
{
return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($buildingId) {
$building = $this->building($village, $buildingId);
$offer = $sim->demolishOffer($building)
?? throw new GameRuleViolation('core_building', 'Core buildings cannot go below level 0.');
$sim->enqueue([
'building_id' => $building->id,
'type' => $building->type,
'action' => BuildOrder::DEMOLISH,
'target_level' => $offer['target_level'],
'x' => $building->x,
'y' => $building->y,
'cost' => ['wood' => 0, 'clay' => 0, 'iron' => 0],
], $now);
});
}
}

View File

@ -0,0 +1,32 @@
<?php
namespace App\Actions;
use App\Engine\Simulation;
use App\Game\GameRuleViolation;
use App\Models\BuildOrder;
use App\Models\User;
use App\Models\Village;
use Carbon\CarbonImmutable;
/** Queue the next level after whatever is already queued for this instance. */
final class QueueUpgrade extends VillageAction
{
public function __invoke(User $user, int $villageId, int $buildingId): Village
{
return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($buildingId) {
$building = $this->building($village, $buildingId);
$offer = $sim->upgradeOffer($building) ?? throw new GameRuleViolation('max_level', 'Already at max level.');
$sim->pay($offer['cost']);
$sim->enqueue([
'building_id' => $building->id,
'type' => $building->type,
'action' => BuildOrder::UPGRADE,
'target_level' => $offer['target_level'],
'x' => $building->x,
'y' => $building->y,
'cost' => $offer['cost'],
], $now);
});
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace App\Actions;
use App\Engine\Simulation;
use App\Models\User;
use App\Models\Village;
use Carbon\CarbonImmutable;
/** Workers go to higher priorities first (0..9). Settled first, since rates change. */
final class SetPriority extends VillageAction
{
public function __invoke(User $user, int $villageId, int $buildingId, int $priority): Village
{
return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($buildingId, $priority) {
$building = $this->building($village, $buildingId);
$building->update(['priority' => max(0, min(9, $priority))]);
});
}
}

View File

@ -0,0 +1,22 @@
<?php
namespace App\Actions;
use App\Game\GameRuleViolation;
use App\Models\User;
use App\Models\Village;
final class ShowVillage extends VillageAction
{
public function __invoke(User $user, int $villageId): Village
{
$this->engine->catchUp($villageId, now()->toImmutable());
$village = Village::with('player')->find($villageId);
if (! $village || $village->player?->user_id !== $user->id) {
throw new GameRuleViolation('not_found', 'Village not found.');
}
return $village;
}
}

View File

@ -0,0 +1,45 @@
<?php
namespace App\Actions;
use App\Engine\Engine;
use App\Engine\Simulation;
use App\Game\GameRuleViolation;
use App\Models\Building;
use App\Models\User;
use App\Models\Village;
use Carbon\CarbonImmutable;
use Closure;
use Illuminate\Support\Facades\DB;
/** Shared path of every village mutation: catch up, lock, settle to now, change, save. */
abstract class VillageAction
{
public function __construct(protected readonly Engine $engine) {}
/** @param Closure(Simulation, Village, CarbonImmutable): void $change */
protected function mutate(User $user, int $villageId, Closure $change): Village
{
$now = now()->toImmutable();
$this->engine->catchUp($villageId, $now);
return DB::transaction(function () use ($user, $villageId, $change, $now) {
$village = Village::whereKey($villageId)->lockForUpdate()->first();
if (! $village || $village->player?->user_id !== $user->id) {
throw new GameRuleViolation('not_found', 'Village not found.');
}
$sim = Simulation::of($village);
$sim->settle($now);
$change($sim, $village, $now);
$village->save();
return $village;
});
}
protected function building(Village $village, int $buildingId): Building
{
return $village->buildings->firstWhere('id', $buildingId)
?? throw new GameRuleViolation('not_found', 'Building not found.');
}
}

View File

@ -0,0 +1,58 @@
<?php
namespace App\Console\Commands;
use App\Engine\Engine;
use App\Models\Village;
use BlaxSoftware\LaravelWebSockets\Services\WebsocketService;
use Illuminate\Console\Command;
use Throwable;
/**
* The game:events worker: runs due events village by village and tells the
* owner's open sockets to refetch. Runs under supervisor next to the WS server,
* whose local broadcast socket it pushes through.
*/
class ProcessGameEvents extends Command
{
protected $signature = 'game:events {--once : Process what is due now and exit}';
protected $description = 'Process due game events and push village:updated to the owners';
public function handle(Engine $engine): int
{
do {
$now = now()->toImmutable();
while ($villageId = $engine->nextDueVillage($now)) {
try {
$engine->catchUp($villageId, $now);
} catch (Throwable $e) {
report($e);
$engine->recordFailure($villageId, $now);
}
$this->push($villageId);
}
if ($this->option('once')) {
return self::SUCCESS;
}
// Sleep until the next event, at most a second, so new events are picked up.
$next = $engine->nextFireAt();
$wait = $next ? ($next->getTimestampMs() - now()->getTimestampMs()) / 1000 : 1.0;
usleep((int) (max(0.05, min(1.0, $wait)) * 1_000_000));
} while (true);
}
private function push(int $villageId): void
{
if (! ws_available()) {
return;
}
$userId = Village::with('player')->find($villageId)?->player?->user_id;
$sockets = $userId ? WebsocketService::getUserSocketIds($userId) : [];
if ($sockets) {
ws_whisper('village:updated', ['village_id' => $villageId], $sockets);
}
}
}

106
app/Engine/Engine.php Normal file
View File

@ -0,0 +1,106 @@
<?php
namespace App\Engine;
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),
};
}
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');
}
}

365
app/Engine/Simulation.php Normal file
View File

@ -0,0 +1,365 @@
<?php
namespace App\Engine;
use App\Game\Buildings\BuildingRules;
use App\Game\Buildings\BuildingState;
use App\Game\Buildings\BuildQueue;
use App\Game\Buildings\VillageGrid;
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\WorldConfig;
use App\Models\Building;
use App\Models\BuildOrder;
use App\Models\GameEvent;
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']));
}
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());
}
/** @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;
}
/** Cells taken by buildings and by new buildings in the queue. */
public function grid(): VillageGrid
{
$rect = function (string $type, int $x, int $y) {
[$w, $h] = $this->rules->footprint($type);
return ['x' => $x, 'y' => $y, 'w' => $w, 'h' => $h];
};
$rects = $this->village->buildings->map(fn (Building $b) => $rect($b->type, $b->x, $b->y))
->merge($this->village->orders->where('action', BuildOrder::BUILD)->map(fn (BuildOrder $o) => $rect($o->type, $o->x, $o->y)));
return VillageGrid::with($this->village->grid_w, $this->village->grid_h, $rects);
}
/** 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
{
foreach ($this->rules->requires($type) as $needed => $level) {
if (! $this->village->buildings->where('type', $needed)->where('level', '>=', $level)->count()) {
return false;
}
}
return true;
}
/** @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
{
$grid = $this->grid();
return array_map(function (string $type) use ($grid) {
$max = $this->rules->maxPerVillage($type);
[$w, $h] = $this->rules->footprint($type);
$blocked = match (true) {
$max !== null && $this->instances($type) >= $max => 'max_per_village',
! $this->meetsRequirements($type) => 'requires',
$grid->freeSlot($w, $h) === null => 'no_space',
default => null,
};
return [
'type' => $type,
'footprint' => [$w, $h],
'target_level' => 0,
'cost' => $this->rules->cost($type, 0, $this->instanceIndex($type)),
'seconds' => $this->rules->buildSeconds($type, 0, $this->hqLevel(), $this->hqStaffing()),
'blocked' => $blocked,
];
}, $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 and drop it from the queue. */
public function finish(BuildOrder $order): void
{
$this->removeOrder($order);
if ($order->action === BuildOrder::BUILD) {
$building = $this->village->buildings()->create([
'type' => $order->type,
'level' => 0,
'x' => $order->x,
'y' => $order->y,
]);
$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) {
$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());
}
}

42
app/Models/BuildOrder.php Normal file
View File

@ -0,0 +1,42 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class BuildOrder extends Model
{
public const BUILD = 'build';
public const UPGRADE = 'upgrade';
public const DEMOLISH = 'demolish';
protected $guarded = [];
protected $dateFormat = 'Y-m-d H:i:s.v';
protected function casts(): array
{
return [
'cost' => 'array',
'target_level' => 'integer',
'x' => 'integer',
'y' => 'integer',
'builder' => 'integer',
'starts_at' => 'immutable_datetime',
'finishes_at' => 'immutable_datetime',
];
}
public function village(): BelongsTo
{
return $this->belongsTo(Village::class);
}
public function building(): BelongsTo
{
return $this->belongsTo(Building::class);
}
}

27
app/Models/Building.php Normal file
View File

@ -0,0 +1,27 @@
<?php
namespace App\Models;
use App\Game\Buildings\BuildingState;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Building extends Model
{
protected $guarded = [];
protected function casts(): array
{
return ['level' => 'integer', 'priority' => 'integer', 'x' => 'integer', 'y' => 'integer'];
}
public function village(): BelongsTo
{
return $this->belongsTo(Village::class);
}
public function state(): BuildingState
{
return new BuildingState($this->id, $this->type, $this->level, $this->priority, $this->x, $this->y);
}
}

29
app/Models/GameEvent.php Normal file
View File

@ -0,0 +1,29 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/** A timed effect. The engine runs due events in (fire_at, id) order. */
class GameEvent extends Model
{
public const BUILD_ORDER_FINISHED = 'build_order.finished';
protected $guarded = [];
protected $dateFormat = 'Y-m-d H:i:s.v';
protected function casts(): array
{
return [
'fire_at' => 'immutable_datetime',
'processed_at' => 'immutable_datetime',
];
}
public function village(): BelongsTo
{
return $this->belongsTo(Village::class);
}
}

27
app/Models/Player.php Normal file
View File

@ -0,0 +1,27 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Player extends Model
{
protected $guarded = [];
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function world(): BelongsTo
{
return $this->belongsTo(World::class);
}
public function villages(): HasMany
{
return $this->hasMany(Village::class);
}
}

53
app/Models/Village.php Normal file
View File

@ -0,0 +1,53 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
class Village extends Model
{
protected $guarded = [];
// resources_at keeps milliseconds, so ordering with events is exact.
protected $dateFormat = 'Y-m-d H:i:s.v';
protected function casts(): array
{
return [
'wood' => 'float',
'clay' => 'float',
'iron' => 'float',
'food' => 'float',
'resources_at' => 'immutable_datetime',
];
}
public function world(): BelongsTo
{
return $this->belongsTo(World::class);
}
public function player(): BelongsTo
{
return $this->belongsTo(Player::class);
}
public function buildings(): HasMany
{
return $this->hasMany(Building::class)->orderBy('id');
}
/** In queue order. */
public function orders(): HasMany
{
return $this->hasMany(BuildOrder::class)->orderBy('id');
}
/** @return array{wood: float, clay: float, iron: float, food: float} */
public function resources(): array
{
return ['wood' => $this->wood, 'clay' => $this->clay, 'iron' => $this->iron, 'food' => $this->food];
}
}

41
app/Models/World.php Normal file
View File

@ -0,0 +1,41 @@
<?php
namespace App\Models;
use App\Game\WorldConfig;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class World extends Model
{
protected $guarded = [];
protected function casts(): array
{
return [
'config' => 'array',
'started_at' => 'immutable_datetime',
'ends_at' => 'immutable_datetime',
];
}
/** The config/game/* defaults with this world's overrides on top. */
public function gameConfig(): WorldConfig
{
return WorldConfig::make([
'world' => config('game.world'),
'economy' => config('game.economy'),
'buildings' => config('game.buildings'),
], $this->config ?? []);
}
public function players(): HasMany
{
return $this->hasMany(Player::class);
}
public function villages(): HasMany
{
return $this->hasMany(Village::class);
}
}

View File

@ -0,0 +1,85 @@
<?php
namespace App\Presenters;
use App\Engine\Simulation;
use App\Models\Building;
use App\Models\BuildOrder;
use App\Models\Village;
use Carbon\CarbonImmutable;
/**
* The `village.show` payload (VillageState in the client's app/types/game.ts).
* Every number is computed here; the client only projects resources and countdowns.
*/
final class VillagePresenter
{
public static function present(Village $village, CarbonImmutable $now): array
{
$sim = Simulation::of($village);
$sim->settle($now);
$workforce = $sim->workforce();
$rules = $sim->rules();
$position = 0;
return [
'id' => $village->id,
'name' => $village->name,
'x' => $village->x,
'y' => $village->y,
'grid' => ['w' => $village->grid_w, 'h' => $village->grid_h],
'resources' => array_map(fn (float $n) => round($n, 4), $village->resources()),
'resources_at' => self::iso($village->resources_at),
'rates' => array_map(fn (float $n) => round($n, 4), $sim->rates()),
'storage_cap' => round($sim->storageCap()),
'population' => [
'food_budget' => round($workforce->foodBudget, 2),
'upkeep' => round($workforce->upkeep, 2),
'villagers' => $workforce->villagers,
'workers' => $workforce->workers(),
'soldiers' => 0,
],
'builders' => $sim->builders(),
'buildings' => $village->buildings->map(function (Building $b) use ($sim, $workforce, $rules) {
$output = $sim->output($b, $workforce);
return [
'id' => $b->id,
'type' => $b->type,
'level' => $b->level,
'x' => $b->x,
'y' => $b->y,
'footprint' => $rules->footprint($b->type),
'priority' => $b->priority,
'workers' => ['assigned' => $workforce->assigned[$b->id] ?? 0, 'required' => $workforce->required[$b->id] ?? 0],
'staffing' => round($workforce->ratio($b->id), 4),
'production' => $output ? ['resource' => $output['resource'], 'per_hour' => round($output['per_hour'], 2)] : null,
'upgrade' => $sim->upgradeOffer($b),
'demolish' => $sim->demolishOffer($b),
];
})->values()->all(),
'queue' => $village->orders->map(fn (BuildOrder $o) => [
'id' => $o->id,
'building_id' => $o->building_id,
'type' => $o->type,
'action' => $o->action,
'target_level' => $o->target_level,
'x' => $o->x,
'y' => $o->y,
'footprint' => $rules->footprint($o->type),
'cost' => $o->cost,
'position' => ++$position,
'builder' => $o->builder,
'starts_at' => $o->starts_at ? self::iso($o->starts_at) : null,
'finishes_at' => $o->finishes_at ? self::iso($o->finishes_at) : null,
])->values()->all(),
'buildable' => $sim->buildOptions(),
'server_time' => self::iso($now),
];
}
private static function iso(CarbonImmutable $at): string
{
return $at->utc()->format('Y-m-d\TH:i:s.v\Z');
}
}

View File

@ -0,0 +1,107 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('worlds', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('slug')->unique();
// Overrides for config/game/*, e.g. {"world": {"speed": 100}}.
$table->json('config')->nullable();
$table->dateTime('started_at')->nullable();
$table->dateTime('ends_at')->nullable();
$table->timestamps();
});
Schema::create('players', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('world_id')->constrained()->cascadeOnDelete();
$table->string('name');
$table->unsignedInteger('points')->default(0);
$table->timestamps();
$table->unique(['user_id', 'world_id']);
});
Schema::create('villages', function (Blueprint $table) {
$table->id();
$table->foreignId('world_id')->constrained()->cascadeOnDelete();
// Null for barbarian villages.
$table->foreignId('player_id')->nullable()->constrained()->nullOnDelete();
$table->string('name');
$table->integer('x');
$table->integer('y');
$table->unsignedSmallInteger('grid_w');
$table->unsignedSmallInteger('grid_h');
// Stored at resources_at; the current value is stored + rate × elapsed.
$table->decimal('wood', 14, 4)->default(0);
$table->decimal('clay', 14, 4)->default(0);
$table->decimal('iron', 14, 4)->default(0);
$table->decimal('food', 14, 4)->default(0);
$table->dateTime('resources_at', 3);
$table->unsignedInteger('points')->default(0);
$table->timestamps();
$table->unique(['world_id', 'x', 'y']);
});
Schema::create('buildings', function (Blueprint $table) {
$table->id();
$table->foreignId('village_id')->constrained()->cascadeOnDelete();
$table->string('type', 32);
$table->smallInteger('level')->default(0);
$table->unsignedSmallInteger('x');
$table->unsignedSmallInteger('y');
$table->unsignedTinyInteger('priority')->default(5);
$table->timestamps();
});
Schema::create('build_orders', function (Blueprint $table) {
$table->id();
$table->foreignId('village_id')->constrained()->cascadeOnDelete();
// Null while the order builds a new instance.
$table->foreignId('building_id')->nullable()->constrained()->cascadeOnDelete();
$table->string('type', 32);
$table->string('action', 16);
// -1 removes the instance.
$table->smallInteger('target_level');
$table->unsignedSmallInteger('x');
$table->unsignedSmallInteger('y');
$table->json('cost');
$table->unsignedTinyInteger('builder')->nullable();
$table->dateTime('starts_at', 3)->nullable();
$table->dateTime('finishes_at', 3)->nullable();
$table->timestamps();
});
Schema::create('game_events', function (Blueprint $table) {
$table->id();
$table->foreignId('world_id')->constrained()->cascadeOnDelete();
// The village whose row is locked while the event runs.
$table->foreignId('village_id')->constrained()->cascadeOnDelete();
$table->string('type', 48);
$table->unsignedBigInteger('subject_id')->nullable();
$table->dateTime('fire_at', 3);
$table->dateTime('processed_at', 3)->nullable();
$table->unsignedSmallInteger('attempts')->default(0);
$table->timestamps();
$table->index(['processed_at', 'fire_at']);
$table->index(['village_id', 'processed_at', 'fire_at']);
});
}
public function down(): void
{
Schema::dropIfExists('game_events');
Schema::dropIfExists('build_orders');
Schema::dropIfExists('buildings');
Schema::dropIfExists('villages');
Schema::dropIfExists('players');
Schema::dropIfExists('worlds');
}
};

View File

@ -0,0 +1,13 @@
<?php
namespace Database\Seeders;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
public function run(): void
{
$this->call(WorldSeeder::class);
}
}

View File

@ -0,0 +1,20 @@
<?php
namespace Database\Seeders;
use App\Models\World;
use Illuminate\Database\Seeder;
/** The default world and a fast dev world. Safe to run on every deploy. */
class WorldSeeder extends Seeder
{
public function run(): void
{
World::firstOrCreate(['slug' => 'w1'], ['name' => 'World 1', 'started_at' => now()]);
World::firstOrCreate(['slug' => 'dev'], [
'name' => 'Dev world',
'config' => ['world' => ['speed' => 100]],
'started_at' => now(),
]);
}
}

View File

@ -0,0 +1,165 @@
<?php
use App\Actions\CancelOrder;
use App\Actions\QueueBuild;
use App\Actions\QueueDemolish;
use App\Actions\QueueUpgrade;
use App\Actions\SetPriority;
use App\Models\GameEvent;
use Carbon\CarbonImmutable;
use Illuminate\Support\Arr;
beforeEach(fn () => $this->travelTo(CarbonImmutable::parse('2026-10-28 12:00:00')));
it('settles resources by rate and elapsed time, up to the storage cap', function () {
$village = startVillage();
$this->travel(2)->hours();
expect(shown($village)['resources'])->toBe(['wood' => 510.0, 'clay' => 510.0, 'iron' => 510.0, 'food' => 300.0]);
$this->travel(200)->hours();
expect(shown($village)['resources']['wood'])->toBe(1000.0);
});
it('pays up front, builds at the first free slot and finishes on time', function () {
$village = startVillage();
app(QueueBuild::class)(owner($village), $village->id, 'timber_camp');
$state = shown($village);
expect($state['resources']['wood'])->toBe(450.0)
->and($state['queue'][0])->toMatchArray([
'type' => 'timber_camp', 'action' => 'build', 'x' => 7, 'y' => 0, 'builder' => 1,
'starts_at' => '2026-10-28T12:00:00.000Z', 'finishes_at' => '2026-10-28T12:01:30.000Z',
]);
$this->travel(89)->seconds();
expect(shown($village)['buildings'])->toHaveCount(3);
$this->travel(1)->seconds();
$state = shown($village);
expect($state['queue'])->toBe([])
->and(collect($state['buildings'])->firstWhere('type', 'timber_camp'))->toMatchArray(['level' => 0, 'x' => 7, 'y' => 0])
->and($state['rates']['wood'])->toBe(35.0);
});
it('builds at a chosen cell and refuses taken cells', function () {
$village = startVillage();
app(QueueBuild::class)(owner($village), $village->id, 'hiding_place', 9, 4);
expect(shown($village)['queue'][0])->toMatchArray(['x' => 9, 'y' => 4])
->and(rule(fn () => app(QueueBuild::class)(owner($village), $village->id, 'rally_point', 9, 4)))->toBe('no_space')
->and(rule(fn () => app(QueueBuild::class)(owner($village), $village->id, 'farm', 1, 1)))->toBe('no_space');
});
it('refuses a second headquarters, a wall without HQ 1 and what it cannot pay', function () {
$village = startVillage();
$village->update(['wood' => 10]);
expect(rule(fn () => app(QueueBuild::class)(owner($village), $village->id, 'headquarters')))->toBe('max_per_village')
->and(rule(fn () => app(QueueBuild::class)(owner($village), $village->id, 'wall')))->toBe('requires')
->and(rule(fn () => app(QueueBuild::class)(owner($village), $village->id, 'storage')))->toBe('resources');
});
it('makes a later instance of a type cost more', function () {
$village = startVillage();
$farms = collect(shown($village)['buildable'])->firstWhere('type', 'farm');
expect($farms['cost'])->toBe(['wood' => 68, 'clay' => 60, 'iron' => 45]);
});
it('keeps a third order waiting and starts it when a builder frees up', function () {
$village = startVillage();
$user = owner($village);
app(QueueBuild::class)($user, $village->id, 'timber_camp'); // 90 s
app(QueueBuild::class)($user, $village->id, 'hiding_place'); // 60 s
app(QueueBuild::class)($user, $village->id, 'rally_point'); // 60 s, waits
expect(collect(shown($village)['queue'])->pluck('builder')->all())->toBe([1, 2, null]);
// Caught up long after: the rally point started when the hiding place finished.
$this->travel(10)->minutes();
expect(shown($village)['queue'])->toBe([])
->and(GameEvent::where('type', GameEvent::BUILD_ORDER_FINISHED)->orderBy('id')->pluck('fire_at')->map->format('H:i:s')->all())
->toBe(['12:01:30', '12:01:00', '12:02:00']);
});
it('queues upgrades of one building one after another', function () {
$village = startVillage();
$hq = $village->buildings->firstWhere('type', 'headquarters');
app(QueueUpgrade::class)(owner($village), $village->id, $hq->id);
app(QueueUpgrade::class)(owner($village), $village->id, $hq->id);
$state = shown($village);
expect(collect($state['queue'])->map(fn (array $o) => Arr::only($o, ['target_level', 'builder']))->all())->toBe([
['target_level' => 1, 'builder' => 1],
['target_level' => 2, 'builder' => null],
])
->and(collect($state['buildings'])->firstWhere('type', 'headquarters')['upgrade']['target_level'])->toBe(3)
->and($state['resources']['wood'])->toBe(500.0 - 113 - 143);
// HQ 1 takes 144 s; HQ 2 then builds with HQ 1's speed-up: 172.8 / 1.05 → 165 s.
$this->travel(144 + 165)->seconds();
expect(collect(shown($village)['buildings'])->firstWhere('type', 'headquarters')['level'])->toBe(2);
});
it('cancels an order, the orders that build on it, and refunds them in full', function () {
$village = startVillage();
$hq = $village->buildings->firstWhere('type', 'headquarters');
app(QueueUpgrade::class)(owner($village), $village->id, $hq->id);
app(QueueUpgrade::class)(owner($village), $village->id, $hq->id);
$first = shown($village)['queue'][0]['id'];
app(CancelOrder::class)(owner($village), $village->id, $first);
$state = shown($village);
expect($state['queue'])->toBe([])
->and($state['resources']['wood'])->toBe(500.0)
->and(GameEvent::whereNull('processed_at')->count())->toBe(0);
});
it('demolishes with a refund on finish and removes a building below level 0', function () {
$village = startVillage();
app(QueueBuild::class)(owner($village), $village->id, 'timber_camp');
$this->travel(90)->seconds();
$camp = collect(shown($village)['buildings'])->firstWhere('type', 'timber_camp');
app(QueueDemolish::class)(owner($village), $village->id, $camp['id']);
expect(shown($village)['queue'][0])->toMatchArray(['action' => 'demolish', 'target_level' => -1]);
$woodBefore = shown($village)['resources']['wood'];
$this->travel(45)->seconds();
$state = shown($village);
expect(collect($state['buildings'])->firstWhere('type', 'timber_camp'))->toBeNull()
->and($state['resources']['wood'])->toEqualWithDelta($woodBefore + 25 + 35 * 45 / 3600, 0.01);
});
it('keeps core buildings at level 0', function () {
$village = startVillage();
$hq = $village->buildings->firstWhere('type', 'headquarters');
expect(collect(shown($village)['buildings'])->firstWhere('type', 'headquarters')['demolish'])->toBeNull()
->and(rule(fn () => app(QueueDemolish::class)(owner($village), $village->id, $hq->id)))->toBe('core_building');
});
it('moves workers to the buildings with the highest priority', function () {
// 30 villagers: the farm takes 2, the clay pit at priority 9 the other 28.
$village = startVillage();
$village->buildings()->create(['type' => 'timber_camp', 'level' => 30, 'x' => 7, 'y' => 0]);
$clay = $village->buildings()->create(['type' => 'clay_pit', 'level' => 30, 'x' => 0, 'y' => 3]);
app(SetPriority::class)(owner($village), $village->id, $clay->id, 12);
$buildings = collect(shown($village)['buildings'])->keyBy('type');
expect($buildings['clay_pit']['workers'])->toBe(['assigned' => 28, 'required' => 60])
->and($buildings['clay_pit']['priority'])->toBe(9)
->and($buildings['timber_camp']['workers']['assigned'])->toBe(0)
->and($buildings['farm']['workers']['assigned'])->toBe(2);
});
it('lets the worker finish orders of idle villages', function () {
$village = startVillage();
app(QueueBuild::class)(owner($village), $village->id, 'timber_camp');
$this->travel(2)->minutes();
$this->artisan('game:events --once')->assertSuccessful();
expect($village->buildings()->where('type', 'timber_camp')->exists())->toBeTrue()
->and(GameEvent::whereNull('processed_at')->count())->toBe(0);
});

View File

@ -0,0 +1,55 @@
<?php
use App\Actions\JoinWorld;
use App\Actions\ListWorlds;
use App\Actions\ShowVillage;
use App\Models\User;
use App\Models\World;
it('starts a village with HQ, storage and farm at level 0', function () {
$village = startVillage();
expect($village->only('x', 'y', 'grid_w', 'grid_h'))->toBe(['x' => 500, 'y' => 500, 'grid_w' => 10, 'grid_h' => 5])
->and($village->resources())->toBe(['wood' => 500.0, 'clay' => 500.0, 'iron' => 500.0, 'food' => 300.0])
->and($village->buildings->map->only('type', 'level', 'x', 'y')->all())->toBe([
['type' => 'headquarters', 'level' => 0, 'x' => 0, 'y' => 0],
['type' => 'storage', 'level' => 0, 'x' => 3, 'y' => 0],
['type' => 'farm', 'level' => 0, 'x' => 5, 'y' => 0],
]);
});
it('returns the same village when joining again', function () {
$village = startVillage();
expect(app(JoinWorld::class)(owner($village), $village->world_id)->id)->toBe($village->id);
});
it('spawns the next player on a free coordinate', function () {
$first = startVillage();
$second = startVillage(User::factory()->create());
expect([$second->x, $second->y])->not->toBe([$first->x, $first->y]);
});
it('lists worlds with their speed and the player village', function () {
$village = startVillage();
$dev = World::where('slug', 'dev')->first();
expect(app(ListWorlds::class)(owner($village)))->toBe([
['id' => $village->world_id, 'name' => 'World 1', 'slug' => 'w1', 'speed' => 1.0, 'village_id' => $village->id],
['id' => $dev->id, 'name' => 'Dev world', 'slug' => 'dev', 'speed' => 100.0, 'village_id' => null],
]);
});
it('shows a start village to its owner only', function () {
$village = startVillage();
$state = shown($village);
expect($state['rates'])->toBe(['wood' => 5.0, 'clay' => 5.0, 'iron' => 5.0, 'food' => 0.0])
->and($state['storage_cap'])->toEqual(1000)
->and($state['population'])->toEqual(['food_budget' => 30, 'upkeep' => 30, 'villagers' => 30, 'workers' => 5, 'soldiers' => 0])
->and($state['builders'])->toBe(2)
->and(collect($state['buildable'])->firstWhere('type', 'headquarters')['blocked'])->toBe('max_per_village')
->and(collect($state['buildable'])->firstWhere('type', 'wall')['blocked'])->toBe('requires')
->and(rule(fn () => app(ShowVillage::class)(User::factory()->create(), $village->id)))->toBe('not_found');
});