feat: combat, travel and loot rules: TravelTime, CombatResolver, LootCalculator, watchtower and hiding place values

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-28 23:56:55 +01:00
parent 8877c6f505
commit 6a1486b9de
12 changed files with 532 additions and 4 deletions

View File

@ -99,6 +99,22 @@ final class BuildingRules
return $capacity ? $capacity['base'] * $capacity['factor'] ** self::above($level) : 0.0; return $capacity ? $capacity['base'] * $capacity['factor'] ** self::above($level) : 0.0;
} }
/** Wood, clay and iron each this building keeps from raiders (hiding place), else 0. */
public function hides(string $type, int $level): float
{
$hides = $this->config->building($type)['hides'] ?? null;
return $hides ? $hides['base'] * $hides['factor'] ** self::above($level) : 0.0;
}
/** Fields this building adds to the village's detection radius (watchtower), else 0. */
public function detection(string $type, int $level): float
{
$detection = $this->config->building($type)['detection'] ?? null;
return $detection ? $detection['base'] * $detection['factor'] ** self::above($level) : 0.0;
}
/** Points an instance at this level adds to its village. */ /** Points an instance at this level adds to its village. */
public function points(string $type, int $level): int public function points(string $type, int $level): int
{ {

View File

@ -0,0 +1,32 @@
<?php
namespace App\Game\Combat;
/** The outcome of one battle, from CombatResolver. */
final readonly class Battle
{
/**
* @param float $attackLoss share of every attacking unit that died, 0..1
* @param float $defenseLoss share of every defending unit that died, 0..1
*/
public function __construct(
public bool $attackerWon,
public float $attackLoss,
public float $defenseLoss,
public int $wallBefore,
public int $wallAfter,
public float $attackPower,
public float $defensePower,
) {}
/**
* Dead units of a group at a loss share, rounded per unit type.
*
* @param array<string, int> $units
* @return array<string, int>
*/
public static function dead(array $units, float $loss): array
{
return array_map(fn (int $n) => min($n, (int) round($n * $loss)), $units);
}
}

View File

@ -0,0 +1,133 @@
<?php
namespace App\Game\Combat;
use App\Game\WorldConfig;
use Carbon\CarbonImmutable;
/**
* The Die Stämme battle (architecture.md, "Combat"). Attack strength is split by class
* (infantry, cavalry, archer); every defender counts with its defence against each class,
* weighted by the attacker's mix. The wall adds basic defence and multiplies it, and rams
* lower the wall first. The winner loses (weaker / stronger)^1.5 of every unit, the
* loser everything. Luck, morale and the night bonus come in as numbers.
*/
final class CombatResolver
{
public function __construct(private readonly WorldConfig $config) {}
/**
* @param array<string, int> $attack units sent
* @param array<string, int> $defense units in the village; `militia` for levied villagers
* @param float $luck between −luck and +luck, see luck()
* @param float $night defence multiplier, see night()
*/
public function fight(array $attack, array $defense, int $wall, float $morale, float $luck, float $night = 1.0): Battle
{
$wallAfter = $this->siege('ram', $wall, $attack['ram'] ?? 0);
$byClass = $this->attackByClass($attack);
$total = array_sum($byClass);
if ($total <= 0) {
return new Battle(false, 1.0, 0.0, $wall, $wall, 0.0, 0.0);
}
$attackPower = $total * $morale * (1 + $luck);
$defensePower = $this->defense($defense, $byClass, $total, $wallAfter) * $night;
$exponent = (float) $this->config->get('combat.loss_exponent', 1.5);
if ($attackPower > $defensePower) {
return new Battle(true, ($defensePower / $attackPower) ** $exponent, 1.0, $wall, $wallAfter, $attackPower, $defensePower);
}
return new Battle(false, 1.0, ($attackPower / $defensePower) ** $exponent, $wall, $wallAfter, $attackPower, $defensePower);
}
/**
* The level a building is left at after $count rams or catapults hit it. Each level
* L down needs base × factor^(L − 1) of them; nothing drops below level 1.
*/
public function siege(string $kind, int $level, int $count): int
{
$siege = $this->config->get("combat.siege.$kind");
$left = (float) $count;
while ($level > 1) {
$needed = $siege['base'] * $siege['factor'] ** ($level - 1);
if ($left < $needed) {
break;
}
$left -= $needed;
$level--;
}
return $level;
}
/** Attack multiplier from points: 1 against barbarians (null), less against smaller players. */
public function morale(?int $defenderPoints, int $attackerPoints): float
{
$morale = $this->config->get('combat.morale');
if (! ($morale['enabled'] ?? false) || $defenderPoints === null || $attackerPoints <= 0) {
return 1.0;
}
return min(1.0, $morale['floor'] + $morale['points_factor'] * $defenderPoints / $attackerPoints);
}
/** Luck from a roll in [0, 1): spread evenly over [−luck, +luck]. */
public function luck(float $roll): float
{
return (2 * $roll - 1) * (float) $this->config->get('combat.luck', 0);
}
/** Defence multiplier at $at: the night factor while it is night on the world's clock. */
public function night(CarbonImmutable $at): float
{
$night = $this->config->get('combat.night');
if (! ($night['enabled'] ?? false)) {
return 1.0;
}
$hour = $at->setTimezone($night['timezone'] ?? 'UTC')->hour;
$inside = $night['start'] <= $night['end']
? $hour >= $night['start'] && $hour < $night['end']
: $hour >= $night['start'] || $hour < $night['end'];
return $inside ? (float) $night['factor'] : 1.0;
}
/**
* @param array<string, int> $units
* @return array<string, float> class => attack strength
*/
private function attackByClass(array $units): array
{
$byClass = ['infantry' => 0.0, 'cavalry' => 0.0, 'archer' => 0.0];
foreach ($units as $unit => $count) {
$values = $this->config->get("units.$unit");
$byClass[$values['class']] += $count * $values['attack'];
}
return $byClass;
}
/**
* Defence against this attack mix, with the wall's basic defence and bonus.
*
* @param array<string, int> $units
* @param array<string, float> $byClass
*/
private function defense(array $units, array $byClass, float $total, int $wall): float
{
$sum = 0.0;
foreach ($units as $unit => $count) {
$values = $unit === 'militia'
? $this->config->get('combat.militia.defense')
: $this->config->get("units.$unit.defense");
foreach ($byClass as $class => $strength) {
$sum += $count * $values[$class] * $strength / $total;
}
}
$walls = $this->config->get('combat.wall');
return ($sum + $walls['basic_defense'] * $wall) * $walls['factor'] ** $wall;
}
}

View File

@ -0,0 +1,47 @@
<?php
namespace App\Game\Combat;
use App\Game\WorldConfig;
/** What surviving attackers carry home: wood, clay and iron above what is hidden, split evenly. */
final class LootCalculator
{
public function __construct(private readonly WorldConfig $config) {}
/** @param array<string, int> $units */
public function capacity(array $units): int
{
$carry = 0;
foreach ($units as $unit => $count) {
$carry += $count * (int) $this->config->get("units.$unit.carry", 0);
}
return $carry;
}
/**
* Take up to $capacity from the stock, the same from each resource as far as it
* goes; what one resource lacks, the others make up. $hidden is kept back from each.
*
* @param array{wood: float, clay: float, iron: float} $stock
* @return array{wood: int, clay: int, iron: int}
*/
public static function take(array $stock, float $hidden, int $capacity): array
{
$available = array_map(fn (float $n) => max(0, (int) floor($n - $hidden)), $stock);
$loot = array_map(fn () => 0, $available);
$left = $capacity;
while ($left > 0 && ($open = array_keys(array_filter($available)))) {
$share = max(1, intdiv($left, count($open)));
foreach ($open as $resource) {
$take = min($share, $available[$resource], $left);
$loot[$resource] += $take;
$available[$resource] -= $take;
$left -= $take;
}
}
return $loot;
}
}

View File

@ -0,0 +1,90 @@
<?php
namespace App\Game\Travel;
use App\Game\WorldConfig;
use InvalidArgumentException;
/**
* How long a group takes between two villages, and how early the target sees it.
* A group moves at its slowest unit's pace (minutes per field), sped up by the
* world speed, the world's unit speed and its travel mode.
*/
final class TravelTime
{
public function __construct(private readonly WorldConfig $config) {}
public static function distance(int $fromX, int $fromY, int $toX, int $toY): float
{
return sqrt(($toX - $fromX) ** 2 + ($toY - $fromY) ** 2);
}
/** @return list<string> */
public function modes(): array
{
return array_keys($this->config->get('movement.modes', []));
}
public function hasMode(string $mode): bool
{
return in_array($mode, $this->modes(), true);
}
public function defaultMode(): string
{
return $this->config->get('movement.default_mode', 'normal');
}
/** @return array{speed: float, visibility: float} */
public function mode(string $mode): array
{
$values = $this->config->get("movement.modes.$mode") ?? throw new InvalidArgumentException("Unknown travel mode [$mode].");
return ['speed' => (float) $values['speed'], 'visibility' => (float) $values['visibility']];
}
/**
* Minutes per field of the slowest unit in the group, at world speed 1.
*
* @param array<string, int> $units unit => count
*/
public function slowest(array $units): float
{
$minutes = 0.0;
foreach ($units as $unit => $count) {
if ($count > 0) {
$minutes = max($minutes, (float) $this->config->get("units.$unit.speed"));
}
}
return $minutes;
}
/**
* Seconds the group takes for $distance fields.
*
* @param array<string, int> $units
*/
public function seconds(array $units, float $distance, string $mode): int
{
$pace = $this->config->speed() * $this->config->get('movement.unit_speed', 1.0) * $this->mode($mode)['speed'];
return max(1, (int) round($this->slowest($units) * $distance * 60 / $pace));
}
/**
* Seconds before arrival at which the target spots the group: once it comes within
* the mode's visibility plus the target's detection radius. An unseen mode shows up
* only when it arrives; a group that starts within range is seen at once.
*/
public function warningSeconds(int $seconds, float $distance, string $mode, float $detection): int
{
$visibility = $this->mode($mode)['visibility'];
if ($visibility <= 0) {
return 0;
}
$range = $visibility + $detection;
return $range >= $distance ? $seconds : (int) floor($seconds * $range / $distance);
}
}

View File

@ -27,6 +27,8 @@ class World extends Model
'economy' => config('game.economy'), 'economy' => config('game.economy'),
'buildings' => config('game.buildings'), 'buildings' => config('game.buildings'),
'units' => config('game.units'), 'units' => config('game.units'),
'combat' => config('game.combat'),
'movement' => config('game.movement'),
], $this->config ?? []); ], $this->config ?? []);
} }

