diff --git a/app/Actions/CancelOrder.php b/app/Actions/CancelOrder.php new file mode 100644 index 0000000..4afda95 --- /dev/null +++ b/app/Actions/CancelOrder.php @@ -0,0 +1,23 @@ +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); + }); + } +} diff --git a/app/Actions/JoinWorld.php b/app/Actions/JoinWorld.php new file mode 100644 index 0000000..3d0bd58 --- /dev/null +++ b/app/Actions/JoinWorld.php @@ -0,0 +1,83 @@ + $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.'); + } +} diff --git a/app/Actions/ListWorlds.php b/app/Actions/ListWorlds.php new file mode 100644 index 0000000..40840db --- /dev/null +++ b/app/Actions/ListWorlds.php @@ -0,0 +1,25 @@ + */ + 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(); + } +} diff --git a/app/Actions/QueueBuild.php b/app/Actions/QueueBuild.php new file mode 100644 index 0000000..b9df76e --- /dev/null +++ b/app/Actions/QueueBuild.php @@ -0,0 +1,53 @@ +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); + }); + } +} diff --git a/app/Actions/QueueDemolish.php b/app/Actions/QueueDemolish.php new file mode 100644 index 0000000..c124b15 --- /dev/null +++ b/app/Actions/QueueDemolish.php @@ -0,0 +1,32 @@ +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); + }); + } +} diff --git a/app/Actions/QueueUpgrade.php b/app/Actions/QueueUpgrade.php new file mode 100644 index 0000000..4cebaa0 --- /dev/null +++ b/app/Actions/QueueUpgrade.php @@ -0,0 +1,32 @@ +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); + }); + } +} diff --git a/app/Actions/SetPriority.php b/app/Actions/SetPriority.php new file mode 100644 index 0000000..fe76015 --- /dev/null +++ b/app/Actions/SetPriority.php @@ -0,0 +1,20 @@ +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))]); + }); + } +} diff --git a/app/Actions/ShowVillage.php b/app/Actions/ShowVillage.php new file mode 100644 index 0000000..d13845a --- /dev/null +++ b/app/Actions/ShowVillage.php @@ -0,0 +1,22 @@ +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; + } +} diff --git a/app/Actions/VillageAction.php b/app/Actions/VillageAction.php new file mode 100644 index 0000000..d002b54 --- /dev/null +++ b/app/Actions/VillageAction.php @@ -0,0 +1,45 @@ +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.'); + } +} diff --git a/app/Console/Commands/ProcessGameEvents.php b/app/Console/Commands/ProcessGameEvents.php new file mode 100644 index 0000000..db77a97 --- /dev/null +++ b/app/Console/Commands/ProcessGameEvents.php @@ -0,0 +1,58 @@ +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); + } + } +} diff --git a/app/Engine/Engine.php b/app/Engine/Engine.php new file mode 100644 index 0000000..98aaee3 --- /dev/null +++ b/app/Engine/Engine.php @@ -0,0 +1,106 @@ +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'); + } +} diff --git a/app/Engine/Simulation.php b/app/Engine/Simulation.php new file mode 100644 index 0000000..c5c7ded --- /dev/null +++ b/app/Engine/Simulation.php @@ -0,0 +1,365 @@ +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 */ + 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 $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, 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, 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 $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()); + } +} diff --git a/app/Models/BuildOrder.php b/app/Models/BuildOrder.php new file mode 100644 index 0000000..11a8897 --- /dev/null +++ b/app/Models/BuildOrder.php @@ -0,0 +1,42 @@ + '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); + } +} diff --git a/app/Models/Building.php b/app/Models/Building.php new file mode 100644 index 0000000..5d75c0f --- /dev/null +++ b/app/Models/Building.php @@ -0,0 +1,27 @@ + '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); + } +} diff --git a/app/Models/GameEvent.php b/app/Models/GameEvent.php new file mode 100644 index 0000000..f77f2e8 --- /dev/null +++ b/app/Models/GameEvent.php @@ -0,0 +1,29 @@ + 'immutable_datetime', + 'processed_at' => 'immutable_datetime', + ]; + } + + public function village(): BelongsTo + { + return $this->belongsTo(Village::class); + } +} diff --git a/app/Models/Player.php b/app/Models/Player.php new file mode 100644 index 0000000..fd81d63 --- /dev/null +++ b/app/Models/Player.php @@ -0,0 +1,27 @@ +belongsTo(User::class); + } + + public function world(): BelongsTo + { + return $this->belongsTo(World::class); + } + + public function villages(): HasMany + { + return $this->hasMany(Village::class); + } +} diff --git a/app/Models/Village.php b/app/Models/Village.php new file mode 100644 index 0000000..aa38133 --- /dev/null +++ b/app/Models/Village.php @@ -0,0 +1,53 @@ + '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]; + } +} diff --git a/app/Models/World.php b/app/Models/World.php new file mode 100644 index 0000000..b248a17 --- /dev/null +++ b/app/Models/World.php @@ -0,0 +1,41 @@ + '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); + } +} diff --git a/app/Presenters/VillagePresenter.php b/app/Presenters/VillagePresenter.php new file mode 100644 index 0000000..aa2c2ea --- /dev/null +++ b/app/Presenters/VillagePresenter.php @@ -0,0 +1,85 @@ +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'); + } +} diff --git a/database/migrations/2026_10_28_200000_create_game_tables.php b/database/migrations/2026_10_28_200000_create_game_tables.php new file mode 100644 index 0000000..d038aa5 --- /dev/null +++ b/database/migrations/2026_10_28_200000_create_game_tables.php @@ -0,0 +1,107 @@ +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'); + } +}; diff --git a/database/seeders/DatabaseSeeder.php b/database/seeders/DatabaseSeeder.php new file mode 100644 index 0000000..512307b --- /dev/null +++ b/database/seeders/DatabaseSeeder.php @@ -0,0 +1,13 @@ +call(WorldSeeder::class); + } +} diff --git a/database/seeders/WorldSeeder.php b/database/seeders/WorldSeeder.php new file mode 100644 index 0000000..dd60459 --- /dev/null +++ b/database/seeders/WorldSeeder.php @@ -0,0 +1,20 @@ + 'w1'], ['name' => 'World 1', 'started_at' => now()]); + World::firstOrCreate(['slug' => 'dev'], [ + 'name' => 'Dev world', + 'config' => ['world' => ['speed' => 100]], + 'started_at' => now(), + ]); + } +} diff --git a/tests/Feature/BuildQueueTest.php b/tests/Feature/BuildQueueTest.php new file mode 100644 index 0000000..c28eed4 --- /dev/null +++ b/tests/Feature/BuildQueueTest.php @@ -0,0 +1,165 @@ + $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); +}); diff --git a/tests/Feature/JoinWorldTest.php b/tests/Feature/JoinWorldTest.php new file mode 100644 index 0000000..600300f --- /dev/null +++ b/tests/Feature/JoinWorldTest.php @@ -0,0 +1,55 @@ +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'); +});