feat: tribes and diplomacy: found, invite, roles, leave and kick; alliances and NAPs accepted by both and ended with notice, enmity declared alone; no attacks within a tribe or across a pact; tribe ranking
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
21ed9de726
commit
1a5ae64b29
|
|
@ -10,7 +10,7 @@ use Illuminate\Support\Collection;
|
||||||
use Illuminate\Support\Facades\DB;
|
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).
|
* 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.
|
* 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 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<array<string, mixed>>, own: array{rank: int, page: int}|null} */
|
/** @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
|
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)) {
|
if (! World::whereKey($worldId)->exists() || ! in_array($kind, self::KINDS, true)) {
|
||||||
throw new GameRuleViolation('not_found', 'No such ranking.');
|
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) {
|
$rows = match ($kind) {
|
||||||
'players' => $this->players($worldId),
|
'players' => $this->players($worldId),
|
||||||
|
'tribes' => $this->tribes($worldId),
|
||||||
'villages' => $this->villages($worldId),
|
'villages' => $this->villages($worldId),
|
||||||
default => $this->defeated($worldId, $kind),
|
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);
|
$mine = $ranked->firstWhere('own', true);
|
||||||
$own = $mine ? ['rank' => $mine['rank'], 'page' => (int) ceil($mine['rank'] / self::PER_PAGE)] : null;
|
$own = $mine ? ['rank' => $mine['rank'], 'page' => (int) ceil($mine['rank'] / self::PER_PAGE)] : null;
|
||||||
$pages = max(1, (int) ceil($ranked->count() / self::PER_PAGE));
|
$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]);
|
->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<int, array{id: int, tag: string}>
|
||||||
|
*/
|
||||||
|
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
|
private function villages(int $worldId): Collection
|
||||||
{
|
{
|
||||||
return DB::table('villages')
|
return DB::table('villages')
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,438 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Actions;
|
||||||
|
|
||||||
|
use App\Engine\Push;
|
||||||
|
use App\Engine\Tribes as TribeRelations;
|
||||||
|
use App\Game\GameRuleViolation;
|
||||||
|
use App\Game\Tribes\Diplomacy;
|
||||||
|
use App\Models\Player;
|
||||||
|
use App\Models\Tribe;
|
||||||
|
use App\Models\TribeEvent;
|
||||||
|
use App\Models\TribeInvite;
|
||||||
|
use App\Models\TribeMember;
|
||||||
|
use App\Models\TribeRelation;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Models\Village;
|
||||||
|
use App\Models\World;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
use Illuminate\Support\Facades\DB;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tribes on one world (architecture.md, "Tribes"): founding, invites, members and roles,
|
||||||
|
* and diplomacy. The leader may do everything; the council invites, removes members
|
||||||
|
* and runs diplomacy; members can leave. Every intent answers with show().
|
||||||
|
*/
|
||||||
|
final class Tribes
|
||||||
|
{
|
||||||
|
public const ROLES = [TribeMember::LEADER, TribeMember::COUNCIL, TribeMember::MEMBER];
|
||||||
|
|
||||||
|
/** The player's tribe page: the tribe with members, invites, relations and news, or the invites waiting. */
|
||||||
|
public function show(User $user, int $worldId): array
|
||||||
|
{
|
||||||
|
$me = $this->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<string, mixed> $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');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -9,6 +9,7 @@ use App\Game\Combat\LootCalculator;
|
||||||
use App\Game\Combat\Raids;
|
use App\Game\Combat\Raids;
|
||||||
use App\Game\GameRuleViolation;
|
use App\Game\GameRuleViolation;
|
||||||
use App\Game\Travel\TravelTime;
|
use App\Game\Travel\TravelTime;
|
||||||
|
use App\Game\Tribes\Diplomacy;
|
||||||
use App\Models\Building;
|
use App\Models\Building;
|
||||||
use App\Models\GameEvent;
|
use App\Models\GameEvent;
|
||||||
use App\Models\Movement;
|
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
|
private function checkTarget(string $type, Village $target, CarbonImmutable $now): void
|
||||||
{
|
{
|
||||||
if ($type === Movement::SUPPORT) {
|
if ($type === Movement::SUPPORT) {
|
||||||
|
|
@ -592,6 +596,11 @@ final class Rally
|
||||||
if ($target->player_id === $this->village->player_id) {
|
if ($target->player_id === $this->village->player_id) {
|
||||||
throw new GameRuleViolation('own_village', 'That is your own village.');
|
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)) {
|
if ($this->protectedUntil($target->player)->greaterThan($now)) {
|
||||||
throw new GameRuleViolation('protected', 'That player is under beginner protection.');
|
throw new GameRuleViolation('protected', 'That player is under beginner protection.');
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,54 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Engine;
|
||||||
|
|
||||||
|
use App\Game\Tribes\Diplomacy;
|
||||||
|
use App\Models\Player;
|
||||||
|
use App\Models\TribeRelation;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
|
/** Tribe relations as rows: between two players, and from one tribe to all others. */
|
||||||
|
final class Tribes
|
||||||
|
{
|
||||||
|
/** What $b is to $a: own tribe, ally, NAP partner, enemy, or nothing. */
|
||||||
|
public static function between(?Player $a, ?Player $b, CarbonImmutable $now): string
|
||||||
|
{
|
||||||
|
$mine = $a?->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<int, string>
|
||||||
|
*/
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,93 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Game\Tribes;
|
||||||
|
|
||||||
|
use App\Game\WorldConfig;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Relations between tribes (architecture.md, "Tribes"). An alliance or a non-aggression
|
||||||
|
* pact holds once both tribes confirmed it and until its notice period ends; enmity is
|
||||||
|
* declared by one side alone. Members of one tribe, allies and NAP partners can't attack
|
||||||
|
* each other.
|
||||||
|
*/
|
||||||
|
final class Diplomacy
|
||||||
|
{
|
||||||
|
public const ALLY = 'ally';
|
||||||
|
|
||||||
|
public const NAP = 'nap';
|
||||||
|
|
||||||
|
public const ENEMY = 'enemy';
|
||||||
|
|
||||||
|
public const PACTS = [self::ALLY, self::NAP];
|
||||||
|
|
||||||
|
/** What one player is to another: own tribe, ally, NAP partner, enemy, or nothing. */
|
||||||
|
public const TRIBE = 'tribe';
|
||||||
|
|
||||||
|
public const NONE = 'none';
|
||||||
|
|
||||||
|
public function __construct(private readonly WorldConfig $config) {}
|
||||||
|
|
||||||
|
/** How long ending a pact takes, at world speed. */
|
||||||
|
public function noticeSeconds(): int
|
||||||
|
{
|
||||||
|
return max(1, (int) round($this->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<array{tribe_id: int, other_tribe_id: int, state: string, confirmed: bool, ends_at: CarbonImmutable|null}> $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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -5,6 +5,7 @@ namespace App\Models;
|
||||||
use Illuminate\Database\Eloquent\Model;
|
use Illuminate\Database\Eloquent\Model;
|
||||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasOne;
|
||||||
|
|
||||||
class Player extends Model
|
class Player extends Model
|
||||||
{
|
{
|
||||||
|
|
@ -20,6 +21,17 @@ class Player extends Model
|
||||||
return $this->belongsTo(World::class);
|
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
|
public function villages(): HasMany
|
||||||
{
|
{
|
||||||
return $this->hasMany(Village::class);
|
return $this->hasMany(Village::class);
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,39 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||||
|
|
||||||
|
class Tribe extends Model
|
||||||
|
{
|
||||||
|
protected $guarded = [];
|
||||||
|
|
||||||
|
public function world(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->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];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,27 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
|
||||||
|
/** What happened in a tribe, for its news: joins, leaves, pacts, enmities. */
|
||||||
|
class TribeEvent extends Model
|
||||||
|
{
|
||||||
|
public $timestamps = false;
|
||||||
|
|
||||||
|
protected $guarded = [];
|
||||||
|
|
||||||
|
protected $dateFormat = 'Y-m-d H:i:s.v';
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return ['payload' => 'array', 'happened_at' => 'immutable_datetime'];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** @param array<string, mixed> $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]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,21 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
class TribeInvite extends Model
|
||||||
|
{
|
||||||
|
protected $guarded = [];
|
||||||
|
|
||||||
|
public function tribe(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Tribe::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function player(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Player::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,27 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
class TribeMember extends Model
|
||||||
|
{
|
||||||
|
public const LEADER = 'leader';
|
||||||
|
|
||||||
|
public const COUNCIL = 'council';
|
||||||
|
|
||||||
|
public const MEMBER = 'member';
|
||||||
|
|
||||||
|
protected $guarded = [];
|
||||||
|
|
||||||
|
public function tribe(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Tribe::class);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function player(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(Player::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,31 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
/** What tribe_id holds towards other_tribe_id: a pact (once confirmed by both) or enmity. */
|
||||||
|
class TribeRelation extends Model
|
||||||
|
{
|
||||||
|
protected $guarded = [];
|
||||||
|
|
||||||
|
protected $dateFormat = 'Y-m-d H:i:s.v';
|
||||||
|
|
||||||
|
protected function casts(): array
|
||||||
|
{
|
||||||
|
return ['confirmed_at' => '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];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -35,6 +35,7 @@ class World extends Model
|
||||||
'combat' => config('game.combat'),
|
'combat' => config('game.combat'),
|
||||||
'movement' => config('game.movement'),
|
'movement' => config('game.movement'),
|
||||||
'raids' => config('game.raids'),
|
'raids' => config('game.raids'),
|
||||||
|
'tribes' => config('game.tribes'),
|
||||||
'quests' => config('game.quests'),
|
'quests' => config('game.quests'),
|
||||||
], $this->config ?? []);
|
], $this->config ?? []);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -13,6 +13,7 @@ use App\Models\Building;
|
||||||
use App\Models\BuildOrder;
|
use App\Models\BuildOrder;
|
||||||
use App\Models\RecruitOrder;
|
use App\Models\RecruitOrder;
|
||||||
use App\Models\Report;
|
use App\Models\Report;
|
||||||
|
use App\Models\TribeInvite;
|
||||||
use App\Models\Village;
|
use App\Models\Village;
|
||||||
use Carbon\CarbonImmutable;
|
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'])
|
'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(),
|
->map(fn (Village $v) => ['id' => $v->id, 'name' => $v->name, 'x' => $v->x, 'y' => $v->y, 'points' => $v->points])->all(),
|
||||||
'quests' => Quests::summary($village),
|
'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),
|
'season' => SeasonPresenter::present($village->world),
|
||||||
'unread_reports' => Report::where('player_id', $village->player_id)->whereNull('read_at')->count(),
|
'unread_reports' => Report::where('player_id', $village->player_id)->whereNull('read_at')->count(),
|
||||||
'builders' => $sim->builders(),
|
'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. */
|
/** Coins and noble slots of the player, and what a coin costs. */
|
||||||
private static function conquest(Village $village): array
|
private static function conquest(Village $village): array
|
||||||
{
|
{
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,99 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Websocket\Controllers;
|
||||||
|
|
||||||
|
use App\Actions\Tribes;
|
||||||
|
use App\Websocket\GameController;
|
||||||
|
use Closure;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* tribe.show|list|found|invite|cancelInvite|join|refuse|leave|kick|role|describe|disband|propose|accept|end|enemy,
|
||||||
|
* each with world_id. All but list answer with the tribe page (Tribes::show).
|
||||||
|
*/
|
||||||
|
class TribeController extends GameController
|
||||||
|
{
|
||||||
|
public function show()
|
||||||
|
{
|
||||||
|
return $this->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')));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,12 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
// Tribes and their diplomacy (architecture.md, "Tribes").
|
||||||
|
|
||||||
|
return [
|
||||||
|
// Players per tribe.
|
||||||
|
'max_members' => 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,
|
||||||
|
];
|
||||||
|
|
@ -0,0 +1,68 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
// Tribes, their members and invites, the diplomacy between them, and what happened in them.
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('tribes', function (Blueprint $table) {
|
||||||
|
$table->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');
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
@ -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 |
|
| `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 |
|
| `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 |
|
| `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 |
|
| `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) |
|
| `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 |
|
| `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
|
### 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
|
## 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`).
|
- 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).
|
- 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
|
## Seasons
|
||||||
|
|
||||||
A world is a season with a winner (`world.season`, rules in `Season`, rows in `Seasons`).
|
A world is a season with a winner (`world.season`, rules in `Season`, rows in `Seasons`).
|
||||||
|
|
|
||||||
|
|
@ -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] Loyalty (lazy regeneration), noble drop per hit, conquest transfers the village
|
||||||
- [x] Coins at the academy, rising noble cost per world config
|
- [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
|
- [x] Village switcher in the header
|
||||||
- [ ] Overviews across villages (production, troops, buildings per village)
|
- [ ] Overviews across villages (production, troops, buildings per village)
|
||||||
- [x] Restart on the same world after losing every village
|
- [x] Restart on the same world after losing every village
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,151 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Actions\Ranking;
|
||||||
|
use App\Actions\SendTroops;
|
||||||
|
use App\Actions\Tribes;
|
||||||
|
use App\Models\Movement;
|
||||||
|
use App\Models\Tribe;
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Models\Village;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
|
beforeEach(fn () => $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');
|
||||||
|
});
|
||||||
|
|
@ -31,6 +31,7 @@ function gameConfig(array $overrides = []): WorldConfig
|
||||||
'combat' => require "$dir/combat.php",
|
'combat' => require "$dir/combat.php",
|
||||||
'movement' => require "$dir/movement.php",
|
'movement' => require "$dir/movement.php",
|
||||||
'raids' => require "$dir/raids.php",
|
'raids' => require "$dir/raids.php",
|
||||||
|
'tribes' => require "$dir/tribes.php",
|
||||||
'quests' => require "$dir/quests.php",
|
'quests' => require "$dir/quests.php",
|
||||||
], $overrides);
|
], $overrides);
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,54 @@
|
||||||
|
<?php
|
||||||
|
|
||||||
|
use App\Game\Tribes\Diplomacy;
|
||||||
|
use Carbon\CarbonImmutable;
|
||||||
|
|
||||||
|
$now = CarbonImmutable::parse('2026-11-01 12:00:00');
|
||||||
|
$row = fn (int $from, int $to, string $state, bool $confirmed = true, ?string $endsAt = null) => [
|
||||||
|
'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();
|
||||||
|
});
|
||||||
Loading…
Reference in New Issue