diff --git a/app/Game/Buildings/BuildQueue.php b/app/Game/Buildings/BuildQueue.php new file mode 100644 index 0000000..dc78cb3 --- /dev/null +++ b/app/Game/Buildings/BuildQueue.php @@ -0,0 +1,54 @@ + $orders in queue order + * @return array order id => builder slot (1-based) to start now + */ + public static function startable(array $orders, int $builders): array + { + $running = array_filter($orders, fn (array $o) => $o['builder'] !== null); + $busy = array_column($running, 'builder'); + $blocked = array_flip(array_filter(array_column($running, 'building_id'), fn ($id) => $id !== null)); + + $start = []; + foreach ($orders as $o) { + if ($o['builder'] !== null) { + continue; + } + if ($o['building_id'] !== null) { + if (isset($blocked[$o['building_id']])) { + continue; + } + $blocked[$o['building_id']] = true; + } + $slot = self::freeSlot($busy, $builders); + if ($slot === null) { + break; + } + $busy[] = $slot; + $start[$o['id']] = $slot; + } + + return $start; + } + + /** @param list $busy */ + private static function freeSlot(array $busy, int $builders): ?int + { + for ($slot = 1; $slot <= $builders; $slot++) { + if (! in_array($slot, $busy, true)) { + return $slot; + } + } + + return null; + } +} diff --git a/app/Game/Buildings/BuildingRules.php b/app/Game/Buildings/BuildingRules.php new file mode 100644 index 0000000..636fb43 --- /dev/null +++ b/app/Game/Buildings/BuildingRules.php @@ -0,0 +1,126 @@ +config->building($type)['cost']; + $multiplier = $cost['factor'] ** $level * $this->instanceFactor($type) ** $instance; + + return [ + 'wood' => (int) round($cost['wood'] * $multiplier), + 'clay' => (int) round($cost['clay'] * $multiplier), + 'iron' => (int) round($cost['iron'] * $multiplier), + ]; + } + + /** + * Seconds to build $level, at world speed, sped up by the headquarters' level + * and slowed by its staffing (output factor 0..1). + */ + public function buildSeconds(string $type, int $level, int $hqLevel, float $hqStaffing): int + { + $time = $this->config->building($type)['build_time']; + $seconds = $time['base'] * $time['factor'] ** $level + / $this->config->speed() + / (1 + $this->config->get('economy.hq_build_speed_per_level', 0) * $hqLevel) + / max($hqStaffing, 0.01); + + return max(1, (int) ceil($seconds)); + } + + /** Seconds to take $level down by one. */ + public function demolishSeconds(string $type, int $level, int $hqLevel, float $hqStaffing): int + { + $factor = $this->config->get('economy.demolish_time_factor', 0.5); + + return max(1, (int) ceil($this->buildSeconds($type, $level, $hqLevel, $hqStaffing) * $factor)); + } + + /** @return array{wood: int, clay: int, iron: int} */ + public function demolishRefund(string $type, int $level, int $instance = 0): array + { + $share = $this->config->get('economy.demolish_refund', 0.5); + + return array_map(fn (int $n) => (int) floor($n * $share), $this->cost($type, $level, $instance)); + } + + public function workers(string $type, int $level): int + { + $workers = $this->config->building($type)['workers']; + + return (int) round($workers['base'] * $workers['factor'] ** $level); + } + + /** + * Output per hour at full staffing and world speed, or null for non-producers. + * + * @return array{resource: string, per_hour: float}|null + */ + public function output(string $type, int $level): ?array + { + $production = $this->config->building($type)['production'] ?? null; + if (! $production) { + return null; + } + + return [ + 'resource' => $production['resource'], + 'per_hour' => $production['base'] * $production['factor'] ** $level * $this->config->speed(), + ]; + } + + /** Storage capacity this building adds, 0 for non-storage. */ + public function capacity(string $type, int $level): float + { + $capacity = $this->config->building($type)['capacity'] ?? null; + + return $capacity ? $capacity['base'] * $capacity['factor'] ** $level : 0.0; + } + + /** @return array{0: int, 1: int} */ + public function footprint(string $type): array + { + return $this->config->building($type)['footprint']; + } + + public function maxLevel(string $type): int + { + return $this->config->building($type)['max_level']; + } + + public function maxPerVillage(string $type): ?int + { + return $this->config->building($type)['max_per_village']; + } + + /** @return array type => minimum level of any instance */ + public function requires(string $type): array + { + return $this->config->building($type)['requires'] ?? []; + } + + public function builders(int $hqLevel): int + { + $extra = array_filter($this->config->get('world.builders.extra_at_hq_levels', []), fn (int $l) => $hqLevel >= $l); + + return $this->config->get('world.builders.base', 2) + count($extra); + } + + private function instanceFactor(string $type): float + { + return $this->config->building($type)['instance_cost_factor'] ?? 1.0; + } +} diff --git a/app/Game/Buildings/BuildingState.php b/app/Game/Buildings/BuildingState.php new file mode 100644 index 0000000..c6e861a --- /dev/null +++ b/app/Game/Buildings/BuildingState.php @@ -0,0 +1,16 @@ + */ + private array $taken = []; + + public function __construct(public readonly int $w, public readonly int $h) {} + + /** @param iterable $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 */ + 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; + } +} diff --git a/app/Game/ConfigLint.php b/app/Game/ConfigLint.php new file mode 100644 index 0000000..635a3a5 --- /dev/null +++ b/app/Game/ConfigLint.php @@ -0,0 +1,140 @@ + */ + public static function check(WorldConfig $config): array + { + $rules = new BuildingRules($config); + + return [ + ...self::startVillageFits($config, $rules), + ...self::farmsFeedTheirWorkers($config, $rules), + ...self::costsFitStorage($config, $rules), + ...self::requirementsReachable($config, $rules), + ]; + } + + /** The start buildings must fit the default grid, and be allowed at all. */ + private static function startVillageFits(WorldConfig $config, BuildingRules $rules): array + { + [$w, $h] = $config->get('world.village.grid'); + $grid = new VillageGrid($w, $h); + $problems = []; + foreach ($config->get('world.village.start_buildings', []) as $type) { + if (! $config->hasBuilding($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); + } + + return $problems; + } + + /** Capacity is never 0, and each farm level's workers eat less than it makes. */ + private static function farmsFeedTheirWorkers(WorldConfig $config, BuildingRules $rules): array + { + $problems = []; + $perVillager = $config->get('economy.upkeep.villager', 1); + foreach ($config->buildingTypes() as $type) { + if (($rules->output($type, 0)['resource'] ?? null) !== 'food') { + continue; + } + for ($level = 0; $level <= $rules->maxLevel($type); $level++) { + $output = $rules->output($type, $level)['per_hour']; + if ($output <= 0 || $rules->workers($type, $level) * $perVillager >= $output) { + $problems[] = "[$type] level $level feeds fewer people than it needs as workers."; + } + } + } + + return $problems; + } + + /** + * Every level's cost fits one storage at max level, and storage's next level + * always fits what its current level holds. + */ + private static function costsFitStorage(WorldConfig $config, BuildingRules $rules): array + { + $storages = array_filter($config->buildingTypes(), fn (string $t) => $rules->capacity($t, 0) > 0); + if (! $storages) { + return ['No building type provides storage.']; + } + $problems = []; + $maxCap = max(array_map(fn (string $t) => $rules->capacity($t, $rules->maxLevel($t)), $storages)); + foreach ($config->buildingTypes() as $type) { + for ($level = 0; $level <= $rules->maxLevel($type); $level++) { + if (max($rules->cost($type, $level)) > $maxCap) { + $problems[] = "[$type] level $level costs more than the largest storage holds."; + } + } + } + foreach ($storages as $type) { + for ($level = 0; $level < $rules->maxLevel($type); $level++) { + if (max($rules->cost($type, $level + 1)) > $rules->capacity($type, $level)) { + $problems[] = "[$type] level ".($level + 1)." costs more than level $level holds."; + } + } + } + + return $problems; + } + + /** Requirements name real types and levels, and have no cycles. */ + private static function requirementsReachable(WorldConfig $config, BuildingRules $rules): array + { + $problems = []; + foreach ($config->buildingTypes() as $type) { + foreach ($rules->requires($type) as $needed => $level) { + if (! $config->hasBuilding($needed)) { + $problems[] = "[$type] requires unknown type [$needed]."; + } elseif ($level > $rules->maxLevel($needed)) { + $problems[] = "[$type] requires [$needed] level $level, above its max level."; + } + } + } + + $visiting = []; + $done = []; + $visit = function (string $type) use (&$visit, &$visiting, &$done, &$problems, $config, $rules): void { + if (isset($done[$type]) || ! $config->hasBuilding($type)) { + return; + } + if (isset($visiting[$type])) { + $problems[] = "Requirement cycle through [$type]."; + + return; + } + $visiting[$type] = true; + foreach (array_keys($rules->requires($type)) as $needed) { + $visit($needed); + } + unset($visiting[$type]); + $done[$type] = true; + }; + foreach ($config->buildingTypes() as $type) { + $visit($type); + } + + return $problems; + } +} diff --git a/app/Game/Economy/Population.php b/app/Game/Economy/Population.php new file mode 100644 index 0000000..d1f8f16 --- /dev/null +++ b/app/Game/Economy/Population.php @@ -0,0 +1,100 @@ +rules = new BuildingRules($config); + } + + /** @param list $buildings */ + public function foodBudget(array $buildings): float + { + $budget = 0.0; + foreach ($buildings as $b) { + $output = $this->rules->output($b->type, $b->level); + if ($output && $output['resource'] === 'food') { + $budget += $output['per_hour']; + } + } + + return $budget; + } + + /** + * @param list $buildings + * @param float $soldierUpkeep food/h eaten by soldiers and stationed support + */ + public function workforce(array $buildings, float $soldierUpkeep = 0.0): Workforce + { + $budget = $this->foodBudget($buildings); + $perVillager = $this->config->get('economy.upkeep.villager', 1); + $villagers = max(0, (int) floor(($budget - $soldierUpkeep) / $perVillager)); + + $required = []; + foreach ($buildings as $b) { + $required[$b->id] = $this->rules->workers($b->type, $b->level); + } + + return new Workforce( + foodBudget: $budget, + villagers: $villagers, + upkeep: $villagers * $perVillager + $soldierUpkeep, + assigned: $this->assign($buildings, $required, $villagers), + required: $required, + ); + } + + /** + * Farms first, then by priority (highest first). Buildings with the same priority + * share what is left evenly, one villager at a time in id order. + * + * @param list $buildings + * @param array $required + * @return array + */ + private function assign(array $buildings, array $required, int $villagers): array + { + $groups = []; + foreach ($buildings as $b) { + $isFarm = ($this->rules->output($b->type, $b->level)['resource'] ?? null) === 'food'; + $groups[($isFarm ? 'a' : 'b').str_pad((string) (99 - $b->priority), 3, '0', STR_PAD_LEFT)][] = $b->id; + } + ksort($groups); + + $assigned = array_fill_keys(array_keys($required), 0); + $free = $villagers; + foreach ($groups as $ids) { + sort($ids); + $open = array_values(array_filter($ids, fn (int $id) => $required[$id] > 0)); + while ($free > 0 && $open) { + foreach ($open as $i => $id) { + if ($free === 0) { + break; + } + $assigned[$id]++; + $free--; + if ($assigned[$id] >= $required[$id]) { + unset($open[$i]); + } + } + } + } + + return $assigned; + } +} diff --git a/app/Game/Economy/Production.php b/app/Game/Economy/Production.php new file mode 100644 index 0000000..972afde --- /dev/null +++ b/app/Game/Economy/Production.php @@ -0,0 +1,60 @@ +rules = new BuildingRules($config); + } + + /** Output share at staffing ratio r: e^(k·(r−1)). Full is 1, empty about 0.1. */ + public function staffingFactor(float $ratio): float + { + return exp($this->config->get('economy.staffing.k', 2.3) * (min(1.0, max(0.0, $ratio)) - 1)); + } + + /** @return array{resource: string, per_hour: float}|null */ + public function output(BuildingState $building, Workforce $workforce): ?array + { + $output = $this->rules->output($building->type, $building->level); + if (! $output) { + return null; + } + $output['per_hour'] *= $this->staffingFactor($workforce->ratio($building->id)); + + return $output; + } + + /** + * Net change per hour. Food is farm output minus upkeep, so it can go negative. + * + * @param list $buildings + * @return array{wood: float, clay: float, iron: float, food: float} + */ + public function rates(array $buildings, Workforce $workforce): array + { + $rates = array_fill_keys(self::RESOURCES, 0.0); + foreach ($this->config->get('economy.base_production', []) as $resource => $perHour) { + $rates[$resource] += $perHour * $this->config->speed(); + } + foreach ($buildings as $b) { + if ($output = $this->output($b, $workforce)) { + $rates[$output['resource']] += $output['per_hour']; + } + } + $rates['food'] -= $workforce->upkeep; + + return $rates; + } +} diff --git a/app/Game/Economy/Settle.php b/app/Game/Economy/Settle.php new file mode 100644 index 0000000..b2c1459 --- /dev/null +++ b/app/Game/Economy/Settle.php @@ -0,0 +1,22 @@ + $stored + * @param array $rates per hour + * @return array + */ + public static function advance(array $stored, array $rates, float $cap, float $hours): array + { + $result = []; + foreach ($stored as $resource => $amount) { + $result[$resource] = min($cap, max(0.0, $amount + ($rates[$resource] ?? 0.0) * $hours)); + } + + return $result; + } +} diff --git a/app/Game/Economy/Workforce.php b/app/Game/Economy/Workforce.php new file mode 100644 index 0000000..86a577b --- /dev/null +++ b/app/Game/Economy/Workforce.php @@ -0,0 +1,32 @@ + $assigned building id => villagers working there + * @param array $required building id => villagers it needs + */ + public function __construct( + public readonly float $foodBudget, + public readonly int $villagers, + public readonly float $upkeep, + public readonly array $assigned, + public readonly array $required, + ) {} + + public function workers(): int + { + return array_sum($this->assigned); + } + + /** Staffing ratio 0..1; a building that needs nobody counts as fully staffed. */ + public function ratio(int $buildingId): float + { + $required = $this->required[$buildingId] ?? 0; + + return $required === 0 ? 1.0 : ($this->assigned[$buildingId] ?? 0) / $required; + } +} diff --git a/app/Game/GameRuleViolation.php b/app/Game/GameRuleViolation.php new file mode 100644 index 0000000..0bb79c9 --- /dev/null +++ b/app/Game/GameRuleViolation.php @@ -0,0 +1,15 @@ +), the message is a fallback for people reading logs. + */ +final class GameRuleViolation extends \RuntimeException +{ + public function __construct(public readonly string $reason, ?string $message = null) + { + parent::__construct($message ?? $reason); + } +} diff --git a/app/Game/WorldConfig.php b/app/Game/WorldConfig.php new file mode 100644 index 0000000..3fc7cff --- /dev/null +++ b/app/Game/WorldConfig.php @@ -0,0 +1,57 @@ + $values */ + private function __construct(private readonly array $values) {} + + /** + * @param array $defaults keyed by file: world, economy, buildings + * @param array $overrides the same shape, e.g. ['world' => ['speed' => 100]] + */ + public static function make(array $defaults, array $overrides = []): self + { + return new self(array_replace_recursive($defaults, $overrides)); + } + + public function get(string $key, mixed $default = null): mixed + { + return Arr::get($this->values, $key, $default); + } + + public function speed(): float + { + return (float) $this->get('world.speed', 1.0); + } + + /** @return list */ + public function buildingTypes(): array + { + return array_keys($this->get('buildings', [])); + } + + public function hasBuilding(string $type): bool + { + return array_key_exists($type, $this->get('buildings', [])); + } + + /** @return array */ + public function building(string $type): array + { + return $this->get("buildings.$type") ?? throw new \InvalidArgumentException("Unknown building type [$type]."); + } + + /** @return array */ + public function toArray(): array + { + return $this->values; + } +} diff --git a/config/game/buildings.php b/config/game/buildings.php new file mode 100644 index 0000000..dc354db --- /dev/null +++ b/config/game/buildings.php @@ -0,0 +1,110 @@ + [ + 'footprint' => [3, 3], + 'max_per_village' => 1, + 'max_level' => 30, + 'cost' => ['wood' => 90, 'clay' => 80, 'iron' => 70, 'factor' => 1.26], + 'build_time' => ['base' => 120, 'factor' => 1.2], + 'workers' => ['base' => 2, 'factor' => 1.1], + 'production' => null, + 'instance_cost_factor' => 1.0, + 'requires' => [], + ], + 'storage' => [ + 'footprint' => [2, 2], + 'max_per_village' => null, + 'max_level' => 30, + 'cost' => ['wood' => 60, 'clay' => 50, 'iron' => 40, 'factor' => 1.27], + 'build_time' => ['base' => 100, 'factor' => 1.2], + 'workers' => ['base' => 1, 'factor' => 1.1], + 'production' => null, + 'capacity' => ['base' => 1000, 'factor' => 1.23], + 'instance_cost_factor' => 1.5, + 'requires' => [], + ], + 'farm' => [ + 'footprint' => [2, 2], + 'max_per_village' => null, + 'max_level' => 30, + 'cost' => ['wood' => 45, 'clay' => 40, 'iron' => 30, 'factor' => 1.27], + 'build_time' => ['base' => 120, 'factor' => 1.2], + 'workers' => ['base' => 2, 'factor' => 1.1], + 'production' => ['resource' => 'food', 'base' => 30, 'factor' => 1.17], + 'instance_cost_factor' => 1.5, + 'requires' => [], + ], + 'timber_camp' => [ + 'footprint' => [2, 2], + 'max_per_village' => null, + 'max_level' => 30, + 'cost' => ['wood' => 50, 'clay' => 60, 'iron' => 40, 'factor' => 1.25], + 'build_time' => ['base' => 90, 'factor' => 1.2], + 'workers' => ['base' => 2, 'factor' => 1.12], + 'production' => ['resource' => 'wood', 'base' => 30, 'factor' => 1.163], + 'instance_cost_factor' => 1.5, + 'requires' => [], + ], + 'clay_pit' => [ + 'footprint' => [2, 2], + 'max_per_village' => null, + 'max_level' => 30, + 'cost' => ['wood' => 65, 'clay' => 50, 'iron' => 40, 'factor' => 1.27], + 'build_time' => ['base' => 90, 'factor' => 1.2], + 'workers' => ['base' => 2, 'factor' => 1.12], + 'production' => ['resource' => 'clay', 'base' => 30, 'factor' => 1.163], + 'instance_cost_factor' => 1.5, + 'requires' => [], + ], + 'iron_mine' => [ + 'footprint' => [2, 2], + 'max_per_village' => null, + 'max_level' => 30, + 'cost' => ['wood' => 75, 'clay' => 65, 'iron' => 70, 'factor' => 1.252], + 'build_time' => ['base' => 110, 'factor' => 1.2], + 'workers' => ['base' => 2, 'factor' => 1.12], + 'production' => ['resource' => 'iron', 'base' => 30, 'factor' => 1.163], + 'instance_cost_factor' => 1.5, + 'requires' => [], + ], + 'hiding_place' => [ + 'footprint' => [1, 1], + 'max_per_village' => null, + 'max_level' => 10, + 'cost' => ['wood' => 50, 'clay' => 60, 'iron' => 50, 'factor' => 1.25], + 'build_time' => ['base' => 60, 'factor' => 1.2], + 'workers' => ['base' => 0, 'factor' => 1.0], + 'production' => null, + 'instance_cost_factor' => 1.5, + 'requires' => [], + ], + 'wall' => [ + // Surrounds the village and takes no cells. + 'footprint' => [0, 0], + 'max_per_village' => 1, + 'max_level' => 20, + 'cost' => ['wood' => 50, 'clay' => 100, 'iron' => 20, 'factor' => 1.26], + 'build_time' => ['base' => 300, 'factor' => 1.2], + 'workers' => ['base' => 1, 'factor' => 1.1], + 'production' => null, + 'instance_cost_factor' => 1.0, + 'requires' => ['headquarters' => 1], + ], + 'rally_point' => [ + 'footprint' => [1, 1], + 'max_per_village' => 1, + 'max_level' => 1, + 'cost' => ['wood' => 10, 'clay' => 40, 'iron' => 30, 'factor' => 1.26], + 'build_time' => ['base' => 60, 'factor' => 1.2], + 'workers' => ['base' => 0, 'factor' => 1.0], + 'production' => null, + 'instance_cost_factor' => 1.0, + 'requires' => [], + ], +]; diff --git a/config/game/economy.php b/config/game/economy.php new file mode 100644 index 0000000..977f100 --- /dev/null +++ b/config/game/economy.php @@ -0,0 +1,19 @@ + ['wood' => 5, 'clay' => 5, 'iron' => 5], + + // Food per hour each villager eats. + 'upkeep' => ['villager' => 1], + + // Output at staffing ratio r is e^(k·(r−1)): 100% full, about 10% empty. + 'staffing' => ['k' => 2.3], + + // Share of a level's cost refunded when it is demolished, and its build time spent doing so. + 'demolish_refund' => 0.5, + 'demolish_time_factor' => 0.5, + + // Each headquarters level makes building this much faster (time / (1 + x·level)). + 'hq_build_speed_per_level' => 0.05, +]; diff --git a/config/game/world.php b/config/game/world.php new file mode 100644 index 0000000..6d058c0 --- /dev/null +++ b/config/game/world.php @@ -0,0 +1,25 @@ + 1.0, + + 'village' => [ + 'grid' => [10, 5], + 'start_resources' => ['wood' => 500, 'clay' => 500, 'iron' => 500, 'food' => 300], + // Auto-placed at level 0 in this order. + 'start_buildings' => ['headquarters', 'storage', 'farm'], + ], + + 'builders' => [ + 'base' => 2, + // One more builder from each of these headquarters levels on. + 'extra_at_hq_levels' => [10, 20], + ], + + 'map' => [ + 'size' => 1000, + ], +]; diff --git a/tests/Pest.php b/tests/Pest.php new file mode 100644 index 0000000..1118df1 --- /dev/null +++ b/tests/Pest.php @@ -0,0 +1,63 @@ +extend(TestCase::class)->use(RefreshDatabase::class)->in('Feature'); + +/** The default game config without booting Laravel, so unit tests stay pure. */ +function gameConfig(array $overrides = []): WorldConfig +{ + $dir = __DIR__.'/../config/game'; + + return WorldConfig::make([ + 'world' => require "$dir/world.php", + 'economy' => require "$dir/economy.php", + 'buildings' => require "$dir/buildings.php", + ], $overrides); +} + +function building(int $id, string $type, int $level = 0, int $priority = 5): BuildingState +{ + return new BuildingState($id, $type, $level, $priority); +} + +/** A user with a fresh start village in World 1 (speed 1). */ +function startVillage(?User $user = null): Village +{ + (new WorldSeeder)->run(); + + return app(JoinWorld::class)($user ?? User::factory()->create(), World::where('slug', 'w1')->value('id')); +} + +function owner(Village $village): User +{ + return $village->player->user; +} + +/** The client payload, as `village.show` would send it now. */ +function shown(Village $village): array +{ + return VillagePresenter::present(app(ShowVillage::class)(owner($village), $village->id), now()->toImmutable()); +} + +function rule(Closure $intent): string +{ + try { + $intent(); + } catch (GameRuleViolation $e) { + return $e->reason; + } + + throw new RuntimeException('Expected a GameRuleViolation.'); +} diff --git a/tests/Unit/Game/BuildQueueTest.php b/tests/Unit/Game/BuildQueueTest.php new file mode 100644 index 0000000..6472860 --- /dev/null +++ b/tests/Unit/Game/BuildQueueTest.php @@ -0,0 +1,26 @@ + ['id' => $id, 'building_id' => $building, 'builder' => $builder]; + +it('starts as many waiting orders as there are free builders', function () use ($order) { + expect(BuildQueue::startable([$order(1), $order(2), $order(3)], 2))->toBe([1 => 1, 2 => 2]); +}); + +it('fills the builder slot that is free', function () use ($order) { + expect(BuildQueue::startable([$order(1, builder: 2), $order(2)], 2))->toBe([2 => 1]); +}); + +it('skips an order blocked by an earlier order on the same building', function () use ($order) { + // Order 2 upgrades the same building as running order 1, so order 3 goes first. + expect(BuildQueue::startable([$order(1, 7, builder: 1), $order(2, 7), $order(3, 8)], 2))->toBe([3 => 2]); +}); + +it('keeps two waiting orders on one building in sequence', function () use ($order) { + expect(BuildQueue::startable([$order(1, 7), $order(2, 7), $order(3)], 2))->toBe([1 => 1, 3 => 2]); +}); + +it('starts nothing when every builder is busy', function () use ($order) { + expect(BuildQueue::startable([$order(1, builder: 1), $order(2, builder: 2), $order(3)], 2))->toBe([]); +}); diff --git a/tests/Unit/Game/BuildingRulesTest.php b/tests/Unit/Game/BuildingRulesTest.php new file mode 100644 index 0000000..462f10e --- /dev/null +++ b/tests/Unit/Game/BuildingRulesTest.php @@ -0,0 +1,68 @@ +cost('timber_camp', 0))->toBe(['wood' => 50, 'clay' => 60, 'iron' => 40]) + ->and($rules->cost('timber_camp', 2))->toBe([ + 'wood' => (int) round(50 * 1.25 ** 2), + 'clay' => (int) round(60 * 1.25 ** 2), + 'iron' => (int) round(40 * 1.25 ** 2), + ]); +}); + +it('makes later instances of a type more expensive', function () { + $rules = new BuildingRules(gameConfig()); + + expect($rules->cost('farm', 0, 1))->toBe(['wood' => 68, 'clay' => 60, 'iron' => 45]) + ->and($rules->cost('headquarters', 0, 3))->toBe($rules->cost('headquarters', 0)); +}); + +it('divides build time by world speed, headquarters level and staffing', function () { + $rules = new BuildingRules(gameConfig()); + $fast = new BuildingRules(gameConfig(['world' => ['speed' => 100]])); + + expect($rules->buildSeconds('timber_camp', 0, 0, 1.0))->toBe(90) + ->and($rules->buildSeconds('timber_camp', 1, 0, 1.0))->toBe(108) + ->and($rules->buildSeconds('timber_camp', 0, 10, 1.0))->toBe(60) + ->and($rules->buildSeconds('timber_camp', 0, 0, 0.5))->toBe(180) + ->and($fast->buildSeconds('timber_camp', 0, 0, 1.0))->toBe(1); +}); + +it('takes half the time and refunds half the cost when demolishing', function () { + $rules = new BuildingRules(gameConfig()); + + expect($rules->demolishSeconds('timber_camp', 1, 0, 1.0))->toBe(54) + ->and($rules->demolishRefund('timber_camp', 0))->toBe(['wood' => 25, 'clay' => 30, 'iron' => 20]); +}); + +it('rounds workers and scales output with world speed', function () { + $rules = new BuildingRules(gameConfig()); + $fast = new BuildingRules(gameConfig(['world' => ['speed' => 2]])); + + expect($rules->workers('timber_camp', 0))->toBe(2) + ->and($rules->workers('timber_camp', 10))->toBe((int) round(2 * 1.12 ** 10)) + ->and($rules->workers('hiding_place', 5))->toBe(0) + ->and($rules->output('timber_camp', 0))->toBe(['resource' => 'wood', 'per_hour' => 30.0]) + ->and($fast->output('farm', 0))->toBe(['resource' => 'food', 'per_hour' => 60.0]) + ->and($rules->output('storage', 3))->toBeNull(); +}); + +it('gives storage capacity only to storage', function () { + $rules = new BuildingRules(gameConfig()); + + expect($rules->capacity('storage', 0))->toBe(1000.0) + ->and($rules->capacity('storage', 1))->toBe(1230.0) + ->and($rules->capacity('farm', 1))->toBe(0.0); +}); + +it('adds builders at the configured headquarters levels', function () { + $rules = new BuildingRules(gameConfig()); + + expect($rules->builders(0))->toBe(2) + ->and($rules->builders(9))->toBe(2) + ->and($rules->builders(10))->toBe(3) + ->and($rules->builders(20))->toBe(4); +}); diff --git a/tests/Unit/Game/ConfigLintTest.php b/tests/Unit/Game/ConfigLintTest.php new file mode 100644 index 0000000..3305fed --- /dev/null +++ b/tests/Unit/Game/ConfigLintTest.php @@ -0,0 +1,40 @@ +toBe([]); +}); + +it('finds no locks in the dev world', function () { + expect(ConfigLint::check(gameConfig(['world' => ['speed' => 100]])))->toBe([]); +}); + +it('reports a farm whose workers eat more than it makes', function () { + $config = gameConfig(['buildings' => ['farm' => ['workers' => ['base' => 40]]]]); + + expect(ConfigLint::check($config))->toContain('[farm] level 0 feeds fewer people than it needs as workers.'); +}); + +it('reports a storage level that its predecessor cannot pay for', function () { + $config = gameConfig(['buildings' => ['storage' => ['cost' => ['wood' => 2000]]]]); + + expect(ConfigLint::check($config))->toContain('[storage] level 1 costs more than level 0 holds.'); +}); + +it('reports requirement cycles and unknown requirements', function () { + $config = gameConfig(['buildings' => [ + 'wall' => ['requires' => ['rally_point' => 1]], + 'rally_point' => ['requires' => ['wall' => 1, 'castle' => 1]], + ]]); + + expect(ConfigLint::check($config)) + ->toContain('[rally_point] requires unknown type [castle].') + ->toContain('Requirement cycle through [wall].'); +}); + +it('reports start buildings that do not fit the grid', function () { + $config = gameConfig(['world' => ['village' => ['grid' => [3, 3]]]]); + + expect(ConfigLint::check($config))->toContain('Start building [storage] does not fit the 3x3 grid.'); +}); diff --git a/tests/Unit/Game/PopulationTest.php b/tests/Unit/Game/PopulationTest.php new file mode 100644 index 0000000..82c8584 --- /dev/null +++ b/tests/Unit/Game/PopulationTest.php @@ -0,0 +1,52 @@ +workforce([building(1, 'farm'), building(2, 'farm', 1)]); + + expect($workforce->foodBudget)->toBe(30 + 30 * 1.17) + ->and($workforce->villagers)->toBe(65) + ->and($workforce->upkeep)->toEqual(65); +}); + +it('leaves soldiers upkeep out of the villagers budget', function () { + $workforce = (new Population(gameConfig()))->workforce([building(1, 'farm')], soldierUpkeep: 10); + + expect($workforce->villagers)->toBe(20) + ->and($workforce->upkeep)->toEqual(30); +}); + +it('staffs farms first, then by priority', function () { + // Farm 0 makes 30 food, so 30 villagers: the farm takes 2, priority 9 the other 28. + $buildings = [ + building(1, 'timber_camp', 30, priority: 1), + building(2, 'clay_pit', 30, priority: 9), + building(3, 'farm', 0, priority: 0), + ]; + $workforce = (new Population(gameConfig()))->workforce($buildings); + + expect($workforce->assigned)->toBe([1 => 0, 2 => 28, 3 => 2]) + ->and($workforce->workers())->toBe(30); +}); + +it('splits villagers evenly between buildings of equal priority', function () { + // 30 villagers: farm takes 2, the two level-20 camps (19 each) share 28. + $buildings = [ + building(1, 'farm'), + building(2, 'timber_camp', 20), + building(3, 'clay_pit', 20), + ]; + $workforce = (new Population(gameConfig()))->workforce($buildings); + + expect($workforce->assigned)->toBe([1 => 2, 2 => 14, 3 => 14]) + ->and($workforce->ratio(2))->toBe(14 / 19); +}); + +it('counts buildings that need nobody as fully staffed', function () { + $workforce = (new Population(gameConfig()))->workforce([building(1, 'hiding_place')]); + + expect($workforce->villagers)->toBe(0) + ->and($workforce->ratio(1))->toBe(1.0); +}); diff --git a/tests/Unit/Game/ProductionTest.php b/tests/Unit/Game/ProductionTest.php new file mode 100644 index 0000000..cd71925 --- /dev/null +++ b/tests/Unit/Game/ProductionTest.php @@ -0,0 +1,46 @@ +staffingFactor(1.0))->toBe(1.0) + ->and($production->staffingFactor(0.0))->toEqualWithDelta(0.1, 0.001) + ->and($production->staffingFactor(0.5))->toEqualWithDelta(exp(-1.15), 1e-9); +}); + +it('adds buildings to the base trickle and nets food against upkeep', function () { + $config = gameConfig(); + $buildings = [building(1, 'headquarters'), building(2, 'storage'), building(3, 'farm'), building(4, 'timber_camp')]; + $workforce = (new Population($config))->workforce($buildings); + $rates = (new Production($config))->rates($buildings, $workforce); + + expect($rates['wood'])->toBe(5.0 + 30.0) + ->and($rates['clay'])->toBe(5.0) + ->and($rates['iron'])->toBe(5.0) + ->and($rates['food'])->toBe(0.0); +}); + +it('makes less in an understaffed building', function () { + $config = gameConfig(); + // 30 villagers for a timber camp needing round(2 × 1.12^30) = 60. + $buildings = [building(1, 'farm'), building(2, 'timber_camp', 30)]; + $workforce = (new Population($config))->workforce($buildings); + $production = new Production($config); + + $ratio = 28 / 60; + expect($workforce->ratio(2))->toBe($ratio) + ->and($production->output($buildings[1], $workforce)['per_hour']) + ->toEqualWithDelta(30 * 1.163 ** 30 * exp(2.3 * ($ratio - 1)), 1e-6); +}); + +it('settles stored amounts by rate and elapsed hours within the cap', function () { + $stored = ['wood' => 100.0, 'clay' => 990.0, 'iron' => 5.0, 'food' => 50.0]; + $rates = ['wood' => 30.0, 'clay' => 30.0, 'iron' => -20.0, 'food' => 0.0]; + + expect(Settle::advance($stored, $rates, 1000.0, 0.5)) + ->toBe(['wood' => 115.0, 'clay' => 1000.0, 'iron' => 0.0, 'food' => 50.0]); +}); diff --git a/tests/Unit/Game/VillageGridTest.php b/tests/Unit/Game/VillageGridTest.php new file mode 100644 index 0000000..76996ab --- /dev/null +++ b/tests/Unit/Game/VillageGridTest.php @@ -0,0 +1,39 @@ +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(); +});