diff --git a/app/Actions/Ranking.php b/app/Actions/Ranking.php new file mode 100644 index 0000000..985897c --- /dev/null +++ b/app/Actions/Ranking.php @@ -0,0 +1,89 @@ +>, own: array{rank: int, page: int}|null} */ + public function list(User $user, int $worldId, string $kind, ?int $page = null): array + { + if (! World::whereKey($worldId)->exists() || ! in_array($kind, self::KINDS, true)) { + throw new GameRuleViolation('not_found', 'No such ranking.'); + } + $me = Player::where('user_id', $user->id)->where('world_id', $worldId)->value('id'); + $rows = match ($kind) { + 'players' => $this->players($worldId), + 'villages' => $this->villages($worldId), + default => $this->defeated($worldId, $kind), + }; + $ranked = $rows->values()->map(fn (array $row, int $i) => ['rank' => $i + 1, ...$row, 'own' => $me !== null && $row['player']['id'] === $me]); + $mine = $ranked->firstWhere('own', true); + $own = $mine ? ['rank' => $mine['rank'], 'page' => (int) ceil($mine['rank'] / self::PER_PAGE)] : null; + $pages = max(1, (int) ceil($ranked->count() / self::PER_PAGE)); + $page = max(1, min($pages, $page ?? $own['page'] ?? 1)); + + return [ + 'kind' => $kind, + 'page' => $page, + 'pages' => $pages, + 'rows' => $ranked->forPage($page, self::PER_PAGE)->values()->all(), + 'own' => $own, + ]; + } + + /** Players with villages, by the sum of their villages' points. */ + private function players(int $worldId): Collection + { + return DB::table('players') + ->join('villages', 'villages.player_id', '=', 'players.id') + ->where('players.world_id', $worldId) + ->groupBy('players.id', 'players.name') + ->selectRaw('players.id, players.name, SUM(villages.points) as points, COUNT(villages.id) as villages') + ->orderByDesc('points')->orderBy('players.id') + ->get() + ->map(fn ($r) => ['player' => ['id' => (int) $r->id, 'name' => $r->name], 'value' => (int) $r->points, 'villages' => (int) $r->villages]); + } + + private function villages(int $worldId): Collection + { + return DB::table('villages') + ->join('players', 'players.id', '=', 'villages.player_id') + ->where('villages.world_id', $worldId) + ->orderByDesc('villages.points')->orderBy('villages.id') + ->get(['villages.id', 'villages.name', 'villages.x', 'villages.y', 'villages.points', 'players.id as player_id', 'players.name as player_name']) + ->map(fn ($r) => [ + 'player' => ['id' => (int) $r->player_id, 'name' => $r->player_name], + 'village' => ['id' => (int) $r->id, 'name' => $r->name, 'x' => (int) $r->x, 'y' => (int) $r->y], + 'value' => (int) $r->points, + ]); + } + + /** Players by opponents defeated in attack or in defence. */ + private function defeated(int $worldId, string $kind): Collection + { + return DB::table('player_counters') + ->join('players', 'players.id', '=', 'player_counters.player_id') + ->where('players.world_id', $worldId) + ->where('player_counters.key', "defeated.$kind") + ->where('player_counters.value', '>', 0) + ->orderByDesc('player_counters.value')->orderBy('players.id') + ->get(['players.id', 'players.name', 'player_counters.value']) + ->map(fn ($r) => ['player' => ['id' => (int) $r->id, 'name' => $r->name], 'value' => (int) $r->value]); + } +} diff --git a/app/Engine/Rally.php b/app/Engine/Rally.php index 47de305..b58bd37 100644 --- a/app/Engine/Rally.php +++ b/app/Engine/Rally.php @@ -4,6 +4,7 @@ namespace App\Engine; use App\Game\Combat\Battle; use App\Game\Combat\CombatResolver; +use App\Game\Combat\Defeated; use App\Game\Combat\LootCalculator; use App\Game\Combat\Raids; use App\Game\GameRuleViolation; @@ -292,6 +293,16 @@ final class Rally $battle = $army ? $combat->fight($army, $defense, $wall?->level ?? 0, $morale, $luck, $night * $fort) : null; $won = $battle ? $battle->attackerWon : $through; + // What each home village had standing here, for its part of the opponents defeated. + $defeated = new Defeated($config); + $standing = []; + foreach ($stacks as $stack) { + $standing[$stack->home_village_id] = ($standing[$stack->home_village_id] ?? 0) + $defeated->weight([$stack->unit => $stack->count]); + } + if (isset($defense['militia'])) { + $standing[$this->village->id] = ($standing[$this->village->id] ?? 0) + $defeated->weight(['militia' => $defense['militia']]); + } + // Defenders fall in every stack alike, support included. $defenseLost = []; $supporters = []; @@ -322,6 +333,12 @@ final class Rally ...($battle ? Battle::dead($army, $battle->attackLoss) : []), ...Battle::dead($scouts, $scouts ? $scoutsLost / array_sum($scouts) : 0.0), ]; + Quests::bump($movement->player_id, 'defeated.attack', $defeated->points($defenseLost)); + $owners = Village::whereIn('id', array_keys($standing))->pluck('player_id', 'id'); + foreach (Defeated::share($defeated->points($attackLost), $standing) as $homeId => $points) { + Quests::bump($owners[$homeId] ?? null, 'defeated.defense', $points); + } + $survivors = []; foreach ($movement->units as $unit => $count) { if ($count > $attackLost[$unit]) { diff --git a/app/Game/Combat/Defeated.php b/app/Game/Combat/Defeated.php new file mode 100644 index 0000000..9894416 --- /dev/null +++ b/app/Game/Combat/Defeated.php @@ -0,0 +1,51 @@ +units = new UnitRules($config); + } + + /** @param array $units by unit; `militia` for levied villagers */ + public function weight(array $units): float + { + $total = 0.0; + foreach ($units as $unit => $count) { + $total += $count * ($unit === 'militia' ? (float) $this->config->get('economy.upkeep.villager', 1) : $this->units->upkeep($unit)); + } + + return $total; + } + + /** Points for what fell. */ + public function points(array $lost): int + { + return (int) round($this->weight($lost)); + } + + /** + * Each defender's part of the points, by the weight they had standing. + * + * @param array $standing defender => weight + * @return array + */ + public static function share(int $points, array $standing): array + { + $total = array_sum($standing); + + return $total > 0 ? array_map(fn (float $w) => (int) round($points * $w / $total), $standing) : []; + } +} diff --git a/app/Websocket/Controllers/RankingController.php b/app/Websocket/Controllers/RankingController.php new file mode 100644 index 0000000..4ee4bf2 --- /dev/null +++ b/app/Websocket/Controllers/RankingController.php @@ -0,0 +1,20 @@ +play(fn () => app(Ranking::class)->list( + auth()->user(), + (int) request('world_id'), + (string) (request('kind') ?: 'players'), + request('page') ? (int) request('page') : null, + )); + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 6ab31de..d6c3853 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -256,6 +256,14 @@ Villages change hands the Die Stämme way (`combat.conquest`, rules in `Conquest - A player who loses the last village joins the world again with a fresh one (`world.join`). - The village payload carries `loyalty`, `conquest: {coins, slots, used, next_slot_coins, coin_cost, max_distance}` and `villages` (the player's villages in the world, for the switcher). +## Ranking + +`ranking.index {world_id, kind, page?}` (`Ranking`) lists a world like Die Stämme's ranking, 25 rows a page; without a page it opens on the page with the user's own row (`own: {rank, page}`). Ties go to the older player or village. + +- `players`: players with villages, by the sum of their villages' points, with their village count. +- `villages`: player villages by points. +- `attack` and `defense`: opponents defeated. Every battle bumps `defeated.attack` for the attacker by the defenders who fell and `defeated.defense` for the defenders by the attackers who fell, each unit counted with the food it eats (`Defeated`: a nobleman is 10, a levied villager 1). Defenders share by what each home village had standing there, so support earns its part. Barbarian garrisons count as opponents; raiders earn nothing, but beating them counts in defence. + ## Combat Combat uses the TW model, in `CombatResolver` (pure, tested with fixed luck) and `config/game/combat.php`: diff --git a/tests/Feature/RaidTest.php b/tests/Feature/RaidTest.php index b36cbcd..3cddb55 100644 --- a/tests/Feature/RaidTest.php +++ b/tests/Feature/RaidTest.php @@ -8,6 +8,7 @@ use App\Models\Report; use App\Models\Village; use Carbon\CarbonImmutable; use Database\Seeders\WorldSeeder; +use Illuminate\Support\Facades\DB; beforeEach(function () { $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00')); @@ -110,6 +111,8 @@ it('pays a bounty when the village beats the band', function () { ->and($report->payload['bounty'])->toBe(['wood' => 15, 'clay' => 15, 'iron' => 15]) ->and($report->payload['attacker']['lost'])->toBe(['spear' => 4, 'sword' => 2]) ->and(Movement::count())->toBe(0) + // 6 raiders at 1 food each count as opponents defeated in defence. + ->and(DB::table('player_counters')->where('player_id', $village->player_id)->where('key', 'defeated.defense')->value('value'))->toBe(6) ->and(shown($village)['resources']['wood'])->toBeGreaterThan($wood + 14); }); diff --git a/tests/Feature/RankingTest.php b/tests/Feature/RankingTest.php new file mode 100644 index 0000000..5d616ea --- /dev/null +++ b/tests/Feature/RankingTest.php @@ -0,0 +1,61 @@ + $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00'))); + +function ranking(Village $village, string $kind, ?int $page = null): array +{ + return app(Ranking::class)->list(owner($village), $village->world_id, $kind, $page); +} + +it('ranks players by the points of all their villages and villages by their own', function () { + $small = startVillage(); + $big = startVillage(); + $big->buildings()->where('type', 'headquarters')->update(['level' => 5]); + $big->update(['points' => 60]); + $second = app(VillageFactory::class)->create($big->world, $big->player, 'Second', $big->x + 9, $big->y, ['headquarters' => 1]); + $second->update(['points' => 10]); + + $players = ranking($small, 'players'); + expect($players['rows'])->toHaveCount(2) + ->and($players['rows'][0])->toMatchArray(['rank' => 1, 'value' => 70, 'villages' => 2, 'own' => false]) + ->and($players['rows'][1])->toMatchArray(['rank' => 2, 'value' => $small->points, 'villages' => 1, 'own' => true]) + ->and($players['own'])->toBe(['rank' => 2, 'page' => 1]); + + $villages = ranking($small, 'villages'); + expect(array_column(array_column($villages['rows'], 'village'), 'name'))->toBe([$big->name, $small->name, 'Second']); +}); + +it('counts opponents defeated in attack and in defence by the food they ate', function () { + $attacker = startVillage(); + $attacker->buildings()->create(['type' => 'rally_point', 'level' => 1]); + $attacker->troops()->create(['home_village_id' => $attacker->id, 'unit' => 'light_cavalry', 'count' => 50]); + $camp = app(VillageFactory::class)->create($attacker->world, null, 'Barbarian village', $attacker->x + 3, $attacker->y, ['headquarters' => 1]); + $camp->troops()->create(['home_village_id' => $camp->id, 'unit' => 'spear', 'count' => 10]); + + app(SendTroops::class)(owner($attacker), $attacker->id, 'attack', $camp->x, $camp->y, ['light_cavalry' => 50], null, null); + $this->travel(1)->hours(); + $this->artisan('game:events --once')->assertSuccessful(); + + // 10 spears at 1 food each. + expect(ranking($attacker, 'attack')['rows'][0])->toMatchArray(['rank' => 1, 'value' => 10, 'own' => true]) + ->and(ranking($attacker, 'defense')['rows'])->toBe([]); +}); + +it('opens on the page with the own row and refuses unknown kinds', function () { + $village = startVillage(); + foreach (range(1, 30) as $i) { + $other = startVillage(User::factory()->create()); + $other->update(['points' => 1000 + $i]); + } + + expect(ranking($village, 'players'))->toMatchArray(['page' => 2, 'pages' => 2, 'own' => ['rank' => 31, 'page' => 2]]) + ->and(ranking($village, 'players', 1)['page'])->toBe(1) + ->and(rule(fn () => ranking($village, 'gold')))->toBe('not_found'); +}); diff --git a/tests/Unit/Game/DefeatedTest.php b/tests/Unit/Game/DefeatedTest.php new file mode 100644 index 0000000..0779292 --- /dev/null +++ b/tests/Unit/Game/DefeatedTest.php @@ -0,0 +1,16 @@ +points(['spear' => 10, 'light_cavalry' => 2, 'nobleman' => 1]))->toBe(10 + 6 + 10) + ->and($defeated->points(['militia' => 7]))->toBe(7) + ->and($defeated->points([]))->toBe(0); +}); + +it('shares the points among defenders by what they had standing', function () { + expect(Defeated::share(30, [5 => 20.0, 9 => 10.0]))->toBe([5 => 20, 9 => 10]) + ->and(Defeated::share(30, []))->toBe([]); +});