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'); } }