refactor: building space instead of a tile grid, plus village points and continent

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-28 19:45:02 +01:00
parent bfefff1796
commit 34aa8acead
25 changed files with 337 additions and 285 deletions

View File

@ -2,10 +2,8 @@
namespace App\Actions; namespace App\Actions;
use App\Game\Buildings\BuildingRules; use App\Engine\VillageFactory;
use App\Game\Buildings\VillageGrid;
use App\Game\GameRuleViolation; use App\Game\GameRuleViolation;
use App\Game\WorldConfig;
use App\Models\Player; use App\Models\Player;
use App\Models\User; use App\Models\User;
use App\Models\Village; use App\Models\Village;
@ -15,6 +13,8 @@ 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. */ /** Join a world (or come back to it): a player and a start village with HQ, storage and farm at 0. */
final class JoinWorld final class JoinWorld
{ {
public function __construct(private readonly VillageFactory $villages) {}
public function __invoke(User $user, int $worldId): Village public function __invoke(User $user, int $worldId): Village
{ {
$world = World::find($worldId) ?? throw new GameRuleViolation('not_found', 'World not found.'); $world = World::find($worldId) ?? throw new GameRuleViolation('not_found', 'World not found.');
@ -25,59 +25,11 @@ final class JoinWorld
return $village; return $village;
} }
$config = $world->gameConfig(); $taken = VillageFactory::takenSpots($world);
[$x, $y] = $this->spawnPoint($world, $config); [$x, $y] = VillageFactory::freeSpot($world, $taken);
[$w, $h] = $config->get('world.village.grid'); $levels = array_fill_keys($world->gameConfig()->get('world.village.start_buildings'), 0);
$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); return $this->villages->create($world, $player, "{$user->name}'s village", $x, $y, $levels);
$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

@ -9,12 +9,12 @@ use App\Models\User;
use App\Models\Village; use App\Models\Village;
use Carbon\CarbonImmutable; use Carbon\CarbonImmutable;
/** Queue a new instance at level 0, at (x, y) or the first free slot. Pays up front. */ /** Queue a new instance at level 0 if its building space is free. Pays up front. */
final class QueueBuild extends VillageAction final class QueueBuild extends VillageAction
{ {
public function __invoke(User $user, int $villageId, string $type, ?int $x = null, ?int $y = null): Village public function __invoke(User $user, int $villageId, string $type): Village
{ {
return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($type, $x, $y) { return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($type) {
if (! $sim->config()->hasBuilding($type)) { if (! $sim->config()->hasBuilding($type)) {
throw new GameRuleViolation('not_found', "Unknown building type [$type]."); throw new GameRuleViolation('not_found', "Unknown building type [$type].");
} }
@ -26,15 +26,8 @@ final class QueueBuild extends VillageAction
if (! $sim->meetsRequirements($type)) { if (! $sim->meetsRequirements($type)) {
throw new GameRuleViolation('requires', 'Requirements not met.'); throw new GameRuleViolation('requires', 'Requirements not met.');
} }
if (! $sim->spaceFits($type)) {
[$w, $h] = $rules->footprint($type); throw new GameRuleViolation('no_space', 'Not enough building space.');
$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)); $cost = $rules->cost($type, 0, $sim->instanceIndex($type));
@ -44,8 +37,6 @@ final class QueueBuild extends VillageAction
'type' => $type, 'type' => $type,
'action' => BuildOrder::BUILD, 'action' => BuildOrder::BUILD,
'target_level' => 0, 'target_level' => 0,
'x' => $at['x'],
'y' => $at['y'],
'cost' => $cost, 'cost' => $cost,
], $now); ], $now);
}); });

View File

@ -23,8 +23,6 @@ final class QueueDemolish extends VillageAction
'type' => $building->type, 'type' => $building->type,
'action' => BuildOrder::DEMOLISH, 'action' => BuildOrder::DEMOLISH,
'target_level' => $offer['target_level'], 'target_level' => $offer['target_level'],
'x' => $building->x,
'y' => $building->y,
'cost' => ['wood' => 0, 'clay' => 0, 'iron' => 0], 'cost' => ['wood' => 0, 'clay' => 0, 'iron' => 0],
], $now); ], $now);
}); });

View File

@ -23,8 +23,6 @@ final class QueueUpgrade extends VillageAction
'type' => $building->type, 'type' => $building->type,
'action' => BuildOrder::UPGRADE, 'action' => BuildOrder::UPGRADE,
'target_level' => $offer['target_level'], 'target_level' => $offer['target_level'],
'x' => $building->x,
'y' => $building->y,
'cost' => $offer['cost'], 'cost' => $offer['cost'],
], $now); ], $now);
}); });

View File

