feat: ranking: players and villages by points, opponents defeated in attack and defence
ranking.index pages 25 rows and opens on the user's own row. Battles bump defeated.attack and defeated.defense by the food the fallen ate; defenders share by what they had standing. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
45eb0a8f92
commit
dc41186b47
|
|
@ -0,0 +1,89 @@
|
|||
<?php
|
||||
|
||||
namespace App\Actions;
|
||||
|
||||
use App\Game\GameRuleViolation;
|
||||
use App\Models\Player;
|
||||
use App\Models\User;
|
||||
use App\Models\World;
|
||||
use Illuminate\Support\Collection;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
/**
|
||||
* The world's ranking, like Die Stämme's: players by points, villages by points, and
|
||||
* opponents defeated in attack and in defence (the `defeated.*` counters Rally bumps).
|
||||
* Ties go to the older player or village. Without a page it opens on the user's own row.
|
||||
*/
|
||||
final class Ranking
|
||||
{
|
||||
public const PER_PAGE = 25;
|
||||
|
||||
public const KINDS = ['players', 'villages', 'attack', 'defense'];
|
||||
|
||||
/** @return array{kind: string, page: int, pages: int, rows: list<array<string, mixed>>, 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]);
|
||||
}
|
||||
}
|
||||
|
|
@ -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]) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,51 @@
|
|||
<?php
|
||||
|
||||
namespace App\Game\Combat;
|
||||
|
||||
use App\Game\Military\UnitRules;
|
||||
use App\Game\WorldConfig;
|
||||
|
||||
/**
|
||||
* Opponents defeated, for the ranking: every fallen enemy counts with the food it ate,
|
||||
* so a nobleman weighs ten spears and a levied villager one. Defenders share what the
|
||||
* attackers lost by what each of them had standing in the village.
|
||||
*/
|
||||
final class Defeated
|
||||
{
|
||||
private UnitRules $units;
|
||||
|
||||
public function __construct(private readonly WorldConfig $config)
|
||||
{
|
||||
$this->units = new UnitRules($config);
|
||||
}
|
||||
|
||||
/** @param array<string, int> $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<int|string, float> $standing defender => weight
|
||||
* @return array<int|string, int>
|
||||
*/
|
||||
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) : [];
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
<?php
|
||||
|
||||
namespace App\Websocket\Controllers;
|
||||
|
||||
use App\Actions\Ranking;
|
||||
use App\Websocket\GameController;
|
||||
|
||||
/** ranking.index {world_id, kind: players|villages|attack|defense, page?}: without a page, the user's own. */
|
||||
class RankingController extends GameController
|
||||
{
|
||||
public function index()
|
||||
{
|
||||
return $this->play(fn () => app(Ranking::class)->list(
|
||||
auth()->user(),
|
||||
(int) request('world_id'),
|
||||
(string) (request('kind') ?: 'players'),
|
||||
request('page') ? (int) request('page') : null,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
|
@ -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`:
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,61 @@
|
|||
<?php
|
||||
|
||||
use App\Actions\Ranking;
|
||||
use App\Actions\SendTroops;
|
||||
use App\Engine\VillageFactory;
|
||||
use App\Models\User;
|
||||
use App\Models\Village;
|
||||
use Carbon\CarbonImmutable;
|
||||
|
||||
beforeEach(fn () => $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');
|
||||
});
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
<?php
|
||||
|
||||
use App\Game\Combat\Defeated;
|
||||
|
||||
it('weighs the fallen by the food they ate', function () {
|
||||
$defeated = new Defeated(gameConfig());
|
||||
|
||||
expect($defeated->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([]);
|
||||
});
|
||||
Loading…
Reference in New Issue