diff --git a/app/Game/Buildings/BuildingRules.php b/app/Game/Buildings/BuildingRules.php index 00a9238..c550380 100644 --- a/app/Game/Buildings/BuildingRules.php +++ b/app/Game/Buildings/BuildingRules.php @@ -99,6 +99,22 @@ final class BuildingRules 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. */ public function points(string $type, int $level): int { diff --git a/app/Game/Combat/Battle.php b/app/Game/Combat/Battle.php new file mode 100644 index 0000000..75fa4a8 --- /dev/null +++ b/app/Game/Combat/Battle.php @@ -0,0 +1,32 @@ + $units + * @return array + */ + public static function dead(array $units, float $loss): array + { + return array_map(fn (int $n) => min($n, (int) round($n * $loss)), $units); + } +} diff --git a/app/Game/Combat/CombatResolver.php b/app/Game/Combat/CombatResolver.php new file mode 100644 index 0000000..2da6e65 --- /dev/null +++ b/app/Game/Combat/CombatResolver.php @@ -0,0 +1,133 @@ + $attack units sent + * @param array $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 $units + * @return array 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 $units + * @param array $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; + } +} diff --git a/app/Game/Combat/LootCalculator.php b/app/Game/Combat/LootCalculator.php new file mode 100644 index 0000000..d253bbb --- /dev/null +++ b/app/Game/Combat/LootCalculator.php @@ -0,0 +1,47 @@ + $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; + } +} diff --git a/app/Game/Travel/TravelTime.php b/app/Game/Travel/TravelTime.php new file mode 100644 index 0000000..7e5eac0 --- /dev/null +++ b/app/Game/Travel/TravelTime.php @@ -0,0 +1,90 @@ + */ + 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 $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 $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); + } +} diff --git a/app/Models/World.php b/app/Models/World.php index fdbeac8..6cc44da 100644 --- a/app/Models/World.php +++ b/app/Models/World.php @@ -27,6 +27,8 @@ class World extends Model 'economy' => config('game.economy'), 'buildings' => config('game.buildings'), 'units' => config('game.units'), + 'combat' => config('game.combat'), + 'movement' => config('game.movement'), ], $this->config ?? []); } diff --git a/config/game/buildings.php b/config/game/buildings.php index 4912fa5..893530c 100644 --- a/config/game/buildings.php +++ b/config/game/buildings.php @@ -1,11 +1,12 @@ [ @@ -89,6 +90,8 @@ return [ 'build_time' => ['base' => 60, 'factor' => 1.2], 'workers' => ['base' => 0, 'factor' => 1.0], '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, 'points' => ['base' => 5, 'factor' => 1.2], 'requires' => [], @@ -118,6 +121,20 @@ return [ 'points' => ['base' => 2, 'factor' => 1.2], '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 // staffing speed up training there (economy.recruit_speed_per_level). diff --git a/config/game/combat.php b/config/game/combat.php new file mode 100644 index 0000000..e68a191 --- /dev/null +++ b/config/game/combat.php @@ -0,0 +1,36 @@ + 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, +]; diff --git a/config/game/movement.php b/config/game/movement.php new file mode 100644 index 0000000..466e381 --- /dev/null +++ b/config/game/movement.php @@ -0,0 +1,26 @@ + [ + '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, +]; diff --git a/tests/Pest.php b/tests/Pest.php index 8e2ffd4..84472b7 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -28,6 +28,8 @@ function gameConfig(array $overrides = []): WorldConfig 'economy' => require "$dir/economy.php", 'buildings' => require "$dir/buildings.php", 'units' => require "$dir/units.php", + 'combat' => require "$dir/combat.php", + 'movement' => require "$dir/movement.php", ], $overrides); } diff --git a/tests/Unit/Game/CombatTest.php b/tests/Unit/Game/CombatTest.php new file mode 100644 index 0000000..5f575e7 --- /dev/null +++ b/tests/Unit/Game/CombatTest.php @@ -0,0 +1,92 @@ +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); +}); diff --git a/tests/Unit/Game/TravelTimeTest.php b/tests/Unit/Game/TravelTimeTest.php new file mode 100644 index 0000000..7651a58 --- /dev/null +++ b/tests/Unit/Game/TravelTimeTest.php @@ -0,0 +1,35 @@ +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); +});