diff --git a/app/Actions/Account.php b/app/Actions/Account.php new file mode 100644 index 0000000..53d9725 --- /dev/null +++ b/app/Actions/Account.php @@ -0,0 +1,97 @@ +where('user_id', $user->id)->get(); + $villages = Village::whereIn('player_id', $players->pluck('id'))->groupBy('player_id') + ->selectRaw('player_id, COUNT(*) as n, SUM(points) as points')->get()->keyBy('player_id'); + + return [ + 'name' => $user->name, + 'email' => $user->email, + 'since' => $user->created_at->utc()->format('Y-m-d\TH:i:s.v\Z'), + 'worlds' => $players->map(fn (Player $p) => [ + 'world' => ['id' => $p->world->id, 'name' => $p->world->name], + 'villages' => (int) ($villages[$p->id]->n ?? 0), + 'points' => (int) ($villages[$p->id]->points ?? 0), + 'tribe' => $p->membership?->tribe?->summary(), + ])->values()->all(), + ]; + } + + public function password(User $user, string $current, string $new): array + { + if (! Hash::check($current, $user->password)) { + throw new GameRuleViolation('wrong_password', 'That is not your current password.'); + } + if (mb_strlen($new) < 8 || mb_strlen($new) > 255) { + throw new GameRuleViolation('password_short', 'Passwords are at least 8 characters.'); + } + $user->update(['password' => $new]); + + return $this->show($user); + } + + /** + * Delete the account: on every world its villages turn barbarian, a tribe it leads + * goes to the next member (or ends with it), and then the players and the account go. + */ + public function delete(User $user, string $password): array + { + if (! Hash::check($password, $user->password)) { + throw new GameRuleViolation('wrong_password', 'That is not your password.'); + } + $now = now()->toImmutable(); + foreach (Player::with('membership')->where('user_id', $user->id)->get() as $player) { + Abandon::player($player, $now); + DB::transaction(function () use ($player, $now) { + $this->leaveTribe($player, $now); + $player->delete(); + }); + } + $user->tokens()->delete(); + $user->delete(); + + return ['deleted' => true]; + } + + /** A leader hands the tribe to the strongest council member, else the strongest member; alone, the tribe ends. */ + private function leaveTribe(Player $player, $now): void + { + $membership = $player->membership; + if (! $membership) { + return; + } + $tribe = Tribe::whereKey($membership->tribe_id)->lockForUpdate()->first(); + $membership->delete(); + $rest = TribeMember::with('player')->where('tribe_id', $tribe->id)->get(); + if ($rest->isEmpty()) { + $tribe->delete(); + + return; + } + TribeEvent::note($tribe->id, 'left', ['player' => $player->name], $now); + if ($membership->role === TribeMember::LEADER) { + $points = Village::whereIn('player_id', $rest->pluck('player_id'))->groupBy('player_id')->selectRaw('player_id, SUM(points) as p')->pluck('p', 'player_id'); + $heir = $rest->sortByDesc(fn (TribeMember $m) => [(int) ($m->role === TribeMember::COUNCIL), (int) ($points[$m->player_id] ?? 0)])->first(); + $heir->update(['role' => TribeMember::LEADER]); + TribeEvent::note($tribe->id, 'role', ['player' => $heir->player->name, 'role' => TribeMember::LEADER], $now); + } + } +} diff --git a/app/Actions/JoinWorld.php b/app/Actions/JoinWorld.php index 4217efa..b7ab93b 100644 --- a/app/Actions/JoinWorld.php +++ b/app/Actions/JoinWorld.php @@ -37,7 +37,10 @@ final class JoinWorld $taken = VillageFactory::takenSpots($world); [$x, $y] = VillageFactory::spawnSpot($world, $taken, $direction); - $levels = array_fill_keys($world->gameConfig()->get('world.village.start_buildings'), 1); + // A first start and a restart after losing every village both get beginner protection. + $config = $world->gameConfig(); + $player->update(['protected_since' => now(), 'last_active_at' => now()]); + $levels = array_fill_keys($config->get('world.village.start_buildings'), 1); $village = $this->villages->create($world, $player, "{$user->name}'s village", $x, $y, $levels); $this->barbarians->around($world, $village, $taken); Raiders::of($village)->ensurePlanned(now()->toImmutable()); diff --git a/app/Actions/ListWorlds.php b/app/Actions/ListWorlds.php index 31fdca2..871582d 100644 --- a/app/Actions/ListWorlds.php +++ b/app/Actions/ListWorlds.php @@ -2,26 +2,61 @@ namespace App\Actions; +use App\Game\GameRuleViolation; +use App\Game\Map\Season; use App\Models\Player; use App\Models\User; +use App\Models\Village; use App\Models\World; +use App\Presenters\WorldPresenter; +use Carbon\CarbonImmutable; +use Illuminate\Support\Facades\DB; +/** The worlds overview: every world with its state and size, and one world's settings. */ final class ListWorlds { - /** @return list */ public function __invoke(User $user): array { - $villageIds = Player::where('user_id', $user->id)->with('villages:id,player_id')->get() - ->mapWithKeys(fn (Player $p) => [$p->world_id => $p->villages->min('id')]); + $players = Player::where('user_id', $user->id)->with('villages:id,player_id')->get()->keyBy('world_id'); + $sizes = Village::whereNotNull('player_id')->groupBy('world_id') + ->selectRaw('world_id, COUNT(*) as villages, COUNT(DISTINCT player_id) as players')->get()->keyBy('world_id'); + $tribes = DB::table('tribes')->groupBy('world_id')->selectRaw('world_id, COUNT(*) as n')->pluck('n', 'world_id'); - return World::with('winner')->orderBy('id')->get()->map(fn (World $world) => [ - 'id' => $world->id, - 'name' => $world->name, - 'slug' => $world->slug, - 'speed' => $world->gameConfig()->speed(), - 'village_id' => $villageIds[$world->id] ?? null, - 'ended_at' => $world->ended_at?->utc()->format('Y-m-d\TH:i:s.v\Z'), - 'winner' => $world->winner ? ['id' => $world->winner->id, 'name' => $world->winner->name] : null, - ])->all(); + return World::with(['winner', 'holder'])->orderBy('id')->get()->map(function (World $world) use ($players, $sizes, $tribes) { + $season = new Season($world->gameConfig()); + $mine = $players[$world->id] ?? null; + + return [ + 'id' => $world->id, + 'name' => $world->name, + 'slug' => $world->slug, + 'speed' => $world->gameConfig()->speed(), + 'village_id' => $mine?->villages->min('id'), + // Joined once and lost every village: the world offers a fresh start. + 'fallen' => $mine !== null && $mine->villages->isEmpty(), + 'started_at' => self::iso($world->started_at), + 'players' => (int) ($sizes[$world->id]->players ?? 0), + 'villages' => (int) ($sizes[$world->id]->villages ?? 0), + 'tribes' => (int) ($tribes[$world->id] ?? 0), + 'crowns_at' => self::iso($world->crowns_placed_at ?? $season->crownsAt($world->started_at)), + 'holder' => $world->holder ? ['id' => $world->holder->id, 'name' => $world->holder->name] : null, + 'ends_at' => $world->ends_at ? self::iso($world->ends_at) : null, + 'ended_at' => $world->ended_at ? self::iso($world->ended_at) : null, + 'winner' => $world->winner ? ['id' => $world->winner->id, 'name' => $world->winner->name] : null, + ]; + })->all(); + } + + /** One world's settings, in plain units. */ + public function settings(int $worldId): array + { + $world = World::find($worldId) ?? throw new GameRuleViolation('not_found', 'World not found.'); + + return ['id' => $world->id, 'name' => $world->name, 'settings' => WorldPresenter::settings($world->gameConfig())]; + } + + private static function iso(CarbonImmutable $at): string + { + return $at->utc()->format('Y-m-d\TH:i:s.v\Z'); } } diff --git a/app/Actions/VillageAction.php b/app/Actions/VillageAction.php index bfdd4fa..c795783 100644 --- a/app/Actions/VillageAction.php +++ b/app/Actions/VillageAction.php @@ -43,6 +43,11 @@ abstract class VillageAction if (! $this->readOnly()) { $village->world->ensureOpen(); } + // Seen now, for the rule that turns long-abandoned villages barbarian. + $player = $village->player; + if (! $player->last_active_at || $player->last_active_at->lessThan($now->subMinutes(5))) { + $player->update(['last_active_at' => $now]); + } $sim = Simulation::of($village); $sim->settle($now); Military::of($village, $sim)->settle($now); diff --git a/app/Console/Commands/ProcessGameEvents.php b/app/Console/Commands/ProcessGameEvents.php index 181fb7c..85b52f2 100644 --- a/app/Console/Commands/ProcessGameEvents.php +++ b/app/Console/Commands/ProcessGameEvents.php @@ -2,6 +2,7 @@ namespace App\Console\Commands; +use App\Engine\Abandon; use App\Engine\Engine; use App\Engine\Push; use App\Engine\Seasons; @@ -21,10 +22,16 @@ class ProcessGameEvents extends Command public function handle(Engine $engine): int { + $lastAbandonCheck = 0; do { $now = now()->toImmutable(); // Crowns that are due appear, and a holder who kept them long enough wins. Seasons::tick($now); + // Once a minute: abandoned accounts lose their villages to the barbarians. + if ($now->getTimestamp() - $lastAbandonCheck >= 60) { + $lastAbandonCheck = $now->getTimestamp(); + Abandon::inactive($now); + } while ($villageId = $engine->nextDueVillage($now)) { try { $engine->catchUp($villageId, $now); diff --git a/app/Engine/Abandon.php b/app/Engine/Abandon.php new file mode 100644 index 0000000..59aff9b --- /dev/null +++ b/app/Engine/Abandon.php @@ -0,0 +1,105 @@ +settle($at); + $touched = Nobility::of($village)->release($village); + + $rally = Rally::of($village, $sim); + foreach ($village->troops->pluck('home_village_id')->unique() as $home) { + if ($home !== $village->id) { + $rally->sendHome($home, $at); + } + } + UnitStack::where('village_id', $village->id)->where('home_village_id', $village->id)->delete(); + $village->setRelation('troops', collect()); + GameEvent::where('village_id', $village->id)->where('type', GameEvent::RAID_PLANNED)->whereNull('processed_at')->delete(); + + $village->player_id = null; + $village->setRelation('player', null); + if ($village->crown) { + Seasons::recount($village, $at); + } else { + GameEvent::create([ + 'world_id' => $village->world_id, + 'village_id' => $village->id, + 'type' => GameEvent::BARBARIAN_GROWS, + 'fire_at' => $at->addSeconds((new BarbarianGrowth($sim->config()))->interval()), + ]); + } + Barbarians::of($village, $sim)->fill(); + Push::queue(...$touched); + } + + /** + * Players not seen for world.inactive_days (real days) lose their villages; players + * never seen since activity is tracked are left alone. + * + * @return int villages turned barbarian + */ + public static function inactive(CarbonImmutable $now): int + { + $count = 0; + foreach (World::whereNull('ended_at')->get() as $world) { + $days = (float) $world->gameConfig()->get('world.inactive_days', 0); + if ($days <= 0) { + continue; + } + $gone = Player::where('world_id', $world->id)->whereNotNull('last_active_at') + ->where('last_active_at', '<', Engine::stamp($now->subSeconds((int) ($days * 86400)))) + ->whereHas('villages')->get(); + foreach ($gone as $player) { + $count += self::player($player, $now); + } + } + + return $count; + } + + /** Every village of a player turns barbarian, each under its own lock. */ + public static function player(Player $player, CarbonImmutable $at): int + { + $engine = app(Engine::class); + $count = 0; + foreach (Village::where('player_id', $player->id)->pluck('id') as $id) { + $engine->catchUpAround($id, $at); + try { + $count += DB::transaction(function () use ($id, $player, $at) { + $village = Village::whereKey($id)->lockForUpdate()->first(); + if (! $village || $village->player_id !== $player->id) { + return 0; + } + self::village($village, $at); + $village->save(); + + return 1; + }); + } finally { + Push::flush(); + } + } + + return $count; + } +} diff --git a/app/Engine/Nobility.php b/app/Engine/Nobility.php index 60fbd01..dbe824f 100644 --- a/app/Engine/Nobility.php +++ b/app/Engine/Nobility.php @@ -70,6 +70,29 @@ final class Nobility * @return list villages whose owners should hear about it */ public function handOver(Village $village, int $playerId, CarbonImmutable $at): array + { + $touched = $this->release($village); + + $village->player_id = $playerId; + $village->setRelation('player', Player::find($playerId)); + $village->loyalty = $this->rules->afterConquest(); + $village->loyalty_at = $at; + // Raiders come for the new owner's village too. + Raiders::of($village)->ensurePlanned($at); + if ($village->crown) { + Seasons::recount($village, $at); + } + + return $touched; + } + + /** + * What a village loses with its owner: its queues end without refunds, the owner's + * groups from or to it are lost, and so is its support standing elsewhere. + * + * @return list villages whose owners should hear about it + */ + public function release(Village $village): array { $touched = []; @@ -106,16 +129,6 @@ final class Nobility $stack->delete(); } - $village->player_id = $playerId; - $village->setRelation('player', Player::find($playerId)); - $village->loyalty = $this->rules->afterConquest(); - $village->loyalty_at = $at; - // Raiders come for the new owner's village too. - Raiders::of($village)->ensurePlanned($at); - if ($village->crown) { - Seasons::recount($village, $at); - } - return array_values(array_unique($touched)); } } diff --git a/app/Engine/Push.php b/app/Engine/Push.php index 40f215c..c796ce6 100644 --- a/app/Engine/Push.php +++ b/app/Engine/Push.php @@ -15,6 +15,15 @@ final class Push /** @var array */ private static array $queued = []; + /** @var list}> */ + private static array $lost = []; + + /** The old owner of a taken village hears of it, to leave its screens and read the report. */ + public static function lost(int $userId, array $payload): void + { + self::$lost[] = ['user' => $userId, 'payload' => $payload]; + } + public static function queue(int ...$villageIds): void { foreach ($villageIds as $id) { @@ -25,8 +34,22 @@ final class Push public static function flush(): void { $ids = array_keys(self::$queued); + $lost = self::$lost; self::$queued = []; + self::$lost = []; self::villages($ids); + if ($lost && ws_available()) { + foreach ($lost as $l) { + try { + $sockets = WebsocketService::getUserSocketIds($l['user']); + if ($sockets) { + ws_whisper('village:lost', $l['payload'], $sockets); + } + } catch (Throwable $e) { + report($e); + } + } + } } /** @param list $villageIds */ diff --git a/app/Engine/Rally.php b/app/Engine/Rally.php index 6db5420..319ab10 100644 --- a/app/Engine/Rally.php +++ b/app/Engine/Rally.php @@ -69,8 +69,10 @@ final class Rally public function protectedUntil(Player $player): CarbonImmutable { $seconds = $this->sim->config()->get('combat.beginner_protection', 0) / $this->sim->config()->speed(); + // From joining, and again from a restart after losing every village. + $since = $player->protected_since ?? $player->created_at->toImmutable(); - return $player->created_at->toImmutable()->addSeconds((int) ceil($seconds)); + return $since->addSeconds((int) ceil($seconds)); } public function cancelWindow(): int @@ -476,6 +478,12 @@ final class Rally private function conquer(Movement $movement, array $survivors, CarbonImmutable $at): void { $nobility = Nobility::of($this->village); + // The old owner hears of it right away (the report tells the rest). + $old = $this->village->player; + if ($old) { + $by = Player::find($movement->player_id); + Push::lost($old->user_id, ['world_id' => $this->village->world_id, 'village_id' => $this->village->id, 'name' => $this->village->name, 'x' => $this->village->x, 'y' => $this->village->y, 'by' => $by?->name]); + } $noble = collect($nobility->rules()->nobleUnits())->first(fn (string $u) => ($survivors[$u] ?? 0) > 0); $survivors[$noble]--; $oldHome = $this->village->troops->filter(fn (UnitStack $s) => $s->home_village_id === $this->village->id); diff --git a/app/Models/Player.php b/app/Models/Player.php index 29fb28c..ab1d34b 100644 --- a/app/Models/Player.php +++ b/app/Models/Player.php @@ -11,6 +11,11 @@ class Player extends Model { protected $guarded = []; + protected function casts(): array + { + return ['protected_since' => 'immutable_datetime', 'last_active_at' => 'immutable_datetime']; + } + public function user(): BelongsTo { return $this->belongsTo(User::class); diff --git a/app/Presenters/WorldPresenter.php b/app/Presenters/WorldPresenter.php new file mode 100644 index 0000000..82fcd5c --- /dev/null +++ b/app/Presenters/WorldPresenter.php @@ -0,0 +1,64 @@ +speed(); + $seconds = fn (float $atSpeedOne) => (int) round($atSpeedOne / $speed); + $night = $config->get('combat.night'); + $season = new Season($config); + [$raidMin, $raidMax] = $config->get('raids.every_hours', [0, 0]); + $drop = $config->get('combat.conquest.loyalty.drop', [20, 35]); + + return [ + 'pace' => [ + 'speed' => $speed, + 'unit_speed' => (float) $config->get('movement.unit_speed', 1), + 'protection' => $seconds($config->get('combat.beginner_protection', 0)), + // Real time, not world time. + 'inactive' => (int) ($config->get('world.inactive_days', 0) * 86400), + ], + 'village' => [ + 'space' => (int) $config->get('world.village.space'), + 'space_per_hq_level' => (int) $config->get('world.village.space_per_hq_level'), + 'builders' => (int) $config->get('world.builders.base', 2), + 'map_size' => (int) $config->get('world.map.size'), + ], + 'combat' => [ + 'morale' => (bool) ($config->get('combat.morale.enabled') ?? false), + 'luck' => (int) round($config->get('combat.luck', 0) * 100), + 'night' => ($night['enabled'] ?? false) ? ['start' => $night['start'], 'end' => $night['end'], 'factor' => $night['factor']] : null, + 'noble_distance' => (int) $config->get('combat.conquest.max_distance', 0), + 'loyalty_drop' => $drop, + 'loyalty_regen' => round($config->get('combat.conquest.loyalty.regen_per_hour', 1) * $speed, 2), + ], + 'raids' => (bool) $config->get('raids.enabled') ? [ + 'every' => [$seconds($raidMin * 3600), $seconds($raidMax * 3600)], + 'warning' => $seconds($config->get('raids.gather_hours', 0) * 3600), + 'range' => (int) $config->get('raids.range'), + ] : null, + 'tribes' => [ + 'max_members' => (new Diplomacy($config))->maxMembers(), + 'notice' => (new Diplomacy($config))->noticeSeconds(), + ], + 'season' => $season->count() > 0 ? [ + 'crowns' => $season->count(), + 'needed' => $season->needed(), + 'crowns_after' => $seconds($config->get('world.season.crowns_after_days', 30) * 86400), + 'hold' => $season->holdSeconds(), + ] : null, + ]; + } +} diff --git a/app/Websocket/Controllers/AccountController.php b/app/Websocket/Controllers/AccountController.php new file mode 100644 index 0000000..a94fe73 --- /dev/null +++ b/app/Websocket/Controllers/AccountController.php @@ -0,0 +1,25 @@ +play(fn () => app(Account::class)->show(auth()->user())); + } + + public function password() + { + return $this->play(fn () => app(Account::class)->password(auth()->user(), (string) request('current'), (string) request('password'))); + } + + public function delete() + { + return $this->play(fn () => app(Account::class)->delete(auth()->user(), (string) request('password'))); + } +} diff --git a/app/Websocket/Controllers/WorldController.php b/app/Websocket/Controllers/WorldController.php index 7a0e4d3..eb0cef8 100644 --- a/app/Websocket/Controllers/WorldController.php +++ b/app/Websocket/Controllers/WorldController.php @@ -6,7 +6,7 @@ use App\Actions\JoinWorld; use App\Actions\ListWorlds; use App\Websocket\GameController; -/** world.index, world.join {world_id, direction: random|nw|ne|sw|se} */ +/** world.index, world.settings {world_id}, world.join {world_id, direction: random|nw|ne|sw|se} */ class WorldController extends GameController { public function index() @@ -14,6 +14,12 @@ class WorldController extends GameController return $this->play(fn () => app(ListWorlds::class)(auth()->user())); } + /** world.settings {world_id}: the world's rules in plain units. */ + public function settings() + { + return $this->play(fn () => app(ListWorlds::class)->settings((int) request('world_id'))); + } + public function join() { return $this->play(fn () => [ diff --git a/config/game/world.php b/config/game/world.php index 4d56e16..69ac560 100644 --- a/config/game/world.php +++ b/config/game/world.php @@ -6,6 +6,11 @@ return [ // Multiplies production and divides every duration. 'speed' => 1.0, + // A player not seen for this many real days (not world days: it measures people) + // loses their villages to the barbarians, so abandoned accounts don't block the map. + // They can start again on the world. 0 turns it off. + 'inactive_days' => 14, + 'village' => [ // Building space: the sum of the buildings' `space` may not exceed // space + space_per_hq_level × (headquarters level − 1): 40 at level 1, 45 at 2, 85 at diff --git a/database/migrations/2026_11_01_120000_protection_since.php b/database/migrations/2026_11_01_120000_protection_since.php new file mode 100644 index 0000000..c220252 --- /dev/null +++ b/database/migrations/2026_11_01_120000_protection_since.php @@ -0,0 +1,24 @@ +renameColumn('protected_until', 'protected_since'); + }); + } + + public function down(): void + { + Schema::table('players', function (Blueprint $table) { + $table->renameColumn('protected_since', 'protected_until'); + }); + } +}; diff --git a/docs/architecture.md b/docs/architecture.md index 736dbbf..dbd05a1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -265,6 +265,14 @@ Players band together in tribes (`Tribes` action, `tribe.*` over WS, rules in `D - 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. +## Accounts and leaving + +- Registration (`POST /api/auth/register`) takes a player name (3 to 24 letters, digits, spaces, dots, dashes or underscores, unique across accounts, case aside), an email, a password of 8 characters or more, and the accepted terms (`terms_accepted_at`). A refusal answers `{code, message, field}`, so the form marks the field. +- `account.show|password|delete` over WS. Deleting needs the password: on every world the player's villages turn barbarian (`Abandon`), a tribe they lead goes to the strongest council member (else the strongest member) or ends with them, then the players and the account go, and with them their reports, quests and chat messages. +- **Losing a village** ("geadelt"): the conquest hands it over (`Nobility::handOver`, which shares `release()` with abandoning: queues end, the owner's groups from and to it are lost, its support elsewhere too), the old owner gets the defence report and a `village:lost {world_id, village_id, name, x, y, by}` whisper, so an open client leaves the village's screens. With no village left, `world.index` marks the world `fallen` and `world.join` starts the player over on the frontier, with fresh beginner protection (`players.protected_since`; protection lasts `combat.beginner_protection` from then, at world speed). +- **Abandoned accounts**: every village action records `players.last_active_at` (at most every 5 minutes). Once a minute the worker turns the villages of players not seen for `world.inactive_days` (14, real days: it measures people, not world time) barbarian (`Abandon::inactive`); the player can come back and start again. A barbarian made this way keeps its buildings and stock, sends other players' support home, loses the owner's troops and queues, grows, and holds a garrison like any other. +- `world.index` gives each world its players, villages, tribes, start, season state and the player's own state; `world.settings` the rules in plain units (durations in seconds at the world's speed) for the world overview. + ## Chat Players talk on their world (`Chat` action, `chat.*` over WS). The client names channels from its own side: `world` (everyone on the world), `tribe` (the player's tribe) and `dm:` (a conversation with that player, opened by name with `chat.open`). Stored (`chat_messages`), they are `world`, `tribe:` and `dm::`, so a tribe's talk stays with the tribe even as members come and go. diff --git a/docs/roadmap.md b/docs/roadmap.md index 90835e4..76e725d 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -60,7 +60,8 @@ What Die Stämme has at this stage that the game still lacks. - [x] Ranking: players by points, villages by points, opponents defeated (attack and defence) - [x] Chat between players: the world, the tribe, and direct conversations, live - [ ] Messages between players as letters (inbox, threads), if the chat isn't enough -- [ ] Notebook and account settings (vacation mode later) +- [x] Account settings: password, delete the account +- [ ] Notebook, vacation mode, password reset by email (needs mail on the server) ## M4.6: Game loop @@ -89,7 +90,7 @@ The world pushes back, so a world with few players is a game too: something thre - [ ] Overviews across villages (production, troops, buildings per village) - [x] Map colours by relation (own, tribe, ally, NAP, enemy, others, barbarians) and every known movement drawn on the map with its size - [x] Restart on the same world after losing every village -- [ ] Inactive villages turn barbarian +- [x] Inactive villages turn barbarian (14 real days); deleted accounts' villages too ## Later: the rest of Die Stämme diff --git a/tests/Feature/JoinWorldTest.php b/tests/Feature/JoinWorldTest.php index ea312cf..1c17797 100644 --- a/tests/Feature/JoinWorldTest.php +++ b/tests/Feature/JoinWorldTest.php @@ -70,10 +70,13 @@ it('lists worlds with their speed and the player village', function () { $village = startVillage(); $dev = World::where('slug', 'dev')->first(); - expect(app(ListWorlds::class)(owner($village)))->toBe([ - ['id' => $village->world_id, 'name' => 'World 1', 'slug' => 'w1', 'speed' => 1.0, 'village_id' => $village->id, 'ended_at' => null, 'winner' => null], - ['id' => $dev->id, 'name' => 'Dev world', 'slug' => 'dev', 'speed' => 100.0, 'village_id' => null, 'ended_at' => null, 'winner' => null], - ]); + $worlds = app(ListWorlds::class)(owner($village)); + $keys = array_flip(['id', 'name', 'slug', 'speed', 'village_id', 'fallen']); + expect($worlds[0])->toMatchArray(['players' => 1, 'villages' => 1, 'tribes' => 0, 'holder' => null, 'ended_at' => null, 'winner' => null]) + ->and(array_map(fn (array $w) => array_intersect_key($w, $keys), $worlds))->toBe([ + ['id' => $village->world_id, 'name' => 'World 1', 'slug' => 'w1', 'speed' => 1.0, 'village_id' => $village->id, 'fallen' => false], + ['id' => $dev->id, 'name' => 'Dev world', 'slug' => 'dev', 'speed' => 100.0, 'village_id' => null, 'fallen' => false], + ]); }); it('shows a start village to its owner only', function () { diff --git a/tests/Feature/LeavingTest.php b/tests/Feature/LeavingTest.php new file mode 100644 index 0000000..1396e9f --- /dev/null +++ b/tests/Feature/LeavingTest.php @@ -0,0 +1,97 @@ + $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00'))); + +it('changes the password only with the current one', function () { + $village = startVillage(User::factory()->create(['password' => 'old-secret'])); + $user = owner($village); + + expect(rule(fn () => app(Account::class)->password($user, 'wrong', 'new-secret')))->toBe('wrong_password') + ->and(rule(fn () => app(Account::class)->password($user, 'old-secret', 'short')))->toBe('password_short'); + app(Account::class)->password($user, 'old-secret', 'new-secret'); + $this->postJson('/api/auth/login', ['email' => $user->email, 'password' => 'new-secret'])->assertOk(); + expect(app(Account::class)->show($user->fresh())['worlds'][0])->toMatchArray(['villages' => 1, 'tribe' => null]); +}); + +it('deletes an account: villages turn barbarian, the tribe goes to the next member, support goes home', function () { + $leaving = startVillage(User::factory()->create(['password' => 'secret-pass'])); + $mate = startVillage(); + app(Tribes::class)->found(owner($leaving), $leaving->world_id, 'Dorfrat', 'DRF'); + app(Tribes::class)->invite(owner($leaving), $leaving->world_id, $mate->player->name); + app(Tribes::class)->join(owner($mate), $mate->world_id, Tribe::where('tag', 'DRF')->value('id')); + $leaving->troops()->create(['home_village_id' => $mate->id, 'unit' => 'spear', 'count' => 5]); + $user = owner($leaving); + + expect(rule(fn () => app(Account::class)->delete($user, 'wrong')))->toBe('wrong_password'); + app(Account::class)->delete($user, 'secret-pass'); + + $village = $leaving->fresh(); + expect($village->player_id)->toBeNull() + ->and($village->name)->toBe($leaving->name) + ->and(GameEvent::where('village_id', $village->id)->where('type', 'barbarian.grows')->exists())->toBeTrue() + ->and(User::find($user->id))->toBeNull() + ->and(Player::where('user_id', $user->id)->exists())->toBeFalse() + ->and(TribeMember::where('player_id', $mate->player_id)->value('role'))->toBe('leader') + ->and(Movement::where('target_id', $mate->id)->where('type', 'return')->exists())->toBeTrue(); +}); + +it('lets a player who lost every village start again with fresh beginner protection', function () { + $fallen = startVillage(); + $other = startVillage(); + $this->travel(5)->days(); + Nobility::of($fallen->fresh())->handOver($fallen->fresh(), $other->player_id, now()->toImmutable()); + Village::whereKey($fallen->id)->update(['player_id' => $other->player_id]); + + $world = collect(app(ListWorlds::class)(owner($fallen)))->firstWhere('id', $fallen->world_id); + expect($world)->toMatchArray(['village_id' => null, 'fallen' => true]); + + $again = app(JoinWorld::class)(owner($fallen), $fallen->world_id); + expect($again->id)->not->toBe($fallen->id) + ->and($again->player_id)->toBe($fallen->player_id); + $other->buildings()->create(['type' => 'rally_point', 'level' => 1]); + $other->troops()->create(['home_village_id' => $other->id, 'unit' => 'spear', 'count' => 5]); + expect(rule(fn () => app(SendTroops::class)(owner($other), $other->id, 'attack', $again->x, $again->y, ['spear' => 1], null, null)))->toBe('protected'); +}); + +it('turns the villages of players gone too long barbarian', function () { + config(['game.world.inactive_days' => 14]); + $gone = startVillage(); + $here = startVillage(); + $never = startVillage(); + Player::whereKey($never->player_id)->update(['last_active_at' => null]); + + $this->travel(15)->days(); + shown($here); + expect(Abandon::inactive(now()->toImmutable()))->toBe(1) + ->and($gone->fresh()->player_id)->toBeNull() + ->and($here->fresh()->player_id)->not->toBeNull() + ->and($never->fresh()->player_id)->not->toBeNull(); +}); + +it('tells a world settings in plain units', function () { + $village = startVillage(); + $settings = app(ListWorlds::class)->settings($village->world_id)['settings']; + + expect($settings['pace'])->toBe(['speed' => 1.0, 'unit_speed' => 1.0, 'protection' => 3 * 86400, 'inactive' => 0]) + ->and($settings['village'])->toMatchArray(['space' => 40, 'space_per_hq_level' => 5]) + ->and($settings['tribes'])->toBe(['max_members' => 25, 'notice' => 86400]) + ->and($settings['season'])->toMatchArray(['crowns' => 5, 'needed' => 3, 'hold' => 7 * 86400]) + ->and($settings['raids'])->toBeNull() + ->and(rule(fn () => app(ListWorlds::class)->settings(999)))->toBe('not_found'); +}); diff --git a/tests/Pest.php b/tests/Pest.php index 13fdc40..b00c75f 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -13,9 +13,9 @@ use Database\Seeders\WorldSeeder; use Illuminate\Foundation\Testing\RefreshDatabase; use Tests\TestCase; -// Feature tests start without barbarians and raids unless a test asks for them, so tests can place their own. +// Feature tests start without barbarians, raids and the inactivity rule unless a test asks for them. pest()->extend(TestCase::class)->use(RefreshDatabase::class) - ->beforeEach(fn () => config(['game.world.map.barbarians.per_join' => 0, 'game.raids.enabled' => false])) + ->beforeEach(fn () => config(['game.world.map.barbarians.per_join' => 0, 'game.raids.enabled' => false, 'game.world.inactive_days' => 0])) ->in('Feature'); /** The default game config without booting Laravel, so unit tests stay pure. */