@ -5,7 +5,6 @@ namespace App\Engine;
use App\Game\Buildings\BuildingRules; use App\Game\Buildings\BuildingRules;
use App\Game\Buildings\BuildingState; use App\Game\Buildings\BuildingState;
use App\Game\Buildings\BuildQueue; use App\Game\Buildings\BuildQueue;
use App\Game\Buildings\VillageGrid;
use App\Game\Economy\Population; use App\Game\Economy\Population;
use App\Game\Economy\Production; use App\Game\Economy\Production;
use App\Game\Economy\Settle; use App\Game\Economy\Settle;
@ -173,18 +172,18 @@ final class Simulation
return $this->village->orders->where('building_id', $building->id)->last()?->target_level ?? $building->level; 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. */ /** Building space taken by buildings and by new buildings in the queue. */
public function grid(): VillageGrid public function spaceUsed(): int
{ {
$rect = function (string $type, int $x, int $y) { return $this->rules->spaceUsed([
[$w, $h] = $this->rules->footprint($type); ...$this->village->buildings->pluck('type'),
...$this->village->orders->where('action', BuildOrder::BUILD)->pluck('type'),
]);
}
return ['x' => $x, 'y' => $y, 'w' => $w, 'h' => $h]; public function spaceFits(string $type): bool
}; {
$rects = $this->village->buildings->map(fn (Building $b) => $rect($b->type, $b->x, $b->y)) return $this->spaceUsed() + $this->rules->space($type) <= $this->village->space;
->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. */ /** The headquarters, and the last storage or farm, never go below level 0. */
@ -244,21 +243,18 @@ final class Simulation
/** New instances the player could queue, with why not where they can't. */ /** New instances the player could queue, with why not where they can't. */
public function buildOptions(): array public function buildOptions(): array
{ {
$grid = $this->grid(); return array_map(function (string $type) {
return array_map(function (string $type) use ($grid) {
$max = $this->rules->maxPerVillage($type); $max = $this->rules->maxPerVillage($type);
[$w, $h] = $this->rules->footprint($type);
$blocked = match (true) { $blocked = match (true) {
$max !== null && $this->instances($type) >= $max => 'max_per_village', $max !== null && $this->instances($type) >= $max => 'max_per_village',
! $this->meetsRequirements($type) => 'requires', ! $this->meetsRequirements($type) => 'requires',
$grid->freeSlot($w, $h) === null => 'no_space', ! $this->spaceFits($type) => 'no_space',
default => null, default => null,
}; };
return [ return [
'type' => $type, 'type' => $type,
'footprint' => [$w, $h], 'space' => $this->rules->space($type),
'target_level' => 0, 'target_level' => 0,
'cost' => $this->rules->cost($type, 0, $this->instanceIndex($type)), 'cost' => $this->rules->cost($type, 0, $this->instanceIndex($type)),
'seconds' => $this->rules->buildSeconds($type, 0, $this->hqLevel(), $this->hqStaffing()), 'seconds' => $this->rules->buildSeconds($type, 0, $this->hqLevel(), $this->hqStaffing()),
@ -307,18 +303,25 @@ final class Simulation
: $this->rules->buildSeconds($order->type, $order->target_level, $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. */ /** Apply a finished order, drop it from the queue and recount the village's points. */
public function finish(BuildOrder $order): void public function finish(BuildOrder $order): void
{
$this->applyFinished($order);
$this->village->points = $this->points();
}
/** Points shown on the map: the sum over buildings of their level's points. */
public function points(): int
{
return $this->village->buildings->sum(fn (Building $b) => $this->rules->points($b->type, $b->level));
}
private function applyFinished(BuildOrder $order): void
{ {
$this->removeOrder($order); $this->removeOrder($order);
if ($order->action === BuildOrder::BUILD) { if ($order->action === BuildOrder::BUILD) {
$building = $this->village->buildings()->create([ $building = $this->village->buildings()->create(['type' => $order->type, 'level' => 0]);
'type' => $order->type,
'level' => 0,
'x' => $order->x,
'y' => $order->y,
]);
$this->village->buildings->push($building->refresh()); $this->village->buildings->push($building->refresh());
return; return;

View File

@ -0,0 +1,77 @@
<?php
namespace App\Engine;
use App\Game\GameRuleViolation;
use App\Models\Player;
use App\Models\Village;
use App\Models\World;
/** Creates villages for players and barbarians, and finds free map coordinates for them. */
final class VillageFactory
{
/**
* A village with the given building levels (type => level, one instance each),
* start resources and the matching points.
*
* @param array<string, int> $levels
*/
public function create(World $world, ?Player $player, string $name, int $x, int $y, array $levels): Village
{
$config = $world->gameConfig();
$village = Village::create([
'world_id' => $world->id,
'player_id' => $player?->id,
'name' => $name,
'x' => $x,
'y' => $y,
'space' => $config->get('world.village.space'),
...$config->get('world.village.start_resources'),
'resources_at' => now()->toImmutable(),
]);
foreach ($levels as $type => $level) {
$village->buildings()->create(['type' => $type, 'level' => $level]);
}
$village->update(['points' => Simulation::of($village)->points()]);
return $village;
}
/**
* First free coordinate on square rings around the map centre, every second field
* so villages don't touch. Stand-in for M2's spawn ring that moves outward as the
* world fills.
*
* @param array<string, true> $taken "x|y" => true, updated with the result
* @return array{0: int, 1: int}
*/
public static function freeSpot(World $world, array &$taken): array
{
$size = $world->gameConfig()->get('world.map.size', 1000);
$centre = intdiv($size, 2);
for ($r = 0; $r <= $centre / 2; $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"])) {
$taken["$x|$y"] = true;
return [$x, $y];
}
}
}
}
throw new GameRuleViolation('world_full', 'This world is full.');
}
/** @return array<string, true> */
public static function takenSpots(World $world): array
{
return $world->villages()->get(['x', 'y'])->mapWithKeys(fn (Village $v) => ["{$v->x}|{$v->y}" => true])->all();
}
}

View File

@ -90,10 +90,33 @@ final class BuildingRules
return $capacity ? $capacity['base'] * $capacity['factor'] ** $level : 0.0; return $capacity ? $capacity['base'] * $capacity['factor'] ** $level : 0.0;
} }
/** @return array{0: int, 1: int} */ /** Points an instance at this level adds to its village. */
public function footprint(string $type): array public function points(string $type, int $level): int
{ {
return $this->config->building($type)['footprint']; $points = $this->config->building($type)['points'];
return (int) round($points['base'] * $points['factor'] ** $level);
}
/** Building space one instance takes, at every level. */
public function space(string $type): int
{
return $this->config->building($type)['space'];
}
/**
* Space taken by these building types together.
*
* @param iterable<string> $types one entry per instance
*/
public function spaceUsed(iterable $types): int
{
$used = 0;
foreach ($types as $type) {
$used += $this->space($type);
}
return $used;
} }
public function maxLevel(string $type): int public function maxLevel(string $type): int

View File

@ -10,7 +10,5 @@ final class BuildingState
public readonly string $type, public readonly string $type,
public readonly int $level, public readonly int $level,
public readonly int $priority = 5, public readonly int $priority = 5,
public readonly int $x = 0,
public readonly int $y = 0,
) {} ) {}
} }

View File

@ -1,78 +0,0 @@
<?php
namespace App\Game\Buildings;
/** The village's cells: bounds and overlap for building footprints. */
final class VillageGrid
{
/** @var array<string, true> */
private array $taken = [];
public function __construct(public readonly int $w, public readonly int $h) {}
/** @param iterable<array{x: int, y: int, w: int, h: int}> $rects */
public static function with(int $w, int $h, iterable $rects): self
{
$grid = new self($w, $h);
foreach ($rects as $r) {
$grid->take($r['x'], $r['y'], $r['w'], $r['h']);
}
return $grid;
}
public function take(int $x, int $y, int $w, int $h): void
{
foreach ($this->cells($x, $y, $w, $h) as $cell) {
$this->taken[$cell] = true;
}
}
/** A [0, 0] footprint (the wall) takes no cells and always fits. */
public function fits(int $w, int $h, int $x, int $y): bool
{
if ($w === 0 || $h === 0) {
return true;
}
if ($x < 0 || $y < 0 || $x + $w > $this->w || $y + $h > $this->h) {
return false;
}
foreach ($this->cells($x, $y, $w, $h) as $cell) {
if (isset($this->taken[$cell])) {
return false;
}
}
return true;
}
/** First free position scanning rows top to bottom, or null when it doesn't fit anywhere. */
public function freeSlot(int $w, int $h): ?array
{
if ($w === 0 || $h === 0) {
return ['x' => 0, 'y' => 0];
}
for ($y = 0; $y + $h <= $this->h; $y++) {
for ($x = 0; $x + $w <= $this->w; $x++) {
if ($this->fits($w, $h, $x, $y)) {
return ['x' => $x, 'y' => $y];
}
}
}
return null;
}
/** @return list<string> */
private function cells(int $x, int $y, int $w, int $h): array
{
$cells = [];
for ($dy = 0; $dy < $h; $dy++) {
for ($dx = 0; $dx < $w; $dx++) {
$cells[] = ($x + $dx).','.($y + $dy);
}
}
return $cells;
}
}

View File

@ -3,7 +3,6 @@
namespace App\Game; namespace App\Game;
use App\Game\Buildings\BuildingRules; use App\Game\Buildings\BuildingRules;
use App\Game\Buildings\VillageGrid;
/** /**
* Proves a world config has no locks (architecture.md, "No locks"). * Proves a world config has no locks (architecture.md, "No locks").
@ -24,26 +23,32 @@ final class ConfigLint
]; ];
} }
/** The start buildings must fit the default grid, and be allowed at all. */ /**
* The start buildings must exist and fit the building space together, and every
* type must fit next to them, or it could never be built.
*/
private static function startVillageFits(WorldConfig $config, BuildingRules $rules): array private static function startVillageFits(WorldConfig $config, BuildingRules $rules): array
{ {
[$w, $h] = $config->get('world.village.grid'); $max = $config->get('world.village.space');
$grid = new VillageGrid($w, $h); $start = $config->get('world.village.start_buildings', []);
$problems = []; $problems = [];
foreach ($config->get('world.village.start_buildings', []) as $type) { foreach ($start as $type) {
if (! $config->hasBuilding($type)) { if (! $config->hasBuilding($type)) {
$problems[] = "Start building [$type] is not a building type."; $problems[] = "Start building [$type] is not a building type.";
continue;
} }
[$fw, $fh] = $rules->footprint($type);
$at = $grid->freeSlot($fw, $fh);
if (! $at) {
$problems[] = "Start building [$type] does not fit the {$w}x{$h} grid.";
continue;
} }
$grid->take($at['x'], $at['y'], $fw, $fh); if ($problems) {
return $problems;
}
$used = $rules->spaceUsed($start);
if ($used > $max) {
return ["The start buildings take $used building space, more than the village's $max."];
}
foreach ($config->buildingTypes() as $type) {
if ($used + $rules->space($type) > $max) {
$problems[] = "[$type] does not fit next to the start buildings.";
}
} }
return $problems; return $problems;

View File

@ -0,0 +1,17 @@
<?php
namespace App\Game\Map;
/**
* Continents are 100 × 100 blocks named by their y and x hundreds, as in Die Stämme:
* 500|500 lies in K55, 123|456 in K41.
*/
final class Continent
{
public const SIZE = 100;
public static function of(int $x, int $y): string
{
return 'K'.intdiv($y, self::SIZE).intdiv($x, self::SIZE);
}
}

View File

@ -22,8 +22,6 @@ class BuildOrder extends Model
return [ return [
'cost' => 'array', 'cost' => 'array',
'target_level' => 'integer', 'target_level' => 'integer',
'x' => 'integer',
'y' => 'integer',
'builder' => 'integer', 'builder' => 'integer',
'starts_at' => 'immutable_datetime', 'starts_at' => 'immutable_datetime',
'finishes_at' => 'immutable_datetime', 'finishes_at' => 'immutable_datetime',

View File

@ -12,7 +12,7 @@ class Building extends Model
protected function casts(): array protected function casts(): array
{ {
return ['level' => 'integer', 'priority' => 'integer', 'x' => 'integer', 'y' => 'integer']; return ['level' => 'integer', 'priority' => 'integer'];
} }
public function village(): BelongsTo public function village(): BelongsTo
@ -22,6 +22,6 @@ class Building extends Model
public function state(): BuildingState public function state(): BuildingState
{ {
return new BuildingState($this->id, $this->type, $this->level, $this->priority, $this->x, $this->y); return new BuildingState($this->id, $this->type, $this->level, $this->priority);
} }
} }

View File

@ -3,6 +3,7 @@
namespace App\Presenters; namespace App\Presenters;
use App\Engine\Simulation; use App\Engine\Simulation;
use App\Game\Map\Continent;
use App\Models\Building; use App\Models\Building;
use App\Models\BuildOrder; use App\Models\BuildOrder;
use App\Models\Village; use App\Models\Village;
@ -24,10 +25,13 @@ final class VillagePresenter
return [ return [
'id' => $village->id, 'id' => $village->id,
'world_id' => $village->world_id,
'name' => $village->name, 'name' => $village->name,
'x' => $village->x, 'x' => $village->x,
'y' => $village->y, 'y' => $village->y,
'grid' => ['w' => $village->grid_w, 'h' => $village->grid_h], 'continent' => Continent::of($village->x, $village->y),
'points' => $village->points,
'space' => ['used' => $sim->spaceUsed(), 'max' => $village->space],
'resources' => array_map(fn (float $n) => round($n, 4), $village->resources()), 'resources' => array_map(fn (float $n) => round($n, 4), $village->resources()),
'resources_at' => self::iso($village->resources_at), 'resources_at' => self::iso($village->resources_at),
'rates' => array_map(fn (float $n) => round($n, 4), $sim->rates()), 'rates' => array_map(fn (float $n) => round($n, 4), $sim->rates()),
@ -47,9 +51,7 @@ final class VillagePresenter
'id' => $b->id, 'id' => $b->id,
'type' => $b->type, 'type' => $b->type,
'level' => $b->level, 'level' => $b->level,
'x' => $b->x, 'space' => $rules->space($b->type),
'y' => $b->y,
'footprint' => $rules->footprint($b->type),
'priority' => $b->priority, 'priority' => $b->priority,
'workers' => ['assigned' => $workforce->assigned[$b->id] ?? 0, 'required' => $workforce->required[$b->id] ?? 0], 'workers' => ['assigned' => $workforce->assigned[$b->id] ?? 0, 'required' => $workforce->required[$b->id] ?? 0],
'staffing' => round($workforce->ratio($b->id), 4), 'staffing' => round($workforce->ratio($b->id), 4),
@ -64,9 +66,7 @@ final class VillagePresenter
'type' => $o->type, 'type' => $o->type,
'action' => $o->action, 'action' => $o->action,
'target_level' => $o->target_level, 'target_level' => $o->target_level,
'x' => $o->x, 'space' => $rules->space($o->type),
'y' => $o->y,
'footprint' => $rules->footprint($o->type),
'cost' => $o->cost, 'cost' => $o->cost,
'position' => ++$position, 'position' => ++$position,
'builder' => $o->builder, 'builder' => $o->builder,

View File

@ -24,16 +24,7 @@ class VillageController extends GameController
public function build() public function build()
{ {
$x = request('x'); return $this->village(fn ($user, $id) => app(QueueBuild::class)($user, $id, (string) request('type')));
$y = request('y');
return $this->village(fn ($user, $id) => app(QueueBuild::class)(
$user,
$id,
(string) request('type'),
is_numeric($x) ? (int) $x : null,
is_numeric($y) ? (int) $y : null,
));
} }
public function upgrade() public function upgrade()

View File

@ -1,13 +1,15 @@
<?php <?php
// Values per building type. Levels start at 0 (tent, open storage, gatherers). // Values per building type. Levels start at 0 (tent, open storage, gatherers).
// `space` is how much of the village's building space an instance takes, at any level.
// Level n: cost = cost × factor^n, build time = base × factor^n seconds at world speed 1, // Level n: cost = cost × factor^n, build time = base × factor^n seconds at world speed 1,
// workers = round(base × factor^n), production/capacity = base × factor^n. // workers = round(base × factor^n), production/capacity = base × factor^n.
// The n-th instance of a type (0-based) costs instance_cost_factor^n times as much. // The n-th instance of a type (0-based) costs instance_cost_factor^n times as much.
// Map points of an instance: round(points.base × points.factor^level).
return [ return [
'headquarters' => [ 'headquarters' => [
'footprint' => [3, 3], 'space' => 9,
'max_per_village' => 1, 'max_per_village' => 1,
'max_level' => 30, 'max_level' => 30,
'cost' => ['wood' => 90, 'clay' => 80, 'iron' => 70, 'factor' => 1.26], 'cost' => ['wood' => 90, 'clay' => 80, 'iron' => 70, 'factor' => 1.26],
@ -15,10 +17,11 @@ return [
'workers' => ['base' => 2, 'factor' => 1.1], 'workers' => ['base' => 2, 'factor' => 1.1],
'production' => null, 'production' => null,
'instance_cost_factor' => 1.0, 'instance_cost_factor' => 1.0,
'points' => ['base' => 10, 'factor' => 1.2],
'requires' => [], 'requires' => [],
], ],
'storage' => [ 'storage' => [
'footprint' => [2, 2], 'space' => 4,
'max_per_village' => null, 'max_per_village' => null,
'max_level' => 30, 'max_level' => 30,
'cost' => ['wood' => 60, 'clay' => 50, 'iron' => 40, 'factor' => 1.27], 'cost' => ['wood' => 60, 'clay' => 50, 'iron' => 40, 'factor' => 1.27],
@ -27,10 +30,11 @@ return [
'production' => null, 'production' => null,
'capacity' => ['base' => 1000, 'factor' => 1.23], 'capacity' => ['base' => 1000, 'factor' => 1.23],
'instance_cost_factor' => 1.5, 'instance_cost_factor' => 1.5,
'points' => ['base' => 6, 'factor' => 1.2],
'requires' => [], 'requires' => [],
], ],
'farm' => [ 'farm' => [
'footprint' => [2, 2], 'space' => 4,
'max_per_village' => null, 'max_per_village' => null,
'max_level' => 30, 'max_level' => 30,
'cost' => ['wood' => 45, 'clay' => 40, 'iron' => 30, 'factor' => 1.27], 'cost' => ['wood' => 45, 'clay' => 40, 'iron' => 30, 'factor' => 1.27],
@ -38,10 +42,11 @@ return [
'workers' => ['base' => 2, 'factor' => 1.1], 'workers' => ['base' => 2, 'factor' => 1.1],
'production' => ['resource' => 'food', 'base' => 30, 'factor' => 1.17], 'production' => ['resource' => 'food', 'base' => 30, 'factor' => 1.17],
'instance_cost_factor' => 1.5, 'instance_cost_factor' => 1.5,
'points' => ['base' => 5, 'factor' => 1.2],
'requires' => [], 'requires' => [],
], ],
'timber_camp' => [ 'timber_camp' => [
'footprint' => [2, 2], 'space' => 4,
'max_per_village' => null, 'max_per_village' => null,
'max_level' => 30, 'max_level' => 30,
'cost' => ['wood' => 50, 'clay' => 60, 'iron' => 40, 'factor' => 1.25], 'cost' => ['wood' => 50, 'clay' => 60, 'iron' => 40, 'factor' => 1.25],
@ -49,10 +54,11 @@ return [
'workers' => ['base' => 2, 'factor' => 1.12], 'workers' => ['base' => 2, 'factor' => 1.12],
'production' => ['resource' => 'wood', 'base' => 30, 'factor' => 1.163], 'production' => ['resource' => 'wood', 'base' => 30, 'factor' => 1.163],
'instance_cost_factor' => 1.5, 'instance_cost_factor' => 1.5,
'points' => ['base' => 6, 'factor' => 1.2],
'requires' => [], 'requires' => [],
], ],
'clay_pit' => [ 'clay_pit' => [
'footprint' => [2, 2], 'space' => 4,
'max_per_village' => null, 'max_per_village' => null,
'max_level' => 30, 'max_level' => 30,
'cost' => ['wood' => 65, 'clay' => 50, 'iron' => 40, 'factor' => 1.27], 'cost' => ['wood' => 65, 'clay' => 50, 'iron' => 40, 'factor' => 1.27],
@ -60,10 +66,11 @@ return [
'workers' => ['base' => 2, 'factor' => 1.12], 'workers' => ['base' => 2, 'factor' => 1.12],
'production' => ['resource' => 'clay', 'base' => 30, 'factor' => 1.163], 'production' => ['resource' => 'clay', 'base' => 30, 'factor' => 1.163],
'instance_cost_factor' => 1.5, 'instance_cost_factor' => 1.5,
'points' => ['base' => 6, 'factor' => 1.2],
'requires' => [], 'requires' => [],
], ],
'iron_mine' => [ 'iron_mine' => [
'footprint' => [2, 2], 'space' => 4,
'max_per_village' => null, 'max_per_village' => null,
'max_level' => 30, 'max_level' => 30,
'cost' => ['wood' => 75, 'clay' => 65, 'iron' => 70, 'factor' => 1.252], 'cost' => ['wood' => 75, 'clay' => 65, 'iron' => 70, 'factor' => 1.252],
@ -71,10 +78,11 @@ return [
'workers' => ['base' => 2, 'factor' => 1.12], 'workers' => ['base' => 2, 'factor' => 1.12],
'production' => ['resource' => 'iron', 'base' => 30, 'factor' => 1.163], 'production' => ['resource' => 'iron', 'base' => 30, 'factor' => 1.163],
'instance_cost_factor' => 1.5, 'instance_cost_factor' => 1.5,
'points' => ['base' => 6, 'factor' => 1.2],
'requires' => [], 'requires' => [],
], ],
'hiding_place' => [ 'hiding_place' => [
'footprint' => [1, 1], 'space' => 1,
'max_per_village' => null, 'max_per_village' => null,
'max_level' => 10, 'max_level' => 10,
'cost' => ['wood' => 50, 'clay' => 60, 'iron' => 50, 'factor' => 1.25], 'cost' => ['wood' => 50, 'clay' => 60, 'iron' => 50, 'factor' => 1.25],
@ -82,11 +90,12 @@ return [
'workers' => ['base' => 0, 'factor' => 1.0], 'workers' => ['base' => 0, 'factor' => 1.0],
'production' => null, 'production' => null,
'instance_cost_factor' => 1.5, 'instance_cost_factor' => 1.5,
'points' => ['base' => 5, 'factor' => 1.2],
'requires' => [], 'requires' => [],
], ],
'wall' => [ 'wall' => [
// Surrounds the village and takes no cells. // Surrounds the village and takes no building space.
'footprint' => [0, 0], 'space' => 0,
'max_per_village' => 1, 'max_per_village' => 1,
'max_level' => 20, 'max_level' => 20,
'cost' => ['wood' => 50, 'clay' => 100, 'iron' => 20, 'factor' => 1.26], 'cost' => ['wood' => 50, 'clay' => 100, 'iron' => 20, 'factor' => 1.26],
@ -94,10 +103,11 @@ return [
'workers' => ['base' => 1, 'factor' => 1.1], 'workers' => ['base' => 1, 'factor' => 1.1],
'production' => null, 'production' => null,
'instance_cost_factor' => 1.0, 'instance_cost_factor' => 1.0,
'points' => ['base' => 8, 'factor' => 1.2],
'requires' => ['headquarters' => 1], 'requires' => ['headquarters' => 1],
], ],
'rally_point' => [ 'rally_point' => [
'footprint' => [1, 1], 'space' => 1,
'max_per_village' => 1, 'max_per_village' => 1,
'max_level' => 1, 'max_level' => 1,
'cost' => ['wood' => 10, 'clay' => 40, 'iron' => 30, 'factor' => 1.26], 'cost' => ['wood' => 10, 'clay' => 40, 'iron' => 30, 'factor' => 1.26],
@ -105,6 +115,7 @@ return [
'workers' => ['base' => 0, 'factor' => 1.0], 'workers' => ['base' => 0, 'factor' => 1.0],
'production' => null, 'production' => null,
'instance_cost_factor' => 1.0, 'instance_cost_factor' => 1.0,
'points' => ['base' => 2, 'factor' => 1.2],
'requires' => [], 'requires' => [],
], ],
]; ];

View File

@ -7,7 +7,8 @@ return [
'speed' => 1.0, 'speed' => 1.0,
'village' => [ 'village' => [
'grid' => [10, 5], // Building space: the sum of the buildings' `space` may not exceed it.
'space' => 50,
'start_resources' => ['wood' => 500, 'clay' => 500, 'iron' => 500, 'food' => 300], 'start_resources' => ['wood' => 500, 'clay' => 500, 'iron' => 500, 'food' => 300],
// Auto-placed at level 0 in this order. // Auto-placed at level 0 in this order.
'start_buildings' => ['headquarters', 'storage', 'farm'], 'start_buildings' => ['headquarters', 'storage', 'farm'],
@ -21,5 +22,9 @@ return [
'map' => [ 'map' => [
'size' => 1000, 'size' => 1000,
// Most fields one map.view may cover in each direction.
'max_view' => 41,
// Seeded once per world around the map centre, buildings at random levels up to max_level.
'barbarians' => ['count' => 120, 'radius' => 25, 'max_level' => 3],
], ],
]; ];

View File

@ -0,0 +1,52 @@
<?php
use App\Engine\Simulation;
use App\Models\Village;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
// Villages no longer have a grid of cells: buildings take building space from a
// per-village budget, and the client lays out the diorama itself.
return new class extends Migration
{
public function up(): void
{
Schema::table('villages', function (Blueprint $table) {
$table->unsignedSmallInteger('space')->default(50)->after('y');
});
Schema::table('villages', function (Blueprint $table) {
$table->dropColumn(['grid_w', 'grid_h']);
});
Schema::table('buildings', function (Blueprint $table) {
$table->dropColumn(['x', 'y']);
});
Schema::table('build_orders', function (Blueprint $table) {
$table->dropColumn(['x', 'y']);
});
// Points were never counted before the map needed them.
Village::with(['world', 'buildings', 'orders'])->each(
fn (Village $village) => $village->update(['points' => Simulation::of($village)->points()]),
);
}
public function down(): void
{
Schema::table('build_orders', function (Blueprint $table) {
$table->unsignedSmallInteger('x')->default(0);
$table->unsignedSmallInteger('y')->default(0);
});
Schema::table('buildings', function (Blueprint $table) {
$table->unsignedSmallInteger('x')->default(0);
$table->unsignedSmallInteger('y')->default(0);
});
Schema::table('villages', function (Blueprint $table) {
$table->unsignedSmallInteger('grid_w')->default(10);
$table->unsignedSmallInteger('grid_h')->default(5);
});
Schema::table('villages', function (Blueprint $table) {
$table->dropColumn('space');
});
}
};

View File

@ -21,14 +21,15 @@ it('settles resources by rate and elapsed time, up to the storage cap', function
expect(shown($village)['resources']['wood'])->toBe(1000.0); expect(shown($village)['resources']['wood'])->toBe(1000.0);
}); });
it('pays up front, builds at the first free slot and finishes on time', function () { it('pays up front, reserves the space and finishes on time', function () {
$village = startVillage(); $village = startVillage();
app(QueueBuild::class)(owner($village), $village->id, 'timber_camp'); app(QueueBuild::class)(owner($village), $village->id, 'timber_camp');
$state = shown($village); $state = shown($village);
expect($state['resources']['wood'])->toBe(450.0) expect($state['resources']['wood'])->toBe(450.0)
->and($state['space'])->toBe(['used' => 21, 'max' => 50])
->and($state['queue'][0])->toMatchArray([ ->and($state['queue'][0])->toMatchArray([
'type' => 'timber_camp', 'action' => 'build', 'x' => 7, 'y' => 0, 'builder' => 1, 'type' => 'timber_camp', 'action' => 'build', 'space' => 4, 'builder' => 1,
'starts_at' => '2026-10-28T12:00:00.000Z', 'finishes_at' => '2026-10-28T12:01:30.000Z', 'starts_at' => '2026-10-28T12:00:00.000Z', 'finishes_at' => '2026-10-28T12:01:30.000Z',
]); ]);
@ -38,17 +39,29 @@ it('pays up front, builds at the first free slot and finishes on time', function
$this->travel(1)->seconds(); $this->travel(1)->seconds();
$state = shown($village); $state = shown($village);
expect($state['queue'])->toBe([]) expect($state['queue'])->toBe([])
->and(collect($state['buildings'])->firstWhere('type', 'timber_camp'))->toMatchArray(['level' => 0, 'x' => 7, 'y' => 0]) ->and(collect($state['buildings'])->firstWhere('type', 'timber_camp'))->toMatchArray(['level' => 0, 'space' => 4])
->and($state['rates']['wood'])->toBe(35.0); ->and($state['rates']['wood'])->toBe(35.0)
->and($state['points'])->toBe(27);
}); });
it('builds at a chosen cell and refuses taken cells', function () { it('refuses a building that does not fit the free building space', function () {
// Start buildings take 17 of 50; five timber camps and twelve hiding places bring it to 49.
$village = startVillage(); $village = startVillage();
$village->buildings()->createMany([
...array_fill(0, 5, ['type' => 'timber_camp', 'level' => 0]),
...array_fill(0, 12, ['type' => 'hiding_place', 'level' => 0]),
]);
app(QueueBuild::class)(owner($village), $village->id, 'hiding_place', 9, 4); $options = collect(shown($village)['buildable'])->keyBy('type');
expect(shown($village)['queue'][0])->toMatchArray(['x' => 9, 'y' => 4]) expect($options['timber_camp']['blocked'])->toBe('no_space')
->and(rule(fn () => app(QueueBuild::class)(owner($village), $village->id, 'rally_point', 9, 4)))->toBe('no_space') ->and($options['rally_point'])->toMatchArray(['space' => 1, 'blocked' => null])
->and(rule(fn () => app(QueueBuild::class)(owner($village), $village->id, 'farm', 1, 1)))->toBe('no_space'); ->and(rule(fn () => app(QueueBuild::class)(owner($village), $village->id, 'storage')))->toBe('no_space');
// Queuing reserves the space right away.
app(QueueBuild::class)(owner($village), $village->id, 'rally_point');
$state = shown($village);
expect($state['space'])->toBe(['used' => 50, 'max' => 50])
->and(collect($state['buildable'])->firstWhere('type', 'hiding_place')['blocked'])->toBe('no_space');
}); });
it('refuses a second headquarters, a wall without HQ 1 and what it cannot pay', function () { it('refuses a second headquarters, a wall without HQ 1 and what it cannot pay', function () {
@ -143,8 +156,8 @@ it('keeps core buildings at level 0', function () {
it('moves workers to the buildings with the highest priority', function () { 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. // 30 villagers: the farm takes 2, the clay pit at priority 9 the other 28.
$village = startVillage(); $village = startVillage();
$village->buildings()->create(['type' => 'timber_camp', 'level' => 30, 'x' => 7, 'y' => 0]); $village->buildings()->create(['type' => 'timber_camp', 'level' => 30]);
$clay = $village->buildings()->create(['type' => 'clay_pit', 'level' => 30, 'x' => 0, 'y' => 3]); $clay = $village->buildings()->create(['type' => 'clay_pit', 'level' => 30]);
app(SetPriority::class)(owner($village), $village->id, $clay->id, 12); app(SetPriority::class)(owner($village), $village->id, $clay->id, 12);
$buildings = collect(shown($village)['buildings'])->keyBy('type'); $buildings = collect(shown($village)['buildings'])->keyBy('type');

View File

@ -9,12 +9,12 @@ use App\Models\World;
it('starts a village with HQ, storage and farm at level 0', function () { it('starts a village with HQ, storage and farm at level 0', function () {
$village = startVillage(); $village = startVillage();
expect($village->only('x', 'y', 'grid_w', 'grid_h'))->toBe(['x' => 500, 'y' => 500, 'grid_w' => 10, 'grid_h' => 5]) expect($village->only('x', 'y', 'space', 'points'))->toBe(['x' => 500, 'y' => 500, 'space' => 50, 'points' => 21])
->and($village->resources())->toBe(['wood' => 500.0, 'clay' => 500.0, 'iron' => 500.0, 'food' => 300.0]) ->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([ ->and($village->buildings->map->only('type', 'level')->all())->toBe([
['type' => 'headquarters', 'level' => 0, 'x' => 0, 'y' => 0], ['type' => 'headquarters', 'level' => 0],
['type' => 'storage', 'level' => 0, 'x' => 3, 'y' => 0], ['type' => 'storage', 'level' => 0],
['type' => 'farm', 'level' => 0, 'x' => 5, 'y' => 0], ['type' => 'farm', 'level' => 0],
]); ]);
}); });
@ -45,7 +45,9 @@ it('shows a start village to its owner only', function () {
$village = startVillage(); $village = startVillage();
$state = shown($village); $state = shown($village);
expect($state['rates'])->toBe(['wood' => 5.0, 'clay' => 5.0, 'iron' => 5.0, 'food' => 0.0]) expect($state['space'])->toBe(['used' => 17, 'max' => 50])
->and($state['continent'])->toBe('K55')
->and($state['rates'])->toBe(['wood' => 5.0, 'clay' => 5.0, 'iron' => 5.0, 'food' => 0.0])
->and($state['storage_cap'])->toEqual(1000) ->and($state['storage_cap'])->toEqual(1000)
->and($state['population'])->toEqual(['food_budget' => 30, 'upkeep' => 30, 'villagers' => 30, 'workers' => 5, 'soldiers' => 0]) ->and($state['population'])->toEqual(['food_budget' => 30, 'upkeep' => 30, 'villagers' => 30, 'workers' => 5, 'soldiers' => 0])
->and($state['builders'])->toBe(2) ->and($state['builders'])->toBe(2)

View File

@ -13,7 +13,10 @@ use Database\Seeders\WorldSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase; use Tests\TestCase;
pest()->extend(TestCase::class)->use(RefreshDatabase::class)->in('Feature'); // Feature tests start without barbarians unless a test asks for them, to stay fast.
pest()->extend(TestCase::class)->use(RefreshDatabase::class)
->beforeEach(fn () => config(['game.world.map.barbarians.count' => 0]))
->in('Feature');
/** The default game config without booting Laravel, so unit tests stay pure. */ /** The default game config without booting Laravel, so unit tests stay pure. */
function gameConfig(array $overrides = []): WorldConfig function gameConfig(array $overrides = []): WorldConfig

View File

@ -58,6 +58,22 @@ it('gives storage capacity only to storage', function () {
->and($rules->capacity('farm', 1))->toBe(0.0); ->and($rules->capacity('farm', 1))->toBe(0.0);
}); });
it('takes building space per type at every level, and none for the wall', function () {
$rules = new BuildingRules(gameConfig());
expect($rules->space('headquarters'))->toBe(9)
->and($rules->space('wall'))->toBe(0)
->and($rules->spaceUsed(['headquarters', 'storage', 'farm', 'hiding_place', 'wall']))->toBe(18);
});
it('gives points per building level', function () {
$rules = new BuildingRules(gameConfig());
expect($rules->points('headquarters', 0))->toBe(10)
->and($rules->points('headquarters', 5))->toBe((int) round(10 * 1.2 ** 5))
->and($rules->points('rally_point', 0))->toBe(2);
});
it('adds builders at the configured headquarters levels', function () { it('adds builders at the configured headquarters levels', function () {
$rules = new BuildingRules(gameConfig()); $rules = new BuildingRules(gameConfig());

View File

@ -33,8 +33,14 @@ it('reports requirement cycles and unknown requirements', function () {
->toContain('Requirement cycle through [wall].'); ->toContain('Requirement cycle through [wall].');
}); });
it('reports start buildings that do not fit the grid', function () { it('reports start buildings that take more space than a village has', function () {
$config = gameConfig(['world' => ['village' => ['grid' => [3, 3]]]]); $config = gameConfig(['world' => ['village' => ['space' => 12]]]);
expect(ConfigLint::check($config))->toContain('Start building [storage] does not fit the 3x3 grid.'); expect(ConfigLint::check($config))->toBe(['The start buildings take 17 building space, more than the village\'s 12.']);
});
it('reports a type that can never fit next to the start buildings', function () {
$config = gameConfig(['world' => ['village' => ['space' => 25]]]);
expect(ConfigLint::check($config))->toBe(['[headquarters] does not fit next to the start buildings.']);
}); });

View File

@ -0,0 +1,10 @@
<?php
use App\Game\Map\Continent;
it('names continents by the hundreds of y, then x', function () {
expect(Continent::of(500, 500))->toBe('K55')
->and(Continent::of(123, 456))->toBe('K41')
->and(Continent::of(0, 0))->toBe('K00')
->and(Continent::of(999, 99))->toBe('K09');
});

View File

@ -1,39 +0,0 @@
<?php
use App\Game\Buildings\VillageGrid;
it('keeps footprints inside the bounds', function () {
$grid = new VillageGrid(10, 5);
expect($grid->fits(3, 3, 0, 0))->toBeTrue()
->and($grid->fits(3, 3, 7, 2))->toBeTrue()
->and($grid->fits(3, 3, 8, 0))->toBeFalse()
->and($grid->fits(2, 2, 0, 4))->toBeFalse()
->and($grid->fits(1, 1, -1, 0))->toBeFalse();
});
it('rejects overlapping footprints', function () {
$grid = VillageGrid::with(10, 5, [['x' => 0, 'y' => 0, 'w' => 3, 'h' => 3]]);
expect($grid->fits(2, 2, 2, 2))->toBeFalse()
->and($grid->fits(2, 2, 3, 0))->toBeTrue();
});
it('finds the first free slot row by row', function () {
$grid = VillageGrid::with(10, 5, [
['x' => 0, 'y' => 0, 'w' => 3, 'h' => 3],
['x' => 3, 'y' => 0, 'w' => 2, 'h' => 2],
]);
expect($grid->freeSlot(2, 2))->toBe(['x' => 5, 'y' => 0])
->and($grid->freeSlot(1, 1))->toBe(['x' => 5, 'y' => 0])
->and($grid->freeSlot(10, 3))->toBeNull();
});
it('lets the wall fit without taking cells', function () {
$full = VillageGrid::with(2, 2, [['x' => 0, 'y' => 0, 'w' => 2, 'h' => 2]]);
expect($full->fits(0, 0, 0, 0))->toBeTrue()
->and($full->freeSlot(0, 0))->toBe(['x' => 0, 'y' => 0])
->and($full->freeSlot(1, 1))->toBeNull();
});