feat: market building with Die Stämme's merchants table, market config and the pure trade rules

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) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-31 10:55:01 +01:00
parent 5a69ce561e
commit b8d5983a63
8 changed files with 360 additions and 0 deletions

View File

@ -160,6 +160,17 @@ final class BuildingRules
return $beds ? $beds['base'] * $beds['factor'] ** self::above($level) : 0.0; 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 * 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' * 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)) { if ($detection = $this->detection($type, $level)) {
$effects[] = ['key' => 'detection', 'value' => round($detection, 1)]; $effects[] = ['key' => 'detection', 'value' => round($detection, 1)];
} }
if ($merchants = $this->merchants($type, $level)) {
$effects[] = ['key' => 'merchants', 'value' => $merchants];
}
if ($type === 'wall') { if ($type === 'wall') {
$wall = $this->config->get('combat.wall'); $wall = $this->config->get('combat.wall');
$effects[] = ['key' => 'wall_defense', 'value' => $wall['basic_defense'] * $level]; $effects[] = ['key' => 'wall_defense', 'value' => $wall['basic_defense'] * $level];

View File

@ -32,9 +32,43 @@ final class ConfigLint
...self::rolesReachable($config), ...self::rolesReachable($config),
...self::crownsHold($config), ...self::crownsHold($config),
...self::woundedHeal($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 * The wounded stand again after a time above 0, and never more of them come back
* than fell: share between 0 and 1. * than fell: share between 0 and 1.

View File

@ -0,0 +1,159 @@
<?php
namespace App\Game\Trade;
use App\Game\Buildings\BuildingRules;
use App\Game\GameRuleViolation;
use App\Game\WorldConfig;
/**
* The market's rules (architecture.md, "Market", config/game/market.php): merchants per
* market level, what one carries, how long they travel, fair offers, and how much a
* trade route sends when the stock or the merchants run short.
*/
final class TradeRules
{
/** The building type whose level gives the merchants. */
public const BUILDING = 'market';
/** Every cargo has these keys; resources the market doesn't trade stay 0. */
public const CARGO = ['wood', 'clay', 'iron'];
public function __construct(private readonly WorldConfig $config) {}
/** Merchants a village has with its market at $level (0 without a market). */
public function merchants(int $level): int
{
return $this->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<string> */
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<string, mixed> $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<string, int> $amounts what the route sends each time
* @param array<string, float> $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;
}
}

View File

@ -37,6 +37,7 @@ class World extends Model
'raids' => config('game.raids'), 'raids' => config('game.raids'),
'tribes' => config('game.tribes'), 'tribes' => config('game.tribes'),
'quests' => config('game.quests'), 'quests' => config('game.quests'),
'market' => config('game.market'),
], $this->config ?? []); ], $this->config ?? []);
} }

View File

@ -205,4 +205,19 @@ return [
'points' => ['base' => 12, 'factor' => 1.2], 'points' => ['base' => 12, 'factor' => 1.2],
'requires' => ['barracks' => 1], '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],
],
]; ];

29
config/game/market.php Normal file
View File

@ -0,0 +1,29 @@
<?php
// The market and its merchants (architecture.md, "Market"). How many merchants a
// village has comes from the market's level (buildings.market.merchants).
return [
// Resources one merchant carries.
'carry' => 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,
],
];

View File

@ -33,6 +33,7 @@ function gameConfig(array $overrides = []): WorldConfig
'raids' => require "$dir/raids.php", 'raids' => require "$dir/raids.php",
'tribes' => require "$dir/tribes.php", 'tribes' => require "$dir/tribes.php",
'quests' => require "$dir/quests.php", 'quests' => require "$dir/quests.php",
'market' => require "$dir/market.php",
], $overrides); ], $overrides);
} }

View File

@ -0,0 +1,107 @@
<?php
use App\Game\Buildings\BuildingRules;
use App\Game\ConfigLint;
use App\Game\GameRuleViolation;
use App\Game\Trade\TradeRules;
use App\Game\WorldConfig;
it('gives a market its merchants per level from the table, none without a market', function () {
$trade = new TradeRules(gameConfig());
expect($trade->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.');
});