View File

@ -1,11 +1,12 @@
<?php <?php
// Values per building type. Levels start at 0 (tent, open storage, gatherers). // Values per building type. Levels start at 1, which has the base values.
// `space` is how much of the village's building space an instance takes, at any level. // `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−1), build time = base × factor^(n−1) seconds at world
// workers = round(base × factor^n), production/capacity = base × factor^n. // speed 1, workers = round(base × factor^(n−1)), and production, capacity, hides and
// detection = base × factor^(n−1).
// 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). // Map points of an instance: round(points.base × points.factor^(level−1)).
return [ return [
'headquarters' => [ 'headquarters' => [
@ -89,6 +90,8 @@ return [
'build_time' => ['base' => 60, 'factor' => 1.2], 'build_time' => ['base' => 60, 'factor' => 1.2],
'workers' => ['base' => 0, 'factor' => 1.0], 'workers' => ['base' => 0, 'factor' => 1.0],
'production' => null, 'production' => null,
// Wood, clay and iron each that raiders can't take; instances add up.
'hides' => ['base' => 150, 'factor' => 1.3335],
'instance_cost_factor' => 1.5, 'instance_cost_factor' => 1.5,
'points' => ['base' => 5, 'factor' => 1.2], 'points' => ['base' => 5, 'factor' => 1.2],
'requires' => [], 'requires' => [],
@ -118,6 +121,20 @@ return [
'points' => ['base' => 2, 'factor' => 1.2], 'points' => ['base' => 2, 'factor' => 1.2],
'requires' => [], 'requires' => [],
], ],
// Spots incoming groups further out: adds `detection` fields to the village's radius.
'watchtower' => [
'space' => 2,
'max_per_village' => 1,
'max_level' => 20,
'cost' => ['wood' => 12000, 'clay' => 14000, 'iron' => 10000, 'factor' => 1.17],
'build_time' => ['base' => 6000, 'factor' => 1.2],
'workers' => ['base' => 1, 'factor' => 1.1],
'production' => null,
'detection' => ['base' => 1.1, 'factor' => 1.162],
'instance_cost_factor' => 1.0,
'points' => ['base' => 42, 'factor' => 1.2],
'requires' => ['headquarters' => 5, 'farm' => 5],
],
// Military buildings. Each instance runs its own recruiting queue; its level and // Military buildings. Each instance runs its own recruiting queue; its level and
// staffing speed up training there (economy.recruit_speed_per_level). // staffing speed up training there (economy.recruit_speed_per_level).

36
config/game/combat.php Normal file
View File

@ -0,0 +1,36 @@
<?php
// Battles in the Die Stämme model (architecture.md, "Combat").
return [
// Attack strength × (1 + luck), luck drawn evenly from [−luck, +luck] per battle. 0 turns it off.
'luck' => 0.25,
// Attacks on smaller players hit with less strength:
// min(1, floor + points_factor × defender points / attacker points). Barbarians always take 100%.
'morale' => ['enabled' => true, 'floor' => 0.3, 'points_factor' => 3],
// The winner loses (loser strength / winner strength) ^ exponent of every unit; the loser loses all.
'loss_exponent' => 1.5,
// Wall at level L: defenders get basic_defense × L extra, then everything × factor^L.
'wall' => ['basic_defense' => 20, 'factor' => 1.037],
// Rams hit the wall before the battle, surviving catapults the chosen building after
// a won one. Taking a building from level L to L − 1 needs base × factor^(L − 1)
// of them; buildings never drop below level 1.
'siege' => [
'ram' => ['base' => 2, 'factor' => 1.09],
'catapult' => ['base' => 2, 'factor' => 1.09],
],
// Defence × factor while the defender's clock is between start and end (hours).
'night' => ['enabled' => false, 'start' => 0, 'end' => 8, 'factor' => 2.0, 'timezone' => 'Europe/Berlin'],
// Levied villagers defend with these values per head.
'militia' => ['defense' => ['infantry' => 5, 'cavalry' => 5, 'archer' => 5]],
// New players can't be attacked by players for this long after joining (seconds at
// world speed 1), and can't attack players themselves meanwhile; barbarians are fine.
'beginner_protection' => 3 * 86400,
];

26
config/game/movement.php Normal file
View File

@ -0,0 +1,26 @@
<?php
// Troops on the move (architecture.md, "Movements and encounters").
return [
// Travel modes: `speed` multiplies how fast the group moves, `visibility` is the
// radius in fields within which it is seen. 0 means unseen until it arrives.
'modes' => [
'sneaky' => ['speed' => 0.5, 'visibility' => 0],
'cautious' => ['speed' => 0.8, 'visibility' => 4],
'normal' => ['speed' => 1.0, 'visibility' => 15],
'fast' => ['speed' => 1.25, 'visibility' => 30],
'forced' => ['speed' => 1.5, 'visibility' => 60],
],
'default_mode' => 'normal',
// Multiplies every unit's speed on this world, on top of the world speed.
'unit_speed' => 1.0,
// Fields around a village within which it spots incoming groups, before a watchtower.
'detection' => 2,
// A sent command can be called back within this many real seconds; the troops
// then turn around and take as long to get home as they had been under way.
'cancel_window' => 600,
];

View File

@ -28,6 +28,8 @@ function gameConfig(array $overrides = []): WorldConfig
'economy' => require "$dir/economy.php", 'economy' => require "$dir/economy.php",
'buildings' => require "$dir/buildings.php", 'buildings' => require "$dir/buildings.php",
'units' => require "$dir/units.php", 'units' => require "$dir/units.php",
'combat' => require "$dir/combat.php",
'movement' => require "$dir/movement.php",
], $overrides); ], $overrides);
} }

