From b8d5983a6381a6397af5792f5fcc1a55b8263b15 Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Sat, 31 Oct 2026 10:55:01 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20market=20building=20with=20Die=20St?= =?UTF-8?q?=C3=A4mme's=20merchants=20table,=20market=20config=20and=20the?= =?UTF-8?q?=20pure=20trade=20rules?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit TradeRules: merchants per level, merchants a shipment needs, travel seconds, fair offers, route intervals and route cargo scaled to the free merchants. ConfigLint checks the merchants table, carry, pace, ratio and route bounds. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/Game/Buildings/BuildingRules.php | 14 +++ app/Game/ConfigLint.php | 34 ++++++ app/Game/Trade/TradeRules.php | 159 +++++++++++++++++++++++++++ app/Models/World.php | 1 + config/game/buildings.php | 15 +++ config/game/market.php | 29 +++++ tests/Pest.php | 1 + tests/Unit/Game/TradeTest.php | 107 ++++++++++++++++++ 8 files changed, 360 insertions(+) create mode 100644 app/Game/Trade/TradeRules.php create mode 100644 config/game/market.php create mode 100644 tests/Unit/Game/TradeTest.php diff --git a/app/Game/Buildings/BuildingRules.php b/app/Game/Buildings/BuildingRules.php index b4ff2d5..1751862 100644 --- a/app/Game/Buildings/BuildingRules.php +++ b/app/Game/Buildings/BuildingRules.php @@ -160,6 +160,17 @@ final class BuildingRules return $beds ? $beds['base'] * $beds['factor'] ** self::above($level) : 0.0; } + /** Merchants this building has at a level (market, from its table; staffing doesn't scale it), else 0. */ + public function merchants(string $type, int $level): int + { + $merchants = $this->config->building($type)['merchants'] ?? null; + if (! $merchants || $level < 1) { + return 0; + } + + return (int) $merchants[min($level, count($merchants)) - 1]; + } + /** * What one instance does at a level, for the building's own screen: production at * full staffing, storage, hiding, beds, detection, the wall's defence, the headquarters' @@ -184,6 +195,9 @@ final class BuildingRules if ($detection = $this->detection($type, $level)) { $effects[] = ['key' => 'detection', 'value' => round($detection, 1)]; } + if ($merchants = $this->merchants($type, $level)) { + $effects[] = ['key' => 'merchants', 'value' => $merchants]; + } if ($type === 'wall') { $wall = $this->config->get('combat.wall'); $effects[] = ['key' => 'wall_defense', 'value' => $wall['basic_defense'] * $level]; diff --git a/app/Game/ConfigLint.php b/app/Game/ConfigLint.php index e206b84..95266ba 100644 --- a/app/Game/ConfigLint.php +++ b/app/Game/ConfigLint.php @@ -32,9 +32,43 @@ final class ConfigLint ...self::rolesReachable($config), ...self::crownsHold($config), ...self::woundedHeal($config), + ...self::merchantsTravel($config, $rules), ]; } + /** + * Every market level has merchants, they carry something and get somewhere, offers can + * be fair, and routes run at a pace that exists. The market's requirements are checked + * with every other building's. + */ + private static function merchantsTravel(WorldConfig $config, BuildingRules $rules): array + { + $problems = []; + foreach ($config->buildingTypes() as $type) { + $merchants = $config->building($type)['merchants'] ?? null; + if ($merchants === null) { + continue; + } + if (! is_array($merchants) || count($merchants) !== $rules->maxLevel($type)) { + $problems[] = "[$type.merchants] must list one number per level, {$rules->maxLevel($type)} in all."; + } elseif (min($merchants) < 1) { + $problems[] = "[$type.merchants] must give every level at least 1 merchant."; + } + } + if ($config->get('market.carry', 0) <= 0 || $config->get('market.minutes_per_field', 0) <= 0) { + $problems[] = '[market.carry] and [market.minutes_per_field] must be above 0, or merchants carry nothing or never arrive.'; + } + if ($config->get('market.max_ratio', 0) < 1) { + $problems[] = '[market.max_ratio] must be at least 1, or no offer is fair enough.'; + } + $min = $config->get('market.route.min_every', 0); + if ($min <= 0 || $min > $config->get('market.route.max_every', 0)) { + $problems[] = '[market.route.min_every] must be above 0 and at most [market.route.max_every].'; + } + + return $problems; + } + /** * The wounded stand again after a time above 0, and never more of them come back * than fell: share between 0 and 1. diff --git a/app/Game/Trade/TradeRules.php b/app/Game/Trade/TradeRules.php new file mode 100644 index 0000000..a4fc3fb --- /dev/null +++ b/app/Game/Trade/TradeRules.php @@ -0,0 +1,159 @@ +config->hasBuilding(self::BUILDING) ? (new BuildingRules($this->config))->merchants(self::BUILDING, $level) : 0; + } + + /** Merchants that are neither under way nor reserved by open offers. */ + public static function free(int $merchants, int $busy): int + { + return max(0, $merchants - $busy); + } + + /** Resources one merchant carries. */ + public function carry(): int + { + return (int) $this->config->get('market.carry', 1000); + } + + /** Merchants a shipment of $amount resources needs. */ + public function needed(int $amount): int + { + return $amount > 0 ? (int) ceil($amount / max(1, $this->carry())) : 0; + } + + public function minutesPerField(): float + { + return (float) $this->config->get('market.minutes_per_field', 6); + } + + /** Seconds merchants take for $distance fields, sped up by the world and unit speed like troops. */ + public function seconds(float $distance): int + { + $pace = $this->config->speed() * $this->config->get('movement.unit_speed', 1.0); + + return max(1, (int) round($this->minutesPerField() * $distance * 60 / $pace)); + } + + /** @return list */ + public function resources(): array + { + return array_values(array_intersect($this->config->get('market.resources', []), self::CARGO)); + } + + public function maxRatio(): float + { + return (float) $this->config->get('market.max_ratio', 1); + } + + public function minEvery(): int + { + return (int) $this->config->get('market.route.min_every', 600); + } + + public function maxEvery(): int + { + return (int) $this->config->get('market.route.max_every', 604800); + } + + public function maxRoutes(): int + { + return (int) $this->config->get('market.route.max_routes', 0); + } + + /** + * The traded resources the player asked for, whole and not negative, as a full cargo. + * + * @param array $amounts + * @return array{wood: int, clay: int, iron: int} + */ + public function cargo(array $amounts): array + { + $traded = $this->resources(); + $cargo = []; + foreach (self::CARGO as $resource) { + $cargo[$resource] = in_array($resource, $traded, true) ? max(0, (int) ($amounts[$resource] ?? 0)) : 0; + } + + return $cargo; + } + + /** + * An offer gives $count times $giveAmount of one traded resource for $wantAmount of + * another, asking at most max_ratio times what it gives and giving at most max_ratio + * times what it asks. + */ + public function checkOffer(string $give, int $giveAmount, string $want, int $wantAmount, int $count): void + { + $traded = $this->resources(); + if (! in_array($give, $traded, true) || ! in_array($want, $traded, true)) { + throw new GameRuleViolation('not_found', 'The market doesn\'t trade that.'); + } + if ($give === $want) { + throw new GameRuleViolation('same_resource', 'Trade one resource for another.'); + } + if ($giveAmount < 1 || $wantAmount < 1) { + throw new GameRuleViolation('amount', 'Give and ask for at least 1.'); + } + if ($count < 1) { + throw new GameRuleViolation('count', 'Offer it at least once.'); + } + $ratio = $this->maxRatio(); + if ($wantAmount > $ratio * $giveAmount || $giveAmount > $ratio * $wantAmount) { + throw new GameRuleViolation('ratio', 'That offer is too lopsided.'); + } + } + + public function checkEvery(int $every): void + { + if ($every < $this->minEvery() || $every > $this->maxEvery()) { + throw new GameRuleViolation('every', 'A route runs between '.$this->minEvery().' and '.$this->maxEvery().' seconds apart.'); + } + } + + /** + * What one run of a trade route sends: of each resource what the route asks for, as + * far as the stock has it, scaled down evenly to what the free merchants carry. + * + * @param array $amounts what the route sends each time + * @param array $stock + * @return array{wood: int, clay: int, iron: int} + */ + public function routeCargo(array $amounts, array $stock, int $freeMerchants): array + { + $cargo = $this->cargo($amounts); + foreach ($cargo as $resource => $amount) { + $cargo[$resource] = min($amount, max(0, (int) floor($stock[$resource] ?? 0))); + } + $total = array_sum($cargo); + $capacity = max(0, $freeMerchants) * $this->carry(); + if ($total > $capacity) { + $cargo = array_map(fn (int $n) => (int) floor($n * $capacity / $total), $cargo); + } + + return $cargo; + } +} diff --git a/app/Models/World.php b/app/Models/World.php index ff82d61..e461ea5 100644 --- a/app/Models/World.php +++ b/app/Models/World.php @@ -37,6 +37,7 @@ class World extends Model 'raids' => config('game.raids'), 'tribes' => config('game.tribes'), 'quests' => config('game.quests'), + 'market' => config('game.market'), ], $this->config ?? []); } diff --git a/config/game/buildings.php b/config/game/buildings.php index 537d7f3..825dc61 100644 --- a/config/game/buildings.php +++ b/config/game/buildings.php @@ -205,4 +205,19 @@ return [ 'points' => ['base' => 12, 'factor' => 1.2], 'requires' => ['barracks' => 1], ], + // The market: its merchants carry resources to other villages (config/game/market.php). + // `merchants` per level, Die Stämme's table; staffing doesn't scale it. + 'market' => [ + 'space' => 4, + 'max_per_village' => 1, + 'max_level' => 25, + 'cost' => ['wood' => 100, 'clay' => 100, 'iron' => 100, 'factor' => 1.26], + 'build_time' => ['base' => 2700, 'factor' => 1.2], + 'workers' => ['base' => 1, 'factor' => 1.1], + 'production' => null, + 'merchants' => [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14, 19, 26, 35, 46, 59, 74, 91, 110, 131, 154, 179, 206, 235], + 'instance_cost_factor' => 1.0, + 'points' => ['base' => 10, 'factor' => 1.2], + 'requires' => ['headquarters' => 3, 'storage' => 2], + ], ]; diff --git a/config/game/market.php b/config/game/market.php new file mode 100644 index 0000000..341d25c --- /dev/null +++ b/config/game/market.php @@ -0,0 +1,29 @@ + 1000, + + // Minutes a merchant takes per field at world speed 1. Like a unit's speed, divided + // by the world speed and movement.unit_speed; travel modes don't apply. + 'minutes_per_field' => 6, + + // What the market trades. Food is not traded yet. + 'resources' => ['wood', 'clay', 'iron'], + + // An offer may ask at most max_ratio times what it gives, and give at most + // max_ratio times what it asks. + 'max_ratio' => 3, + + // Trade routes repeat a shipment every `every` seconds, between min_every and + // max_every. Real seconds, not divided by the world speed: routes run on the + // player's clock. max_routes per village. + 'route' => [ + 'min_every' => 600, + 'max_every' => 604800, + 'max_routes' => 10, + ], +]; diff --git a/tests/Pest.php b/tests/Pest.php index b00c75f..d11ca6e 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -33,6 +33,7 @@ function gameConfig(array $overrides = []): WorldConfig 'raids' => require "$dir/raids.php", 'tribes' => require "$dir/tribes.php", 'quests' => require "$dir/quests.php", + 'market' => require "$dir/market.php", ], $overrides); } diff --git a/tests/Unit/Game/TradeTest.php b/tests/Unit/Game/TradeTest.php new file mode 100644 index 0000000..35fdabe --- /dev/null +++ b/tests/Unit/Game/TradeTest.php @@ -0,0 +1,107 @@ +merchants(0))->toBe(0) + ->and($trade->merchants(1))->toBe(1) + ->and($trade->merchants(11))->toBe(11) + ->and($trade->merchants(12))->toBe(14) + ->and($trade->merchants(25))->toBe(235) + ->and(TradeRules::free(5, 3))->toBe(2) + ->and(TradeRules::free(2, 3))->toBe(0); +}); + +it('shows the merchants among the market effects', function () { + $rules = new BuildingRules(gameConfig()); + + expect($rules->effects('market', 12))->toContain(['key' => 'merchants', 'value' => 14]) + ->and(collect($rules->effects('storage', 3))->pluck('key'))->not->toContain('merchants'); +}); + +it('counts the merchants a shipment needs', function () { + $trade = new TradeRules(gameConfig()); + + expect($trade->needed(0))->toBe(0) + ->and($trade->needed(1))->toBe(1) + ->and($trade->needed(1000))->toBe(1) + ->and($trade->needed(1001))->toBe(2) + ->and($trade->needed(4500))->toBe(5); +}); + +it('moves merchants at their minutes per field, sped up by world and unit speed', function () { + expect((new TradeRules(gameConfig()))->seconds(5))->toBe(1800) + ->and((new TradeRules(gameConfig()))->seconds(2.5))->toBe(900) + ->and((new TradeRules(gameConfig(['world' => ['speed' => 100]])))->seconds(5))->toBe(18) + ->and((new TradeRules(gameConfig(['world' => ['speed' => 2], 'movement' => ['unit_speed' => 0.5]])))->seconds(5))->toBe(1800) + ->and((new TradeRules(gameConfig()))->seconds(0.001))->toBe(1); +}); + +it('keeps only traded resources in a cargo, whole and not negative', function () { + expect((new TradeRules(gameConfig()))->cargo(['wood' => '120', 'clay' => -5, 'food' => 300]))->toBe(['wood' => 120, 'clay' => 0, 'iron' => 0]) + ->and((new TradeRules(WorldConfig::make(['market' => ['resources' => ['wood']]])))->cargo(['wood' => 1, 'iron' => 1]))->toBe(['wood' => 1, 'clay' => 0, 'iron' => 0]); +}); + +it('sends on a route what the stock has, scaled down evenly to the free merchants', function () { + $trade = new TradeRules(gameConfig()); + + // Enough of everything. + expect($trade->routeCargo(['wood' => 500, 'clay' => 300, 'iron' => 0], ['wood' => 900.5, 'clay' => 900, 'iron' => 900], 1)) + ->toBe(['wood' => 500, 'clay' => 300, 'iron' => 0]) + // Clay runs short: 500 of it; then 3500 > 2 merchants' 2000, scaled by 4/7. + ->and($trade->routeCargo(['wood' => 3000, 'clay' => 1000, 'iron' => 0], ['wood' => 5000, 'clay' => 500.9, 'iron' => 100], 2)) + ->toBe(['wood' => 1714, 'clay' => 285, 'iron' => 0]) + ->and($trade->routeCargo(['wood' => 3000, 'clay' => 0, 'iron' => 0], ['wood' => 5000, 'clay' => 0, 'iron' => 0], 0)) + ->toBe(['wood' => 0, 'clay' => 0, 'iron' => 0]) + ->and($trade->routeCargo(['wood' => 3000, 'clay' => 0, 'iron' => 0], ['wood' => 0.7, 'clay' => 0, 'iron' => 0], 5)) + ->toBe(['wood' => 0, 'clay' => 0, 'iron' => 0]); +}); + +it('takes offers up to the ratio, of two different traded resources', function () { + $trade = new TradeRules(gameConfig()); + $offer = function (string $give, int $giveAmount, string $want, int $wantAmount, int $count = 1) use ($trade) { + try { + $trade->checkOffer($give, $giveAmount, $want, $wantAmount, $count); + + return 'ok'; + } catch (GameRuleViolation $e) { + return $e->reason; + } + }; + + expect($offer('wood', 100, 'clay', 300))->toBe('ok') + ->and($offer('wood', 300, 'clay', 100))->toBe('ok') + ->and($offer('wood', 100, 'clay', 301))->toBe('ratio') + ->and($offer('wood', 301, 'clay', 100))->toBe('ratio') + ->and($offer('wood', 100, 'wood', 100))->toBe('same_resource') + ->and($offer('wood', 100, 'food', 100))->toBe('not_found') + ->and($offer('wood', 0, 'clay', 100))->toBe('amount') + ->and($offer('wood', 100, 'clay', 100, 0))->toBe('count'); +}); + +it('keeps routes between their shortest and longest interval', function () { + $trade = new TradeRules(gameConfig()); + $trade->checkEvery(600); + $trade->checkEvery(604800); + + expect(fn () => $trade->checkEvery(599))->toThrow(GameRuleViolation::class) + ->and(fn () => $trade->checkEvery(604801))->toThrow(GameRuleViolation::class); +}); + +it('lints merchants that are missing a level, carry nothing or routes that never run', function () { + $short = gameConfig(['buildings' => ['market' => ['max_level' => 26]]]); + $zero = gameConfig(['buildings' => ['market' => ['merchants' => [0]]]]); + $market = gameConfig(['market' => ['carry' => 0, 'max_ratio' => 0.5, 'route' => ['min_every' => 700, 'max_every' => 600]]]); + + expect(ConfigLint::check($short))->toContain('[market.merchants] must list one number per level, 26 in all.') + ->and(ConfigLint::check($zero))->toContain('[market.merchants] must give every level at least 1 merchant.') + ->and(ConfigLint::check($market))->toHaveCount(3) + ->and(ConfigLint::check(gameConfig(['buildings' => ['market' => ['requires' => ['academy' => 9]]]]))) + ->toContain('[market] requires [academy] level 9, above its max level.'); +});