diff --git a/app/Actions/Ranking.php b/app/Actions/Ranking.php index 985897c..a404ffa 100644 --- a/app/Actions/Ranking.php +++ b/app/Actions/Ranking.php @@ -10,7 +10,7 @@ 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 + * The world's ranking, like Die Stämme's: players, tribes and 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. */ @@ -18,7 +18,7 @@ final class Ranking { public const PER_PAGE = 25; - public const KINDS = ['players', 'villages', 'attack', 'defense']; + public const KINDS = ['players', 'tribes', 'villages', 'attack', 'defense']; /** @return array{kind: string, page: int, pages: int, rows: list>, own: array{rank: int, page: int}|null} */ public function list(User $user, int $worldId, string $kind, ?int $page = null): array @@ -26,13 +26,23 @@ final class Ranking 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'); + $me = Player::with('membership')->where('user_id', $user->id)->where('world_id', $worldId)->first(); $rows = match ($kind) { 'players' => $this->players($worldId), + 'tribes' => $this->tribes($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]); + $own = fn (array $row) => $kind === 'tribes' + ? $me?->tribeId() !== null && $row['tribe']['id'] === $me->tribeId() + : $me !== null && $row['player']['id'] === $me->id; + $tags = $this->tags($worldId); + $ranked = $rows->values()->map(fn (array $row, int $i) => [ + 'rank' => $i + 1, + ...$row, + ...(isset($row['player']) ? ['player' => [...$row['player'], 'tribe' => $tags[$row['player']['id']] ?? null]] : []), + 'own' => $own($row), + ]); $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)); @@ -60,6 +70,32 @@ final class Ranking ->map(fn ($r) => ['player' => ['id' => (int) $r->id, 'name' => $r->name], 'value' => (int) $r->points, 'villages' => (int) $r->villages]); } + /** Tribes by the points of all their members' villages. */ + private function tribes(int $worldId): Collection + { + return DB::table('tribes') + ->join('tribe_members', 'tribe_members.tribe_id', '=', 'tribes.id') + ->leftJoin('villages', 'villages.player_id', '=', 'tribe_members.player_id') + ->where('tribes.world_id', $worldId) + ->groupBy('tribes.id', 'tribes.name', 'tribes.tag') + ->selectRaw('tribes.id, tribes.name, tribes.tag, COALESCE(SUM(villages.points), 0) as points, COUNT(DISTINCT tribe_members.player_id) as members') + ->orderByDesc('points')->orderBy('tribes.id') + ->get() + ->map(fn ($r) => ['tribe' => ['id' => (int) $r->id, 'name' => $r->name, 'tag' => $r->tag], 'value' => (int) $r->points, 'members' => (int) $r->members]); + } + + /** + * Tribe tags of the world's players, for the rows. + * + * @return array + */ + private function tags(int $worldId): array + { + return DB::table('tribe_members')->join('tribes', 'tribes.id', '=', 'tribe_members.tribe_id')->where('tribes.world_id', $worldId) + ->get(['tribe_members.player_id', 'tribes.id', 'tribes.tag']) + ->mapWithKeys(fn ($r) => [(int) $r->player_id => ['id' => (int) $r->id, 'tag' => $r->tag]])->all(); + } + private function villages(int $worldId): Collection { return DB::table('villages') diff --git a/app/Actions/Tribes.php b/app/Actions/Tribes.php new file mode 100644 index 0000000..7bd00d3 --- /dev/null +++ b/app/Actions/Tribes.php @@ -0,0 +1,438 @@ +player($user, $worldId); + $now = now()->toImmutable(); + $diplomacy = new Diplomacy($me->world->gameConfig()); + $membership = $me->membership()->with('tribe')->first(); + $tribe = $membership?->tribe; + + return [ + 'tribe' => $tribe ? $this->present($tribe, $membership, $now) : null, + 'invites' => TribeInvite::with(['tribe', 'tribe.members'])->where('player_id', $me->id)->orderBy('id')->get() + ->map(fn (TribeInvite $i) => ['tribe' => $i->tribe->summary(), 'members' => $i->tribe->members->count(), 'at' => self::iso($i->created_at->toImmutable())])->all(), + 'max_members' => $diplomacy->maxMembers(), + 'notice_seconds' => $diplomacy->noticeSeconds(), + ]; + } + + /** Every tribe of the world with its size and points, and what it is to the player's tribe. */ + public function list(User $user, int $worldId): array + { + $me = $this->player($user, $worldId); + $relations = TribeRelations::relationsOf($me->tribeId(), now()->toImmutable()); + $points = DB::table('tribe_members') + ->join('villages', 'villages.player_id', '=', 'tribe_members.player_id') + ->groupBy('tribe_members.tribe_id') + ->selectRaw('tribe_members.tribe_id, SUM(villages.points) as points') + ->pluck('points', 'tribe_id'); + + return Tribe::withCount('members')->where('world_id', $worldId)->get() + ->map(fn (Tribe $t) => [ + ...$t->summary(), + 'members' => $t->members_count, + 'points' => (int) ($points[$t->id] ?? 0), + 'relation' => $t->id === $me->tribeId() ? Diplomacy::TRIBE : ($relations[$t->id] ?? Diplomacy::NONE), + ]) + ->sortByDesc('points')->values()->all(); + } + + public function found(User $user, int $worldId, string $name, string $tag): array + { + $name = trim($name); + $tag = trim($tag); + if (! Diplomacy::validName($name) || ! Diplomacy::validTag($tag)) { + throw new GameRuleViolation('tribe_name', 'Name 3 to 32 characters, tag 2 to 6.'); + } + + return $this->change($user, $worldId, function (Player $me, CarbonImmutable $now) use ($worldId, $name, $tag) { + if ($me->tribeId()) { + throw new GameRuleViolation('in_tribe', 'Leave your tribe first.'); + } + if (Tribe::where('world_id', $worldId)->where(fn ($q) => $q->where('name', $name)->orWhere('tag', $tag))->exists()) { + throw new GameRuleViolation('tribe_taken', 'That name or tag is taken.'); + } + $tribe = Tribe::create(['world_id' => $worldId, 'name' => $name, 'tag' => $tag]); + $tribe->members()->create(['player_id' => $me->id, 'role' => TribeMember::LEADER]); + TribeInvite::where('player_id', $me->id)->delete(); + TribeEvent::note($tribe->id, 'founded', ['player' => $me->name], $now); + }); + } + + public function invite(User $user, int $worldId, string $playerName): array + { + return $this->change($user, $worldId, function (Player $me, CarbonImmutable $now) use ($worldId, $playerName) { + $tribe = $this->managed($me); + $player = Player::where('world_id', $worldId)->where('name', trim($playerName))->first() + ?? throw new GameRuleViolation('no_player', 'No player of that name here.'); + if ($player->tribeId() === $tribe->id) { + throw new GameRuleViolation('already_member', 'Already in your tribe.'); + } + TribeInvite::firstOrCreate(['tribe_id' => $tribe->id, 'player_id' => $player->id], ['invited_by' => $me->id]); + TribeEvent::note($tribe->id, 'invited', ['player' => $player->name, 'by' => $me->name], $now); + Push::queue(...$player->villages()->pluck('id')); + }); + } + + public function cancelInvite(User $user, int $worldId, int $playerId): array + { + return $this->change($user, $worldId, function (Player $me) use ($playerId) { + TribeInvite::where('tribe_id', $this->managed($me)->id)->where('player_id', $playerId)->delete(); + }); + } + + /** Accept an invite. */ + public function join(User $user, int $worldId, int $tribeId): array + { + return $this->change($user, $worldId, function (Player $me, CarbonImmutable $now) use ($tribeId) { + if ($me->tribeId()) { + throw new GameRuleViolation('in_tribe', 'Leave your tribe first.'); + } + $tribe = Tribe::whereKey($tribeId)->lockForUpdate()->first(); + if (! $tribe || ! TribeInvite::where('tribe_id', $tribeId)->where('player_id', $me->id)->exists()) { + throw new GameRuleViolation('not_found', 'No such invite.'); + } + if ($tribe->members()->count() >= (new Diplomacy($tribe->world->gameConfig()))->maxMembers()) { + throw new GameRuleViolation('tribe_full', 'That tribe is full.'); + } + $tribe->members()->create(['player_id' => $me->id, 'role' => TribeMember::MEMBER]); + TribeInvite::where('player_id', $me->id)->delete(); + TribeEvent::note($tribe->id, 'joined', ['player' => $me->name], $now); + }); + } + + /** Turn an invite down. */ + public function refuse(User $user, int $worldId, int $tribeId): array + { + return $this->change($user, $worldId, function (Player $me) use ($tribeId) { + TribeInvite::where('tribe_id', $tribeId)->where('player_id', $me->id)->delete(); + }); + } + + /** Leave; a leader hands over first, unless alone, which ends the tribe. */ + public function leave(User $user, int $worldId): array + { + return $this->change($user, $worldId, function (Player $me, CarbonImmutable $now) { + $membership = $me->membership ?? throw new GameRuleViolation('no_tribe', 'You are not in a tribe.'); + $tribe = Tribe::whereKey($membership->tribe_id)->lockForUpdate()->first(); + if ($membership->role === TribeMember::LEADER) { + if ($tribe->members()->count() > 1) { + throw new GameRuleViolation('hand_over', 'Make someone else leader first.'); + } + $tribe->delete(); + + return; + } + $membership->delete(); + TribeEvent::note($tribe->id, 'left', ['player' => $me->name], $now); + }); + } + + /** The leader removes anyone, the council plain members. */ + public function kick(User $user, int $worldId, int $playerId): array + { + return $this->change($user, $worldId, function (Player $me, CarbonImmutable $now) use ($playerId) { + $tribe = $this->managed($me); + $target = TribeMember::with('player')->where('tribe_id', $tribe->id)->where('player_id', $playerId)->first() + ?? throw new GameRuleViolation('not_found', 'Not in your tribe.'); + $mine = $me->membership->role; + if ($target->player_id === $me->id || ($mine !== TribeMember::LEADER && $target->role !== TribeMember::MEMBER)) { + throw new GameRuleViolation('rank', 'Your rank does not allow that.'); + } + $target->delete(); + TribeEvent::note($tribe->id, 'kicked', ['player' => $target->player->name, 'by' => $me->name], $now); + Push::queue(...$target->player->villages()->pluck('id')); + }); + } + + /** The leader sets roles; making someone leader hands the tribe over. */ + public function role(User $user, int $worldId, int $playerId, string $role): array + { + if (! in_array($role, self::ROLES, true)) { + throw new GameRuleViolation('not_found', "Unknown role [$role]."); + } + + return $this->change($user, $worldId, function (Player $me, CarbonImmutable $now) use ($playerId, $role) { + $membership = $me->membership; + if ($membership?->role !== TribeMember::LEADER) { + throw new GameRuleViolation('rank', 'Only the leader sets roles.'); + } + $target = TribeMember::with('player')->where('tribe_id', $membership->tribe_id)->where('player_id', $playerId)->first(); + if (! $target || $target->player_id === $me->id) { + throw new GameRuleViolation('not_found', 'Not another member of your tribe.'); + } + if ($role === TribeMember::LEADER) { + $membership->update(['role' => TribeMember::COUNCIL]); + } + $target->update(['role' => $role]); + TribeEvent::note($membership->tribe_id, 'role', ['player' => $target->player->name, 'role' => $role], $now); + }); + } + + public function describe(User $user, int $worldId, string $text): array + { + return $this->change($user, $worldId, function (Player $me) use ($text) { + $this->managed($me)->update(['description' => mb_substr(trim($text), 0, 2000) ?: null]); + }); + } + + public function disband(User $user, int $worldId): array + { + return $this->change($user, $worldId, function (Player $me) { + if ($me->membership?->role !== TribeMember::LEADER) { + throw new GameRuleViolation('rank', 'Only the leader can disband the tribe.'); + } + Tribe::whereKey($me->membership->tribe_id)->delete(); + }); + } + + /** + * Offer an alliance or a NAP to the tribe with this tag. If they offered the same to + * us already, it holds at once. + */ + public function propose(User $user, int $worldId, string $tag, string $state): array + { + if (! in_array($state, Diplomacy::PACTS, true)) { + throw new GameRuleViolation('not_found', "Unknown pact [$state]."); + } + + return $this->change($user, $worldId, function (Player $me, CarbonImmutable $now) use ($worldId, $tag, $state) { + [$tribe, $other] = $this->counterpart($me, $worldId, $tag); + if (Diplomacy::protects(TribeRelations::between($me, $this->anyMember($other), $now))) { + throw new GameRuleViolation('pact_active', 'A pact holds already; end it first.'); + } + $theirs = TribeRelation::where('tribe_id', $other->id)->where('other_tribe_id', $tribe->id)->first(); + if ($theirs && $theirs->state === $state && ! $theirs->confirmed_at) { + $this->seal($tribe, $other, $state, $now); + + return; + } + TribeRelation::updateOrCreate(['tribe_id' => $tribe->id, 'other_tribe_id' => $other->id], ['state' => $state, 'confirmed_at' => null, 'ends_at' => null]); + $this->both($tribe, $other, 'pact_proposed', ['state' => $state, 'from' => $tribe->tag, 'to' => $other->tag], $now); + }); + } + + /** Accept the pact another tribe offered. */ + public function accept(User $user, int $worldId, int $otherTribeId): array + { + return $this->change($user, $worldId, function (Player $me, CarbonImmutable $now) use ($otherTribeId) { + $tribe = $this->managed($me); + $theirs = TribeRelation::where('tribe_id', $otherTribeId)->where('other_tribe_id', $tribe->id)->whereNull('confirmed_at')->whereIn('state', Diplomacy::PACTS)->first() + ?? throw new GameRuleViolation('not_found', 'No such offer.'); + $this->seal($tribe, Tribe::findOrFail($otherTribeId), $theirs->state, $now); + }); + } + + /** + * Whatever stands between us and them, undone from our side: a pact starts its notice + * period, our offer is withdrawn, their offer turned down, our enmity dropped. + */ + public function end(User $user, int $worldId, int $otherTribeId): array + { + return $this->change($user, $worldId, function (Player $me, CarbonImmutable $now) use ($otherTribeId) { + $tribe = $this->managed($me); + $other = Tribe::where('world_id', $tribe->world_id)->find($otherTribeId) ?? throw new GameRuleViolation('not_found', 'No such tribe.'); + $ours = TribeRelation::where('tribe_id', $tribe->id)->where('other_tribe_id', $other->id)->first(); + $theirs = TribeRelation::where('tribe_id', $other->id)->where('other_tribe_id', $tribe->id)->first(); + $relation = TribeRelations::between($me, $this->anyMember($other), $now); + if (in_array($relation, Diplomacy::PACTS, true)) { + if (! $ours->ends_at) { + $endsAt = $now->addSeconds((new Diplomacy($tribe->world->gameConfig()))->noticeSeconds()); + TribeRelation::whereKey([$ours->id, $theirs->id])->update(['ends_at' => $endsAt]); + $this->both($tribe, $other, 'pact_ending', ['state' => $relation, 'by' => $tribe->tag, 'ends_at' => self::iso($endsAt)], $now); + } + + return; + } + if ($ours) { + $ours->delete(); + $this->both($tribe, $other, $ours->state === Diplomacy::ENEMY ? 'enemy_cleared' : 'pact_withdrawn', ['state' => $ours->state, 'by' => $tribe->tag], $now); + } elseif ($theirs && ! $theirs->confirmed_at && $theirs->state !== Diplomacy::ENEMY) { + $theirs->delete(); + $this->both($tribe, $other, 'pact_refused', ['state' => $theirs->state, 'by' => $tribe->tag], $now); + } + }); + } + + /** Declare the tribe with this tag an enemy; a pact has to end first. */ + public function enemy(User $user, int $worldId, string $tag): array + { + return $this->change($user, $worldId, function (Player $me, CarbonImmutable $now) use ($worldId, $tag) { + [$tribe, $other] = $this->counterpart($me, $worldId, $tag); + if (Diplomacy::protects(TribeRelations::between($me, $this->anyMember($other), $now))) { + throw new GameRuleViolation('pact_active', 'A pact holds; end it first.'); + } + TribeRelation::updateOrCreate(['tribe_id' => $tribe->id, 'other_tribe_id' => $other->id], ['state' => Diplomacy::ENEMY, 'confirmed_at' => $now, 'ends_at' => null]); + $this->both($tribe, $other, 'enemy_declared', ['by' => $tribe->tag, 'against' => $other->tag], $now); + }); + } + + /** Both rows of a pact, confirmed now. */ + private function seal(Tribe $tribe, Tribe $other, string $state, CarbonImmutable $now): void + { + foreach ([[$tribe, $other], [$other, $tribe]] as [$a, $b]) { + TribeRelation::updateOrCreate(['tribe_id' => $a->id, 'other_tribe_id' => $b->id], ['state' => $state, 'confirmed_at' => $now, 'ends_at' => null]); + } + $this->both($tribe, $other, 'pact_sealed', ['state' => $state, 'between' => [$tribe->tag, $other->tag]], $now); + } + + /** @return array{0: Tribe, 1: Tribe} the player's tribe (managed by them) and the other one */ + private function counterpart(Player $me, int $worldId, string $tag): array + { + $tribe = $this->managed($me); + $other = Tribe::where('world_id', $worldId)->where('tag', trim($tag))->first() + ?? throw new GameRuleViolation('no_tribe_tag', 'No tribe with that tag.'); + if ($other->id === $tribe->id) { + throw new GameRuleViolation('own_tribe', 'That is your own tribe.'); + } + + return [$tribe, $other]; + } + + /** A member stands in for the tribe when relations are worked out between players. */ + private function anyMember(Tribe $tribe): ?Player + { + return Player::whereKey(TribeMember::where('tribe_id', $tribe->id)->value('player_id'))->first(); + } + + /** The player's tribe, if they lead it or sit on its council. */ + private function managed(Player $me): Tribe + { + $membership = $me->membership ?? throw new GameRuleViolation('no_tribe', 'You are not in a tribe.'); + if (! in_array($membership->role, [TribeMember::LEADER, TribeMember::COUNCIL], true)) { + throw new GameRuleViolation('rank', 'Your rank does not allow that.'); + } + + return Tribe::findOrFail($membership->tribe_id); + } + + /** @param array $payload */ + private function both(Tribe $a, Tribe $b, string $type, array $payload, CarbonImmutable $now): void + { + TribeEvent::note($a->id, $type, $payload, $now); + TribeEvent::note($b->id, $type, $payload, $now); + } + + /** Run a change in a transaction on an open world, then answer with the page. */ + private function change(User $user, int $worldId, \Closure $change): array + { + $me = $this->player($user, $worldId); + $me->world->ensureOpen(); + try { + DB::transaction(function () use ($me, $change) { + $me->load('membership'); + $change($me, now()->toImmutable()); + }); + } finally { + Push::flush(); + } + + return $this->show($user, $worldId); + } + + private function player(User $user, int $worldId): Player + { + return Player::with('world')->where('user_id', $user->id)->where('world_id', $worldId)->first() + ?? throw new GameRuleViolation('not_found', 'You have not joined this world.'); + } + + private function present(Tribe $tribe, TribeMember $mine, CarbonImmutable $now): array + { + TribeRelations::prune($tribe->id, $now); + $members = $tribe->members()->with('player')->get(); + $points = Village::whereIn('player_id', $members->pluck('player_id'))->groupBy('player_id') + ->selectRaw('player_id, SUM(points) as points, COUNT(*) as villages')->get()->keyBy('player_id'); + $manages = in_array($mine->role, [TribeMember::LEADER, TribeMember::COUNCIL], true); + + return [ + ...$tribe->summary(), + 'description' => $tribe->description, + 'role' => $mine->role, + 'members' => $members->map(fn (TribeMember $m) => [ + 'player' => ['id' => $m->player->id, 'name' => $m->player->name], + 'role' => $m->role, + 'points' => (int) ($points[$m->player_id]->points ?? 0), + 'villages' => (int) ($points[$m->player_id]->villages ?? 0), + ])->sortByDesc('points')->values()->all(), + 'invites' => $manages ? $tribe->invites()->with('player')->get() + ->map(fn (TribeInvite $i) => ['player' => ['id' => $i->player->id, 'name' => $i->player->name], 'at' => self::iso($i->created_at->toImmutable())])->all() : [], + 'relations' => $this->relations($tribe, $now), + 'events' => TribeEvent::where('tribe_id', $tribe->id)->orderByDesc('happened_at')->orderByDesc('id')->limit(30)->get() + ->map(fn (TribeEvent $e) => ['type' => $e->type, 'payload' => $e->payload, 'at' => self::iso($e->happened_at)])->all(), + ]; + } + + /** + * What stands between this tribe and others, one line each: a pact that holds (or + * runs out at ends_at), our offer, their offer, our enmity, theirs. + */ + private function relations(Tribe $tribe, CarbonImmutable $now): array + { + $rows = TribeRelation::with('other')->where('tribe_id', $tribe->id)->get(); + $incoming = TribeRelation::where('other_tribe_id', $tribe->id)->get()->keyBy('tribe_id'); + $others = Tribe::whereIn('id', $incoming->keys())->get()->keyBy('id'); + $lines = []; + foreach ($rows as $ours) { + $theirs = $incoming[$ours->other_tribe_id] ?? null; + $status = match (true) { + $ours->state === Diplomacy::ENEMY => 'enemy', + ! $ours->confirmed_at => 'offered', + $ours->ends_at !== null => 'ending', + default => 'holds', + }; + if ($status === 'holds' || $status === 'ending') { + if (! $theirs || ! $theirs->confirmed_at) { + continue; + } + } + $lines[] = ['tribe' => $ours->other->summary(), 'state' => $ours->state, 'status' => $status, 'ends_at' => $ours->ends_at ? self::iso($ours->ends_at) : null]; + } + foreach ($incoming as $theirs) { + $other = $others[$theirs->tribe_id] ?? null; + if (! $other) { + continue; + } + if ($theirs->state === Diplomacy::ENEMY) { + $lines[] = ['tribe' => $other->summary(), 'state' => Diplomacy::ENEMY, 'status' => 'hostile', 'ends_at' => null]; + } elseif (! $theirs->confirmed_at) { + $lines[] = ['tribe' => $other->summary(), 'state' => $theirs->state, 'status' => 'incoming', 'ends_at' => null]; + } + } + + return $lines; + } + + private static function iso(CarbonImmutable $at): string + { + return $at->utc()->format('Y-m-d\TH:i:s.v\Z'); + } +} diff --git a/app/Engine/Rally.php b/app/Engine/Rally.php index b58bd37..19ce269 100644 --- a/app/Engine/Rally.php +++ b/app/Engine/Rally.php @@ -9,6 +9,7 @@ use App\Game\Combat\LootCalculator; use App\Game\Combat\Raids; use App\Game\GameRuleViolation; use App\Game\Travel\TravelTime; +use App\Game\Tribes\Diplomacy; use App\Models\Building; use App\Models\GameEvent; use App\Models\Movement; @@ -576,7 +577,10 @@ final class Rally } } - /** Attacks on own villages, support for barbarians, and anything during beginner protection are refused. */ + /** + * Attacks on own villages, on the own tribe and on allies or NAP partners, support for + * barbarians, and anything during beginner protection are refused. + */ private function checkTarget(string $type, Village $target, CarbonImmutable $now): void { if ($type === Movement::SUPPORT) { @@ -592,6 +596,11 @@ final class Rally if ($target->player_id === $this->village->player_id) { throw new GameRuleViolation('own_village', 'That is your own village.'); } + // Tribe members, allies and NAP partners keep the peace. + $relation = Tribes::between($this->village->player, $target->player, $now); + if (Diplomacy::protects($relation)) { + throw new GameRuleViolation($relation === Diplomacy::TRIBE ? 'own_tribe' : 'pact', 'Your tribes are at peace.'); + } if ($this->protectedUntil($target->player)->greaterThan($now)) { throw new GameRuleViolation('protected', 'That player is under beginner protection.'); } diff --git a/app/Engine/Tribes.php b/app/Engine/Tribes.php new file mode 100644 index 0000000..7a3f56b --- /dev/null +++ b/app/Engine/Tribes.php @@ -0,0 +1,54 @@ +tribeId(); + $theirs = $b?->tribeId(); + if ($mine === null || $theirs === null || $mine === $theirs) { + return Diplomacy::relation($mine, $theirs, [], $now); + } + $rows = TribeRelation::where(fn ($q) => $q->where('tribe_id', $mine)->where('other_tribe_id', $theirs)) + ->orWhere(fn ($q) => $q->where('tribe_id', $theirs)->where('other_tribe_id', $mine)) + ->get()->map->row(); + + return Diplomacy::relation($mine, $theirs, $rows, $now); + } + + /** + * Every other tribe this one has a relation with: tribe id => relation. + * + * @return array + */ + public static function relationsOf(?int $tribeId, CarbonImmutable $now): array + { + if ($tribeId === null) { + return []; + } + $rows = TribeRelation::where('tribe_id', $tribeId)->orWhere('other_tribe_id', $tribeId)->get()->map->row(); + $out = []; + foreach ($rows as $row) { + $other = $row['tribe_id'] === $tribeId ? $row['other_tribe_id'] : $row['tribe_id']; + $out[$other] ??= Diplomacy::relation($tribeId, $other, $rows, $now); + } + + return array_filter($out, fn (string $r) => $r !== Diplomacy::NONE); + } + + /** Drop pacts whose notice has run out. */ + public static function prune(int $tribeId, CarbonImmutable $now): void + { + TribeRelation::where(fn ($q) => $q->where('tribe_id', $tribeId)->orWhere('other_tribe_id', $tribeId)) + ->whereNotNull('ends_at')->where('ends_at', '<=', Engine::stamp($now))->delete(); + } +} diff --git a/app/Game/Tribes/Diplomacy.php b/app/Game/Tribes/Diplomacy.php new file mode 100644 index 0000000..febdb78 --- /dev/null +++ b/app/Game/Tribes/Diplomacy.php @@ -0,0 +1,93 @@ +config->get('tribes.notice_hours', 24) * 3600 / $this->config->speed())); + } + + public function maxMembers(): int + { + return (int) $this->config->get('tribes.max_members', 25); + } + + /** + * The relation between two tribes, from the rows between them (both directions). + * + * @param iterable $rows + */ + public static function relation(?int $mine, ?int $theirs, iterable $rows, CarbonImmutable $now): string + { + if ($mine === null || $theirs === null) { + return self::NONE; + } + if ($mine === $theirs) { + return self::TRIBE; + } + $ours = $their = null; + foreach ($rows as $row) { + if ($row['tribe_id'] === $mine && $row['other_tribe_id'] === $theirs) { + $ours = $row; + } elseif ($row['tribe_id'] === $theirs && $row['other_tribe_id'] === $mine) { + $their = $row; + } + } + $holds = fn (?array $r, string $state) => $r && $r['state'] === $state && $r['confirmed'] && ($r['ends_at'] === null || $r['ends_at']->greaterThan($now)); + foreach (self::PACTS as $pact) { + if ($holds($ours, $pact) && $holds($their, $pact)) { + return $pact; + } + } + if (($ours['state'] ?? null) === self::ENEMY || ($their['state'] ?? null) === self::ENEMY) { + return self::ENEMY; + } + + return self::NONE; + } + + /** Whether a relation forbids attacks between the two. */ + public static function protects(string $relation): bool + { + return in_array($relation, [self::TRIBE, self::ALLY, self::NAP], true); + } + + /** 3 to 32 characters, letters, digits, spaces and a few marks. */ + public static function validName(string $name): bool + { + return (bool) preg_match('/^[\p{L}\p{N}][\p{L}\p{N} \'\-_.&]{1,30}[\p{L}\p{N}.]$/u', $name); + } + + /** 2 to 6 characters, letters, digits and - _ . */ + public static function validTag(string $tag): bool + { + return (bool) preg_match('/^[\p{L}\p{N}\-_.]{2,6}$/u', $tag); + } +} diff --git a/app/Models/Player.php b/app/Models/Player.php index fd81d63..29fb28c 100644 --- a/app/Models/Player.php +++ b/app/Models/Player.php @@ -5,6 +5,7 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; use Illuminate\Database\Eloquent\Relations\HasMany; +use Illuminate\Database\Eloquent\Relations\HasOne; class Player extends Model { @@ -20,6 +21,17 @@ class Player extends Model return $this->belongsTo(World::class); } + public function membership(): HasOne + { + return $this->hasOne(TribeMember::class); + } + + /** The tribe the player belongs to, if any. */ + public function tribeId(): ?int + { + return $this->membership?->tribe_id; + } + public function villages(): HasMany { return $this->hasMany(Village::class); diff --git a/app/Models/Tribe.php b/app/Models/Tribe.php new file mode 100644 index 0000000..e72a504 --- /dev/null +++ b/app/Models/Tribe.php @@ -0,0 +1,39 @@ +belongsTo(World::class); + } + + public function members(): HasMany + { + return $this->hasMany(TribeMember::class)->orderBy('id'); + } + + public function invites(): HasMany + { + return $this->hasMany(TribeInvite::class)->orderBy('id'); + } + + /** What this tribe holds towards others. */ + public function relations(): HasMany + { + return $this->hasMany(TribeRelation::class); + } + + /** @return array{id: int, name: string, tag: string} */ + public function summary(): array + { + return ['id' => $this->id, 'name' => $this->name, 'tag' => $this->tag]; + } +} diff --git a/app/Models/TribeEvent.php b/app/Models/TribeEvent.php new file mode 100644 index 0000000..44434a3 --- /dev/null +++ b/app/Models/TribeEvent.php @@ -0,0 +1,27 @@ + 'array', 'happened_at' => 'immutable_datetime']; + } + + /** @param array $payload */ + public static function note(int $tribeId, string $type, array $payload, CarbonImmutable $at): void + { + self::create(['tribe_id' => $tribeId, 'type' => $type, 'payload' => $payload, 'happened_at' => $at]); + } +} diff --git a/app/Models/TribeInvite.php b/app/Models/TribeInvite.php new file mode 100644 index 0000000..6c5ce1c --- /dev/null +++ b/app/Models/TribeInvite.php @@ -0,0 +1,21 @@ +belongsTo(Tribe::class); + } + + public function player(): BelongsTo + { + return $this->belongsTo(Player::class); + } +} diff --git a/app/Models/TribeMember.php b/app/Models/TribeMember.php new file mode 100644 index 0000000..b520339 --- /dev/null +++ b/app/Models/TribeMember.php @@ -0,0 +1,27 @@ +belongsTo(Tribe::class); + } + + public function player(): BelongsTo + { + return $this->belongsTo(Player::class); + } +} diff --git a/app/Models/TribeRelation.php b/app/Models/TribeRelation.php new file mode 100644 index 0000000..1c453ab --- /dev/null +++ b/app/Models/TribeRelation.php @@ -0,0 +1,31 @@ + 'immutable_datetime', 'ends_at' => 'immutable_datetime']; + } + + public function other(): BelongsTo + { + return $this->belongsTo(Tribe::class, 'other_tribe_id'); + } + + /** @return array{tribe_id: int, other_tribe_id: int, state: string, confirmed: bool, ends_at: CarbonImmutable|null} */ + public function row(): array + { + return ['tribe_id' => $this->tribe_id, 'other_tribe_id' => $this->other_tribe_id, 'state' => $this->state, 'confirmed' => $this->confirmed_at !== null, 'ends_at' => $this->ends_at]; + } +} diff --git a/app/Models/World.php b/app/Models/World.php index 6b3dde7..ff82d61 100644 --- a/app/Models/World.php +++ b/app/Models/World.php @@ -35,6 +35,7 @@ class World extends Model 'combat' => config('game.combat'), 'movement' => config('game.movement'), 'raids' => config('game.raids'), + 'tribes' => config('game.tribes'), 'quests' => config('game.quests'), ], $this->config ?? []); } diff --git a/app/Presenters/VillagePresenter.php b/app/Presenters/VillagePresenter.php index 2e84ef5..f9c3012 100644 --- a/app/Presenters/VillagePresenter.php +++ b/app/Presenters/VillagePresenter.php @@ -13,6 +13,7 @@ use App\Models\Building; use App\Models\BuildOrder; use App\Models\RecruitOrder; use App\Models\Report; +use App\Models\TribeInvite; use App\Models\Village; use Carbon\CarbonImmutable; @@ -79,6 +80,8 @@ final class VillagePresenter 'villages' => Village::where('player_id', $village->player_id)->orderBy('id')->get(['id', 'name', 'x', 'y', 'points']) ->map(fn (Village $v) => ['id' => $v->id, 'name' => $v->name, 'x' => $v->x, 'y' => $v->y, 'points' => $v->points])->all(), 'quests' => Quests::summary($village), + // The player's tribe for the menu, and invites waiting for the badge. + 'tribe' => self::tribe($village), 'season' => SeasonPresenter::present($village->world), 'unread_reports' => Report::where('player_id', $village->player_id)->whereNull('read_at')->count(), 'builders' => $sim->builders(), @@ -186,6 +189,17 @@ final class VillagePresenter ]; } + /** @return array{tribe: array{id: int, name: string, tag: string, role: string}|null, invites: int} */ + private static function tribe(Village $village): array + { + $membership = $village->player?->membership()->with('tribe')->first(); + + return [ + 'tribe' => $membership ? [...$membership->tribe->summary(), 'role' => $membership->role] : null, + 'invites' => $village->player_id ? TribeInvite::where('player_id', $village->player_id)->count() : 0, + ]; + } + /** Coins and noble slots of the player, and what a coin costs. */ private static function conquest(Village $village): array { diff --git a/app/Websocket/Controllers/TribeController.php b/app/Websocket/Controllers/TribeController.php new file mode 100644 index 0000000..60590c0 --- /dev/null +++ b/app/Websocket/Controllers/TribeController.php @@ -0,0 +1,99 @@ +tribes(fn (Tribes $t, $u, $w) => $t->show($u, $w)); + } + + public function list() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->list($u, $w)); + } + + public function found() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->found($u, $w, (string) request('name'), (string) request('tag'))); + } + + public function invite() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->invite($u, $w, (string) request('player'))); + } + + public function cancelInvite() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->cancelInvite($u, $w, (int) request('player_id'))); + } + + public function join() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->join($u, $w, (int) request('tribe_id'))); + } + + public function refuse() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->refuse($u, $w, (int) request('tribe_id'))); + } + + public function leave() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->leave($u, $w)); + } + + public function kick() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->kick($u, $w, (int) request('player_id'))); + } + + public function role() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->role($u, $w, (int) request('player_id'), (string) request('role'))); + } + + public function describe() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->describe($u, $w, (string) request('description'))); + } + + public function disband() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->disband($u, $w)); + } + + public function propose() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->propose($u, $w, (string) request('tag'), (string) request('state'))); + } + + public function accept() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->accept($u, $w, (int) request('tribe_id'))); + } + + public function end() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->end($u, $w, (int) request('tribe_id'))); + } + + public function enemy() + { + return $this->tribes(fn (Tribes $t, $u, $w) => $t->enemy($u, $w, (string) request('tag'))); + } + + private function tribes(Closure $intent) + { + return $this->play(fn () => $intent(app(Tribes::class), auth()->user(), (int) request('world_id'))); + } +} diff --git a/config/game/tribes.php b/config/game/tribes.php new file mode 100644 index 0000000..6c8c5b1 --- /dev/null +++ b/config/game/tribes.php @@ -0,0 +1,12 @@ + 25, + + // Ending an alliance or a non-aggression pact takes this long (hours at world speed 1): + // until then it still holds, so nobody can betray a partner in the same breath. + 'notice_hours' => 24, +]; diff --git a/database/migrations/2026_10_31_150000_create_tribes.php b/database/migrations/2026_10_31_150000_create_tribes.php new file mode 100644 index 0000000..422d638 --- /dev/null +++ b/database/migrations/2026_10_31_150000_create_tribes.php @@ -0,0 +1,68 @@ +id(); + $table->foreignId('world_id')->constrained()->cascadeOnDelete(); + $table->string('name', 32); + $table->string('tag', 6); + $table->text('description')->nullable(); + $table->timestamps(); + $table->unique(['world_id', 'name']); + $table->unique(['world_id', 'tag']); + }); + Schema::create('tribe_members', function (Blueprint $table) { + $table->id(); + $table->foreignId('tribe_id')->constrained()->cascadeOnDelete(); + // A player belongs to one tribe at most. + $table->foreignId('player_id')->unique()->constrained()->cascadeOnDelete(); + $table->string('role', 16); + $table->timestamps(); + }); + Schema::create('tribe_invites', function (Blueprint $table) { + $table->id(); + $table->foreignId('tribe_id')->constrained()->cascadeOnDelete(); + $table->foreignId('player_id')->constrained()->cascadeOnDelete(); + $table->foreignId('invited_by')->nullable()->constrained('players')->nullOnDelete(); + $table->timestamps(); + $table->unique(['tribe_id', 'player_id']); + }); + // One row per direction: what tribe_id holds towards other_tribe_id. An alliance or + // NAP counts once both rows are confirmed; ends_at is the end of its notice period. + Schema::create('tribe_relations', function (Blueprint $table) { + $table->id(); + $table->foreignId('tribe_id')->constrained()->cascadeOnDelete(); + $table->foreignId('other_tribe_id')->constrained('tribes')->cascadeOnDelete(); + $table->string('state', 8); + $table->dateTime('confirmed_at', 3)->nullable(); + $table->dateTime('ends_at', 3)->nullable(); + $table->timestamps(); + $table->unique(['tribe_id', 'other_tribe_id']); + }); + Schema::create('tribe_events', function (Blueprint $table) { + $table->id(); + $table->foreignId('tribe_id')->constrained()->cascadeOnDelete(); + $table->string('type', 32); + $table->json('payload'); + $table->dateTime('happened_at', 3); + $table->index(['tribe_id', 'happened_at']); + }); + } + + public function down(): void + { + Schema::dropIfExists('tribe_events'); + Schema::dropIfExists('tribe_relations'); + Schema::dropIfExists('tribe_invites'); + Schema::dropIfExists('tribe_members'); + Schema::dropIfExists('tribes'); + } +}; diff --git a/docs/architecture.md b/docs/architecture.md index d466311..1013b89 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -159,7 +159,7 @@ A building entry looks like this (numbers start TW-like): | `recruit_orders` | village_id, building_id, unit, count, done, seconds_per_unit, starts_at, finishes_at, game_event_id | | `food_deliveries` | village_id, amount, delivered_at. Feeds the 24h import average; each row's expiry is an event | | `movements` | world_id, player_id (whose troops), type (attack/support/return), mode, origin_id, target_id, units json, cargo json null, catapult_target null, rng_seed, sent_at, arrives_at, visible_at. Trade, merchants and destroyed_at come with M5 | -| `tribes`, `tribe_members`, `tribe_relations` | name, tag; player_id, role; tribe_id, other_tribe_id, state (ally/nap/enemy). Arrives in M6 | +| `tribes`, `tribe_members`, `tribe_invites`, `tribe_relations`, `tribe_events` | world_id, name, tag, description; tribe_id, player_id (unique), role; tribe_id, player_id, invited_by; tribe_id, other_tribe_id, state (ally/nap/enemy), confirmed_at, ends_at; tribe_id, type, payload, happened_at | | `player_quests`, `player_counters` | player_id, quest, claimed_at; player_id, key, value. Progress is derived, not stored | | `level_rewards` | player_id, village_id (where reached), type, level, reward json, reached_at, claimed_at null. unique(player_id, type, level) | | `reports` | player_id, type (attack/defense/support), payload json (a snapshot with village names, units, losses, loot), happened_at, read_at | @@ -232,7 +232,7 @@ The visibility radius decides two things: ### Diplomacy -Tribes arrive in M6, with ally, NAP (non-aggression pact), and enemy states between them. Until then, every other player is hostile. Hostility is checked at encounter time, not at send time. +See "Tribes". Encounters (M5) will check hostility at encounter time, not at send time. ## Raids @@ -256,6 +256,15 @@ 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). +## Tribes + +Players band together in tribes (`Tribes` action, `tribe.*` over WS, rules in `Diplomacy`, `config/game/tribes.php`). + +- A player founds a tribe (name 3 to 32 characters, tag 2 to 6, both unique per world) and leads it. The leader and the council invite players by name; an invited player joins (up to `max_members`, 25) or refuses. A player belongs to one tribe at most. Members leave; the council removes plain members, the leader anyone. The leader sets roles (leader, council, member); making someone else leader hands the tribe over. A leader can't leave while others remain; the last member leaving, or the leader disbanding, ends the tribe. +- Diplomacy runs between tribes, one row per direction (`tribe_relations`). An alliance or a non-aggression pact is offered by one tribe and holds once the other accepts (or offers the same back); ending it from either side starts `notice_hours` (24, at world speed) of notice, and it holds until then, so nobody betrays a partner in the same breath. Enmity is declared by one side alone and needs no pact to end first, only to be declared. The council and the leader run diplomacy. +- Members of one tribe, allies and NAP partners can't attack each other (`own_tribe`, `pact` at the rally point). Support goes to anyone, as before. +- The tribe page (`tribe.show`) carries the members with points, the invites sent, the relations (holds, ending with `ends_at`, offered, incoming, enemy, hostile) and the last 30 events of its news; `tribe.list` every tribe with its size, points and relation. The village payload carries `tribe: {tribe, invites}` for the menu badge. The ranking has a tribe kind and tags players with their tribe. + ## Seasons A world is a season with a winner (`world.season`, rules in `Season`, rows in `Seasons`). diff --git a/docs/roadmap.md b/docs/roadmap.md index ba92c9d..191299d 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -82,7 +82,8 @@ The world pushes back, so a world with few players is a game too: something thre - [x] Loyalty (lazy regeneration), noble drop per hit, conquest transfers the village - [x] Coins at the academy, rising noble cost per world config -- [ ] Tribes with ally/NAP/enemy relations, applied at encounter time +- [x] Tribes with members, roles and invites; alliances and NAPs accepted by both and ended with notice, enmity declared alone; no attacks within a tribe or across a pact +- [ ] Tribe relations applied at encounter time (with M5) - [x] Village switcher in the header - [ ] Overviews across villages (production, troops, buildings per village) - [x] Restart on the same world after losing every village diff --git a/tests/Feature/TribeTest.php b/tests/Feature/TribeTest.php new file mode 100644 index 0000000..8cc55aa --- /dev/null +++ b/tests/Feature/TribeTest.php @@ -0,0 +1,151 @@ + $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00'))); + +function tribes(): Tribes +{ + return app(Tribes::class); +} + +/** A player's village with its own tribe (tag from the name), they lead it. */ +function tribeOf(Village $village, string $tag): Village +{ + tribes()->found(owner($village), $village->world_id, "Tribe $tag", $tag); + + return $village->fresh(); +} + +function attackFrom(Village $from, Village $to): Village +{ + $from->buildings()->firstOrCreate(['type' => 'rally_point'], ['level' => 1]); + $from->troops()->firstOrCreate(['home_village_id' => $from->id, 'unit' => 'spear'], ['count' => 10]); + + return app(SendTroops::class)(owner($from), $from->id, 'attack', $to->x, $to->y, ['spear' => 1], null, null); +} + +it('founds a tribe, invites, and lets the invited join', function () { + $leader = startVillage(); + $other = startVillage(); + $page = tribes()->found(owner($leader), $leader->world_id, 'Dorfrat', 'DRF'); + expect($page['tribe'])->toMatchArray(['name' => 'Dorfrat', 'tag' => 'DRF', 'role' => 'leader']) + ->and($page['tribe']['members'])->toHaveCount(1); + + tribes()->invite(owner($leader), $leader->world_id, $other->player->name); + $invited = tribes()->show(owner($other), $other->world_id); + expect($invited['tribe'])->toBeNull() + ->and($invited['invites'][0]['tribe']['tag'])->toBe('DRF') + ->and(shown($other)['tribe'])->toBe(['tribe' => null, 'invites' => 1]); + + $joined = tribes()->join(owner($other), $other->world_id, $invited['invites'][0]['tribe']['id']); + expect($joined['tribe'])->toMatchArray(['tag' => 'DRF', 'role' => 'member']) + ->and($joined['tribe']['members'])->toHaveCount(2) + ->and($joined['invites'])->toBe([]) + ->and(collect($joined['tribe']['events'])->pluck('type')->all())->toContain('joined', 'invited', 'founded') + ->and(shown($other)['tribe']['tribe'])->toMatchArray(['tag' => 'DRF', 'role' => 'member']); +}); + +it('checks names, tags and ranks', function () { + $leader = tribeOf(startVillage(), 'DRF'); + $member = startVillage(); + tribes()->invite(owner($leader), $leader->world_id, $member->player->name); + tribes()->join(owner($member), $member->world_id, Tribe::where('tag', 'DRF')->value('id')); + $third = startVillage(); + + expect(rule(fn () => tribes()->found(owner($third), $third->world_id, 'Other', 'DRF')))->toBe('tribe_taken') + ->and(rule(fn () => tribes()->found(owner($third), $third->world_id, 'x', 'Y')))->toBe('tribe_name') + ->and(rule(fn () => tribes()->found(owner($member), $member->world_id, 'Second', 'SEC')))->toBe('in_tribe') + ->and(rule(fn () => tribes()->invite(owner($member), $member->world_id, $third->player->name)))->toBe('rank') + ->and(rule(fn () => tribes()->join(owner($third), $third->world_id, Tribe::where('tag', 'DRF')->value('id'))))->toBe('not_found') + ->and(rule(fn () => tribes()->leave(owner($leader), $leader->world_id)))->toBe('hand_over'); +}); + +it('hands the tribe over, removes members, and ends with its last member', function () { + $leader = tribeOf(startVillage(), 'DRF'); + $member = startVillage(); + $tribeId = Tribe::where('tag', 'DRF')->value('id'); + tribes()->invite(owner($leader), $leader->world_id, $member->player->name); + tribes()->join(owner($member), $member->world_id, $tribeId); + + tribes()->role(owner($leader), $leader->world_id, $member->player_id, 'leader'); + $page = tribes()->show(owner($leader), $leader->world_id); + expect($page['tribe']['role'])->toBe('council'); + + tribes()->kick(owner($member), $member->world_id, $leader->player_id); + expect(tribes()->show(owner($leader), $leader->world_id)['tribe'])->toBeNull(); + + tribes()->leave(owner($member), $member->world_id); + expect(Tribe::count())->toBe(0); +}); + +it('seals an alliance only when both tribes agree, and keeps the peace while it holds', function () { + $a = tribeOf(startVillage(), 'AAA'); + $b = tribeOf(startVillage(), 'BBB'); + $this->travel(4)->days(); + + $offered = tribes()->propose(owner($a), $a->world_id, 'BBB', 'ally'); + expect($offered['tribe']['relations'][0])->toMatchArray(['state' => 'ally', 'status' => 'offered']); + $incoming = tribes()->show(owner($b), $b->world_id)['tribe']['relations'][0]; + expect($incoming)->toMatchArray(['state' => 'ally', 'status' => 'incoming']); + + $sealed = tribes()->accept(owner($b), $b->world_id, $incoming['tribe']['id']); + expect($sealed['tribe']['relations'])->toBe([['tribe' => Tribe::where('tag', 'AAA')->first()->summary(), 'state' => 'ally', 'status' => 'holds', 'ends_at' => null]]) + ->and(rule(fn () => attackFrom($a, $b)))->toBe('pact'); + + // Ending it takes a day of notice; the alliance holds until then. + $ending = tribes()->end(owner($a), $a->world_id, Tribe::where('tag', 'BBB')->value('id')); + expect($ending['tribe']['relations'][0])->toMatchArray(['status' => 'ending', 'ends_at' => '2026-11-03T12:00:00.000Z']) + ->and(rule(fn () => attackFrom($a, $b)))->toBe('pact'); + + $this->travel(1)->days(); + expect(tribes()->show(owner($a), $a->world_id)['tribe']['relations'])->toBe([]); + attackFrom($a, $b); + expect(Movement::where('origin_id', $a->id)->count())->toBe(1); +}); + +it('seals at once when both offered the same, and keeps tribe members from attacking each other', function () { + $a = tribeOf(startVillage(), 'AAA'); + $b = tribeOf(startVillage(), 'BBB'); + tribes()->propose(owner($b), $b->world_id, 'AAA', 'nap'); + $page = tribes()->propose(owner($a), $a->world_id, 'BBB', 'nap'); + expect($page['tribe']['relations'][0])->toMatchArray(['state' => 'nap', 'status' => 'holds']); + + $mate = startVillage(User::factory()->create()); + tribes()->invite(owner($a), $a->world_id, $mate->player->name); + tribes()->join(owner($mate), $mate->world_id, Tribe::where('tag', 'AAA')->value('id')); + $this->travel(4)->days(); + expect(rule(fn () => attackFrom($a, $mate)))->toBe('own_tribe'); +}); + +it('declares enmity alone, but not over a pact', function () { + $a = tribeOf(startVillage(), 'AAA'); + $b = tribeOf(startVillage(), 'BBB'); + tribes()->enemy(owner($a), $a->world_id, 'BBB'); + expect(tribes()->show(owner($b), $b->world_id)['tribe']['relations'][0])->toMatchArray(['state' => 'enemy', 'status' => 'hostile']) + ->and(collect(tribes()->list(owner($b), $b->world_id))->firstWhere('tag', 'AAA')['relation'])->toBe('enemy'); + + tribes()->end(owner($a), $a->world_id, Tribe::where('tag', 'BBB')->value('id')); + tribes()->propose(owner($a), $a->world_id, 'BBB', 'ally'); + tribes()->accept(owner($b), $b->world_id, Tribe::where('tag', 'AAA')->value('id')); + expect(rule(fn () => tribes()->enemy(owner($b), $b->world_id, 'AAA')))->toBe('pact_active'); +}); + +it('ranks tribes by their members points and tags players in the ranking', function () { + $a = tribeOf(startVillage(), 'AAA'); + $b = startVillage(); + $b->update(['points' => 500]); + tribeOf($b, 'BBB'); + + $ranking = app(Ranking::class)->list(owner($a), $a->world_id, 'tribes'); + expect(array_column(array_column($ranking['rows'], 'tribe'), 'tag'))->toBe(['BBB', 'AAA']) + ->and($ranking['rows'][1])->toMatchArray(['rank' => 2, 'members' => 1, 'own' => true]) + ->and(app(Ranking::class)->list(owner($a), $a->world_id, 'players')['rows'][0]['player']['tribe']['tag'])->toBe('BBB'); +}); diff --git a/tests/Pest.php b/tests/Pest.php index 23b8432..13fdc40 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -31,6 +31,7 @@ function gameConfig(array $overrides = []): WorldConfig 'combat' => require "$dir/combat.php", 'movement' => require "$dir/movement.php", 'raids' => require "$dir/raids.php", + 'tribes' => require "$dir/tribes.php", 'quests' => require "$dir/quests.php", ], $overrides); } diff --git a/tests/Unit/Game/DiplomacyTest.php b/tests/Unit/Game/DiplomacyTest.php new file mode 100644 index 0000000..ec1d355 --- /dev/null +++ b/tests/Unit/Game/DiplomacyTest.php @@ -0,0 +1,54 @@ + [ + 'tribe_id' => $from, 'other_tribe_id' => $to, 'state' => $state, 'confirmed' => $confirmed, 'ends_at' => $endsAt ? CarbonImmutable::parse($endsAt) : null, +]; + +it('needs both tribes to confirm an alliance or a NAP', function () use ($now, $row) { + expect(Diplomacy::relation(1, 2, [$row(1, 2, 'ally')], $now))->toBe('none') + ->and(Diplomacy::relation(1, 2, [$row(1, 2, 'ally'), $row(2, 1, 'ally', false)], $now))->toBe('none') + ->and(Diplomacy::relation(1, 2, [$row(1, 2, 'ally'), $row(2, 1, 'ally')], $now))->toBe('ally') + ->and(Diplomacy::relation(2, 1, [$row(1, 2, 'nap'), $row(2, 1, 'nap')], $now))->toBe('nap') + ->and(Diplomacy::relation(1, 2, [$row(1, 2, 'ally'), $row(2, 1, 'nap')], $now))->toBe('none'); +}); + +it('keeps a pact until its notice ends', function () use ($now, $row) { + $ending = fn (string $at) => [$row(1, 2, 'ally', true, $at), $row(2, 1, 'ally', true, $at)]; + + expect(Diplomacy::relation(1, 2, $ending('2026-11-01 12:00:01'), $now))->toBe('ally') + ->and(Diplomacy::relation(1, 2, $ending('2026-11-01 12:00:00'), $now))->toBe('none'); +}); + +it('lets one side declare enmity', function () use ($now, $row) { + expect(Diplomacy::relation(1, 2, [$row(2, 1, 'enemy')], $now))->toBe('enemy') + ->and(Diplomacy::relation(2, 1, [$row(2, 1, 'enemy')], $now))->toBe('enemy'); +}); + +it('knows the own tribe and players without one', function () use ($now) { + expect(Diplomacy::relation(3, 3, [], $now))->toBe('tribe') + ->and(Diplomacy::relation(null, 3, [], $now))->toBe('none') + ->and(Diplomacy::protects('tribe'))->toBeTrue() + ->and(Diplomacy::protects('nap'))->toBeTrue() + ->and(Diplomacy::protects('enemy'))->toBeFalse() + ->and(Diplomacy::protects('none'))->toBeFalse(); +}); + +it('takes a day of notice at world speed', function () { + expect((new Diplomacy(gameConfig()))->noticeSeconds())->toBe(86400) + ->and((new Diplomacy(gameConfig(['world' => ['speed' => 100]])))->noticeSeconds())->toBe(864); +}); + +it('checks names and tags', function () { + expect(Diplomacy::validName('Dorfrat'))->toBeTrue() + ->and(Diplomacy::validName('Die Rote Hand'))->toBeTrue() + ->and(Diplomacy::validName('ab'))->toBeFalse() + ->and(Diplomacy::validName(' padded '))->toBeFalse() + ->and(Diplomacy::validTag('DRF'))->toBeTrue() + ->and(Diplomacy::validTag('X'))->toBeFalse() + ->and(Diplomacy::validTag('TOOLONG'))->toBeFalse() + ->and(Diplomacy::validTag('a b'))->toBeFalse(); +});