View File

@ -0,0 +1,92 @@
<?php
use App\Game\Combat\Battle;
use App\Game\Combat\CombatResolver;
use App\Game\Combat\LootCalculator;
use Carbon\CarbonImmutable;
it('lets the stronger attacker win and lose (weaker / stronger)^1.5', function () {
$battle = (new CombatResolver(gameConfig()))->fight(['light_cavalry' => 100], ['spear' => 50], 0, 1.0, 0.0);
// 13000 cavalry attack against 50 × 45 cavalry defence.
expect($battle->attackerWon)->toBeTrue()
->and($battle->defenseLoss)->toBe(1.0)
->and($battle->attackLoss)->toEqualWithDelta((2250 / 13000) ** 1.5, 1e-9)
->and(Battle::dead(['light_cavalry' => 100], $battle->attackLoss))->toBe(['light_cavalry' => 7]);
});
it('kills every attacker when the defence holds', function () {
$battle = (new CombatResolver(gameConfig()))->fight(['spear' => 10], ['sword' => 20], 0, 1.0, 0.0);
expect($battle->attackerWon)->toBeFalse()
->and($battle->attackLoss)->toBe(1.0)
->and(Battle::dead(['sword' => 20], $battle->defenseLoss))->toBe(['sword' => 1]);
});
it('weights the defence by the attacker\'s mix of classes', function () {
$battle = (new CombatResolver(gameConfig()))->fight(['spear' => 10, 'light_cavalry' => 1], ['spear' => 10], 0, 1.0, 0.0);
// 100 infantry and 130 cavalry: spears defend 15 against the one and 45 against the other.
expect($battle->defensePower)->toEqualWithDelta(150 * 100 / 230 + 450 * 130 / 230, 1e-9)
->and($battle->attackerWon)->toBeFalse();
});
it('wins every fight against an empty village without losses', function () {
$battle = (new CombatResolver(gameConfig()))->fight(['spear' => 1], [], 0, 1.0, 0.0);
expect($battle->attackerWon)->toBeTrue()
->and($battle->attackLoss)->toBe(0.0);
});
it('lets the wall defend on its own, and rams take it down first', function () {
$combat = new CombatResolver(gameConfig());
$held = $combat->fight(['sword' => 10], [], 10, 1.0, 0.0);
$rammed = $combat->fight(['sword' => 10, 'ram' => 20], [], 10, 1.0, 0.0);
expect($held->defensePower)->toEqualWithDelta(200 * 1.037 ** 10, 1e-9)
->and($held->attackerWon)->toBeFalse()
->and($rammed->wallBefore)->toBe(10)
->and($rammed->wallAfter)->toBe(5)
->and($rammed->attackerWon)->toBeTrue();
});
it('needs more siege units for every higher level and never goes below level 1', function () {
$combat = new CombatResolver(gameConfig());
expect($combat->siege('ram', 10, 20))->toBe(5)
->and($combat->siege('ram', 10, 0))->toBe(10)
->and($combat->siege('catapult', 3, 1000))->toBe(1)
->and($combat->siege('ram', 0, 50))->toBe(0);
});
it('scales attacks on smaller players by morale and draws luck evenly', function () {
$combat = new CombatResolver(gameConfig());
$off = new CombatResolver(gameConfig(['combat' => ['morale' => ['enabled' => false], 'luck' => 0]]));
expect($combat->morale(1000, 10000))->toEqualWithDelta(0.6, 1e-9)
->and($combat->morale(5000, 10000))->toBe(1.0)
->and($combat->morale(null, 10000))->toBe(1.0)
->and($off->morale(1000, 10000))->toBe(1.0)
->and($combat->luck(0.0))->toBe(-0.25)
->and($combat->luck(0.5))->toBe(0.0)
->and($off->luck(0.9))->toBe(0.0);
});
it('doubles the defence at night where the world has a night bonus', function () {
$combat = new CombatResolver(gameConfig(['combat' => ['night' => ['enabled' => true]]]));
// 03:00 and 13:00 in Berlin.
expect($combat->night(CarbonImmutable::parse('2026-10-29 02:00:00', 'UTC')))->toBe(2.0)
->and($combat->night(CarbonImmutable::parse('2026-10-29 12:00:00', 'UTC')))->toBe(1.0)
->and((new CombatResolver(gameConfig()))->night(CarbonImmutable::parse('2026-10-29 02:00:00', 'UTC')))->toBe(1.0);
});
it('loots evenly and lets the other resources make up for a short one', function () {
expect(LootCalculator::take(['wood' => 1000.0, 'clay' => 100.0, 'iron' => 500.0], 0, 900))->toBe(['wood' => 400, 'clay' => 100, 'iron' => 400])
->and(LootCalculator::take(['wood' => 1000.0, 'clay' => 1000.0, 'iron' => 1000.0], 0, 10))->toBe(['wood' => 4, 'clay' => 3, 'iron' => 3])
->and(LootCalculator::take(['wood' => 300.0, 'clay' => 120.0, 'iron' => 151.9], 150, 1000))->toBe(['wood' => 150, 'clay' => 0, 'iron' => 1]);
});
it('carries what the survivors can carry', function () {
expect((new LootCalculator(gameConfig()))->capacity(['spear' => 10, 'light_cavalry' => 2, 'ram' => 3]))->toBe(250 + 160);
});

View File

@ -0,0 +1,35 @@
<?php
use App\Game\Travel\TravelTime;
it('measures distance in fields as the crow flies', function () {
expect(TravelTime::distance(500, 500, 503, 504))->toBe(5.0)
->and(TravelTime::distance(500, 500, 500, 500))->toBe(0.0);
});
it('moves at the pace of the slowest unit', function () {
$travel = new TravelTime(gameConfig());
expect($travel->seconds(['spear' => 10], 5.0, 'normal'))->toBe(18 * 5 * 60)
->and($travel->seconds(['spear' => 10, 'ram' => 1], 5.0, 'normal'))->toBe(30 * 5 * 60)
->and($travel->seconds(['spear' => 10, 'ram' => 0], 5.0, 'normal'))->toBe(18 * 5 * 60);
});
it('speeds up with the travel mode, world speed and unit speed', function () {
$travel = new TravelTime(gameConfig());
$fast = new TravelTime(gameConfig(['world' => ['speed' => 100], 'movement' => ['unit_speed' => 0.5]]));
expect($travel->seconds(['spear' => 1], 5.0, 'fast'))->toBe(4320)
->and($travel->seconds(['spear' => 1], 5.0, 'sneaky'))->toBe(10800)
->and($fast->seconds(['spear' => 1], 5.0, 'normal'))->toBe(108);
});
it('is spotted once it comes within visibility plus detection', function () {
$travel = new TravelTime(gameConfig());
$seconds = $travel->seconds(['spear' => 1], 34.0, 'normal');
// Normal visibility 15 plus 2 fields of detection: seen for the last half of 34 fields.
expect($travel->warningSeconds($seconds, 34.0, 'normal', 2.0))->toBe(intdiv($seconds, 2))
->and($travel->warningSeconds($seconds, 10.0, 'normal', 2.0))->toBe($seconds)
->and($travel->warningSeconds($seconds, 34.0, 'sneaky', 20.0))->toBe(0);
});