diff --git a/app/Actions/ClaimQuest.php b/app/Actions/ClaimQuest.php new file mode 100644 index 0000000..5915296 --- /dev/null +++ b/app/Actions/ClaimQuest.php @@ -0,0 +1,29 @@ +mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($quest) { + $book = new QuestBook($sim->config()); + $claimed = Quests::claimed($village->player_id); + if (! $book->claimable($quest, $claimed, Quests::facts($village->player_id))) { + throw new GameRuleViolation('quest_open', 'This quest is not complete yet.'); + } + DB::table('player_quests')->insert(['player_id' => $village->player_id, 'quest' => $quest, 'claimed_at' => $now->format('Y-m-d H:i:s.v')]); + $sim->refund($book->quest($quest)['reward']); + }); + } +} diff --git a/app/Actions/CollectRewards.php b/app/Actions/CollectRewards.php new file mode 100644 index 0000000..d376799 --- /dev/null +++ b/app/Actions/CollectRewards.php @@ -0,0 +1,27 @@ +|null $ids */ + public function __invoke(User $user, int $villageId, ?array $ids = null): Village + { + return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($ids) { + $rewards = LevelReward::where('player_id', $village->player_id)->whereNull('claimed_at') + ->when($ids !== null, fn ($q) => $q->whereIn('id', $ids)) + ->lockForUpdate()->get(); + foreach ($rewards as $reward) { + $sim->refund($reward->reward); + $reward->update(['claimed_at' => $now]); + } + }); + } +} diff --git a/app/Actions/Levy.php b/app/Actions/Levy.php index 98047e2..5676d82 100644 --- a/app/Actions/Levy.php +++ b/app/Actions/Levy.php @@ -3,6 +3,7 @@ namespace App\Actions; use App\Engine\Military; +use App\Engine\Quests; use App\Engine\Simulation; use App\Models\User; use App\Models\Village; @@ -15,6 +16,7 @@ final class Levy extends VillageAction { return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($count) { Military::of($village, $sim)->levy($count, $now); + Quests::bump($village->player_id, 'levy.called'); }); } } diff --git a/app/Actions/Recruit.php b/app/Actions/Recruit.php index 19d8218..27f26d7 100644 --- a/app/Actions/Recruit.php +++ b/app/Actions/Recruit.php @@ -3,6 +3,7 @@ namespace App\Actions; use App\Engine\Military; +use App\Engine\Quests; use App\Engine\Simulation; use App\Models\User; use App\Models\Village; @@ -15,6 +16,7 @@ final class Recruit extends VillageAction { return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($buildingId, $unit, $count) { Military::of($village, $sim)->recruit($this->building($village, $buildingId), $unit, $count, $now); + Quests::bump($village->player_id, "recruited.$unit", $count); }); } } diff --git a/app/Actions/RenameVillage.php b/app/Actions/RenameVillage.php index ce22104..201a329 100644 --- a/app/Actions/RenameVillage.php +++ b/app/Actions/RenameVillage.php @@ -2,6 +2,7 @@ namespace App\Actions; +use App\Engine\Quests; use App\Engine\Simulation; use App\Game\GameRuleViolation; use App\Models\User; @@ -22,6 +23,7 @@ final class RenameVillage extends VillageAction return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($name) { $village->name = $name; + Quests::bump($village->player_id, 'village.renamed'); }); } } diff --git a/app/Actions/Reports.php b/app/Actions/Reports.php index 633f934..705a242 100644 --- a/app/Actions/Reports.php +++ b/app/Actions/Reports.php @@ -2,6 +2,7 @@ namespace App\Actions; +use App\Engine\Quests; use App\Game\GameRuleViolation; use App\Models\Player; use App\Models\Report; @@ -41,6 +42,9 @@ final class Reports { $report = Report::whereKey($reportId)->whereIn('player_id', Player::where('user_id', $user->id)->select('id'))->first() ?? throw new GameRuleViolation('not_found', 'Report not found.'); + if (! $report->read_at) { + Quests::bump($report->player_id, 'reports.read'); + } $report->read_at ??= now(); $report->save(); diff --git a/app/Actions/SendTroops.php b/app/Actions/SendTroops.php index 5304390..987d929 100644 --- a/app/Actions/SendTroops.php +++ b/app/Actions/SendTroops.php @@ -2,9 +2,11 @@ namespace App\Actions; +use App\Engine\Quests; use App\Engine\Rally; use App\Engine\Simulation; use App\Game\GameRuleViolation; +use App\Models\Movement; use App\Models\User; use App\Models\Village; use Carbon\CarbonImmutable; @@ -19,7 +21,31 @@ final class SendTroops extends VillageAction $target = Village::where('world_id', $village->world_id)->where('x', $x)->where('y', $y)->first() ?? throw new GameRuleViolation('not_found', 'No village there.'); $rally = Rally::of($village, $sim); - $rally->send($type, $target, $units, $mode ?: $rally->travel()->defaultMode(), $catapultTarget ?: null, $now); + $movement = $rally->send($type, $target, $units, $mode ?: $rally->travel()->defaultMode(), $catapultTarget ?: null, $now); + $this->count($village, $target, $movement); }); } + + /** Counters for the quest book: attacks (on barbarians), support, scouting. */ + private function count(Village $village, Village $target, Movement $movement): void + { + if ($movement->type === Movement::SUPPORT) { + Quests::bump($village->player_id, 'support.sent'); + + return; + } + Quests::bump($village->player_id, 'attacks.sent'); + if ($target->player_id === null) { + Quests::bump($village->player_id, 'attacks.barbarian'); + } + if (array_intersect(array_keys($movement->units), $this->scoutUnits($village))) { + Quests::bump($village->player_id, 'scouts.sent'); + } + } + + /** @return list */ + private function scoutUnits(Village $village): array + { + return array_keys(array_filter($village->world->gameConfig()->get('units', []), fn (array $u) => $u['scout'] ?? false)); + } } diff --git a/app/Actions/SetPriority.php b/app/Actions/SetPriority.php index fe76015..5541c40 100644 --- a/app/Actions/SetPriority.php +++ b/app/Actions/SetPriority.php @@ -2,6 +2,7 @@ namespace App\Actions; +use App\Engine\Quests; use App\Engine\Simulation; use App\Models\User; use App\Models\Village; @@ -15,6 +16,7 @@ final class SetPriority extends VillageAction return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($buildingId, $priority) { $building = $this->building($village, $buildingId); $building->update(['priority' => max(0, min(9, $priority))]); + Quests::bump($village->player_id, 'priority.set'); }); } } diff --git a/app/Actions/ShowMap.php b/app/Actions/ShowMap.php index a4b329a..84e2a25 100644 --- a/app/Actions/ShowMap.php +++ b/app/Actions/ShowMap.php @@ -2,6 +2,7 @@ namespace App\Actions; +use App\Engine\Quests; use App\Game\GameRuleViolation; use App\Game\Map\Continent; use App\Game\Map\MapBounds; @@ -27,6 +28,8 @@ final class ShowMap $w = max(1, min($max, $w)); $h = max(1, min($max, $h)); + Quests::mark(Player::where('user_id', $user->id)->where('world_id', $world->id)->value('id'), 'map.viewed'); + if ($x === null || $y === null) { $home = Village::whereIn('player_id', Player::where('user_id', $user->id)->where('world_id', $world->id)->select('id')) ->orderBy('id')->first(); diff --git a/app/Actions/ShowQuests.php b/app/Actions/ShowQuests.php new file mode 100644 index 0000000..1570a80 --- /dev/null +++ b/app/Actions/ShowQuests.php @@ -0,0 +1,66 @@ +find($villageId); + if (! $village || $village->player?->user_id !== $user->id) { + throw new GameRuleViolation('not_found', 'Village not found.'); + } + $config = $village->world->gameConfig(); + $book = new QuestBook($config); + $rules = new BuildingRules($config); + $playerId = $village->player_id; + $claimed = Quests::claimed($playerId); + $facts = Quests::facts($playerId); + + $lines = array_map(fn (array $line) => [ + ...$line, + 'quests' => array_map(fn (string $key) => [ + 'key' => $key, + 'claimed' => in_array($key, $claimed, true), + ], array_keys($book->lines()[$line['line']])), + ], $book->progress($claimed, $facts)); + + $rewards = LevelReward::with('village:id,name')->where('player_id', $playerId)->whereNull('claimed_at') + ->orderBy('reached_at')->orderBy('id')->get(); + + $upcoming = []; + foreach ($village->buildings->pluck('type')->unique()->sort()->values() as $type) { + $level = ($facts->levels[$type] ?? 0) + 1; + if ($level > $rules->maxLevel($type)) { + continue; + } + $upcoming[] = ['type' => $type, 'level' => $level, 'reward' => $book->levelReward($rules->cost($type, $level, 0))]; + } + + return [ + 'lines' => $lines, + 'rewards' => $rewards->map(fn (LevelReward $r) => [ + 'id' => $r->id, + 'type' => $r->type, + 'level' => $r->level, + 'reward' => $r->reward, + 'village' => ['id' => $r->village_id, 'name' => $r->village?->name], + ])->values()->all(), + 'upcoming' => $upcoming, + 'share' => (float) $config->get('quests.level_reward_share', 0), + ]; + } +} diff --git a/app/Engine/Engine.php b/app/Engine/Engine.php index f26e05c..bddede6 100644 --- a/app/Engine/Engine.php +++ b/app/Engine/Engine.php @@ -158,7 +158,7 @@ final class Engine return; } $sim->settle($event->fire_at); - $sim->finish($order); + $sim->finish($order, $event->fire_at); $sim->startWaitingOrders($event->fire_at); } diff --git a/app/Engine/Quests.php b/app/Engine/Quests.php new file mode 100644 index 0000000..5929aac --- /dev/null +++ b/app/Engine/Quests.php @@ -0,0 +1,102 @@ +upsert( + [['player_id' => $playerId, 'key' => $key, 'value' => $by]], + ['player_id', 'key'], + ['value' => DB::raw("value + $by")], + ); + } + + /** Note that something happened at least once, without a write on every repeat (map views). */ + public static function mark(?int $playerId, string $key): void + { + if ($playerId !== null) { + DB::table('player_counters')->insertOrIgnore(['player_id' => $playerId, 'key' => $key, 'value' => 1]); + } + } + + /** @return list */ + public static function claimed(int $playerId): array + { + return DB::table('player_quests')->where('player_id', $playerId)->pluck('quest')->all(); + } + + public static function facts(int $playerId): Facts + { + $buildings = Building::query() + ->join('villages', 'villages.id', '=', 'buildings.village_id') + ->where('villages.player_id', $playerId) + ->get(['buildings.village_id', 'buildings.type', 'buildings.level']); + + $levels = []; + $instances = []; + foreach ($buildings->groupBy('type') as $type => $rows) { + $levels[$type] = (int) $rows->max('level'); + $instances[$type] = (int) $rows->countBy('village_id')->max(); + } + + return new Facts( + $levels, + $instances, + DB::table('player_counters')->where('player_id', $playerId)->pluck('value', 'key')->map(fn ($n) => (int) $n)->all(), + ); + } + + /** The badge in the village payload: quests to claim and level rewards to collect. */ + public static function summary(Village $village): array + { + if ($village->player_id === null) { + return ['claimable' => 0, 'rewards' => 0]; + } + $book = new QuestBook($village->world->gameConfig()); + + return [ + 'claimable' => $book->claimableCount(self::claimed($village->player_id), self::facts($village->player_id)), + 'rewards' => LevelReward::where('player_id', $village->player_id)->whereNull('claimed_at')->count(), + ]; + } + + /** + * A finished order reached $level of $type: the first time for this player, part of + * what it cost waits to be collected in this village. + * + * @param array $cost + */ + public static function reached(Village $village, string $type, int $level, array $cost, CarbonImmutable $at): void + { + if ($village->player_id === null) { + return; + } + $reward = (new QuestBook($village->world->gameConfig()))->levelReward($cost); + if (array_sum($reward) < 1) { + return; + } + LevelReward::insertOrIgnore([ + 'player_id' => $village->player_id, + 'village_id' => $village->id, + 'type' => $type, + 'level' => $level, + 'reward' => json_encode($reward), + 'reached_at' => Engine::stamp($at), + ]); + } +} diff --git a/app/Engine/Simulation.php b/app/Engine/Simulation.php index 73b1ed9..b5245c7 100644 --- a/app/Engine/Simulation.php +++ b/app/Engine/Simulation.php @@ -344,11 +344,17 @@ final class Simulation : $this->rules->buildSeconds($order->type, $order->target_level, $this->hqLevel(), $this->hqStaffing()); } - /** Apply a finished order, drop it from the queue and recount the village's points. */ - public function finish(BuildOrder $order): void + /** + * Apply a finished order, drop it from the queue and recount the village's points. A + * level reached for the first time leaves a level reward for the player. + */ + public function finish(BuildOrder $order, CarbonImmutable $at): void { $this->applyFinished($order); $this->village->points = $this->points(); + if ($order->action !== BuildOrder::DEMOLISH) { + Quests::reached($this->village, $order->type, $order->target_level, $order->cost, $at); + } } /** Points shown on the map: the sum over buildings of their level's points. */ diff --git a/app/Game/ConfigLint.php b/app/Game/ConfigLint.php index 31e452d..a2a639f 100644 --- a/app/Game/ConfigLint.php +++ b/app/Game/ConfigLint.php @@ -24,9 +24,56 @@ final class ConfigLint ...self::requirementsReachable($config, $rules), ...self::unitsTrainable($config, $rules), ...self::timersRun($config), + ...self::questsReachable($config, $rules), ]; } + /** Counter keys the actions bump (App\Engine\Quests::bump), besides recruited.. */ + public const QUEST_COUNTERS = [ + 'attacks.sent', 'attacks.barbarian', 'support.sent', 'scouts.sent', 'village.renamed', + 'priority.set', 'levy.called', 'map.viewed', 'reports.read', + ]; + + /** + * Every quest must be completable, or its line stops there for good: known buildings + * at levels that exist, instances that fit the largest village, counters some action + * bumps, and each key once. + */ + private static function questsReachable(WorldConfig $config, BuildingRules $rules): array + { + $units = (new UnitRules($config))->units(); + $start = $rules->spaceUsed($config->get('world.village.start_buildings', [])); + $hqMax = $config->hasBuilding('headquarters') ? $rules->maxLevel('headquarters') : 1; + $spaceMax = $rules->spaceMax((int) $config->get('world.village.space'), $hqMax); + $seen = []; + $problems = []; + foreach ($config->get('quests.lines', []) as $line => $quests) { + foreach ($quests as $key => $quest) { + if (isset($seen[$key])) { + $problems[] = "Quest [$key] appears twice."; + } + $seen[$key] = true; + foreach ($quest['goals'] as [$kind, $subject, $need]) { + $problem = match (true) { + $kind === 'counter' => in_array($subject, self::QUEST_COUNTERS, true) + || (str_starts_with($subject, 'recruited.') && in_array(substr($subject, 10), $units, true)) + ? null : "counts [$subject], which no action bumps", + ! in_array($kind, ['building', 'instances'], true) => "has an unknown goal [$kind]", + ! $config->hasBuilding($subject) => "needs unknown building [$subject]", + $kind === 'building' && $need > $rules->maxLevel($subject) => "needs [$subject] level $need, above its maximum", + $kind === 'instances' && (($rules->maxPerVillage($subject) ?? $need) < $need || $start + $need * $rules->space($subject) > $spaceMax) => "needs $need [$subject] in one village, which never fit", + default => null, + }; + if ($problem) { + $problems[] = "Quest [$line.$key] $problem."; + } + } + } + } + + return $problems; + } + /** A levy has to end and desertion waves have to come apart in time, or the village stays stuck. */ private static function timersRun(WorldConfig $config): array { diff --git a/app/Game/Quests/Facts.php b/app/Game/Quests/Facts.php new file mode 100644 index 0000000..ed280f6 --- /dev/null +++ b/app/Game/Quests/Facts.php @@ -0,0 +1,18 @@ + $levels highest level per building type + * @param array $instances most buildings of a type in one village + * @param array $counters action counters (Counters::bump keys) + */ + public function __construct( + public readonly array $levels = [], + public readonly array $instances = [], + public readonly array $counters = [], + ) {} +} diff --git a/app/Game/Quests/QuestBook.php b/app/Game/Quests/QuestBook.php new file mode 100644 index 0000000..1727333 --- /dev/null +++ b/app/Game/Quests/QuestBook.php @@ -0,0 +1,127 @@ +, reward: array}>> */ + public function lines(): array + { + return $this->config->get('quests.lines', []); + } + + /** @return array{goals: list, reward: array}|null */ + public function quest(string $key): ?array + { + foreach ($this->lines() as $quests) { + if (isset($quests[$key])) { + return $quests[$key]; + } + } + + return null; + } + + /** + * Every line with its quests, the current one with goal progress. + * + * @param list $claimed + * @return list + */ + public function progress(array $claimed, Facts $facts): array + { + $out = []; + foreach ($this->lines() as $line => $quests) { + $current = null; + foreach ($quests as $key => $quest) { + if (! in_array($key, $claimed, true)) { + $current = $key; + break; + } + } + $done = count(array_intersect(array_keys($quests), $claimed)); + $out[] = [ + 'line' => $line, + 'done' => $done, + 'total' => count($quests), + 'quest' => $current === null ? null : $this->present($current, $quests[$current], $facts), + ]; + } + + return $out; + } + + /** Whether the quest is a line's current one and all its goals are met. */ + public function claimable(string $key, array $claimed, Facts $facts): bool + { + foreach ($this->progress($claimed, $facts) as $line) { + if ($line['quest'] && $line['quest']['key'] === $key) { + return $line['quest']['complete']; + } + } + + return false; + } + + /** How many lines have a completed quest waiting to be claimed. */ + public function claimableCount(array $claimed, Facts $facts): int + { + return count(array_filter($this->progress($claimed, $facts), fn (array $line) => $line['quest']['complete'] ?? false)); + } + + private function present(string $key, array $quest, Facts $facts): array + { + $goals = array_map(fn (array $goal) => $this->goal($goal, $facts), $quest['goals']); + + return [ + 'key' => $key, + 'goals' => $goals, + 'reward' => $quest['reward'], + 'complete' => ! in_array(false, array_column($goals, 'met'), true), + ]; + } + + /** @return array{kind: string, subject: string, have: int, need: int, met: bool, hint: string} */ + private function goal(array $goal, Facts $facts): array + { + [$kind, $subject, $need] = $goal; + $have = match ($kind) { + 'building' => $facts->levels[$subject] ?? 0, + 'instances' => $facts->instances[$subject] ?? 0, + 'counter' => $facts->counters[$subject] ?? 0, + }; + + return [ + 'kind' => $kind, + 'subject' => $subject, + 'have' => min($have, $need), + 'need' => $need, + 'met' => $have >= $need, + // Buildings point at their own screen; counters name theirs. + 'hint' => $kind === 'counter' ? $goal[3] : $subject, + ]; + } + + /** + * What a level reached for the first time pays back: the share of what its order cost. + * + * @param array $cost + * @return array + */ + public function levelReward(array $cost): array + { + $share = (float) $this->config->get('quests.level_reward_share', 0); + + return array_map(fn (int $n) => (int) round($n * $share), $cost); + } +} diff --git a/app/Models/LevelReward.php b/app/Models/LevelReward.php new file mode 100644 index 0000000..db6a845 --- /dev/null +++ b/app/Models/LevelReward.php @@ -0,0 +1,30 @@ + 'array', + 'reached_at' => 'immutable_datetime', + 'claimed_at' => 'immutable_datetime', + ]; + } + + public function village(): BelongsTo + { + return $this->belongsTo(Village::class); + } +} diff --git a/app/Models/World.php b/app/Models/World.php index 6cc44da..9912888 100644 --- a/app/Models/World.php +++ b/app/Models/World.php @@ -29,6 +29,7 @@ class World extends Model 'units' => config('game.units'), 'combat' => config('game.combat'), 'movement' => config('game.movement'), + 'quests' => config('game.quests'), ], $this->config ?? []); } diff --git a/app/Presenters/VillagePresenter.php b/app/Presenters/VillagePresenter.php index 6ca7f0f..6fcd7c5 100644 --- a/app/Presenters/VillagePresenter.php +++ b/app/Presenters/VillagePresenter.php @@ -3,6 +3,7 @@ namespace App\Presenters; use App\Engine\Military; +use App\Engine\Quests; use App\Engine\Simulation; use App\Engine\Starvation; use App\Game\Map\Continent; @@ -69,6 +70,7 @@ final class VillagePresenter 'movements' => RallyPresenter::movements($village, $now), 'support' => RallyPresenter::support($village), 'rally' => RallyPresenter::rally($village, $now), + 'quests' => Quests::summary($village), 'unread_reports' => Report::where('player_id', $village->player_id)->whereNull('read_at')->count(), 'builders' => $sim->builders(), 'buildings' => $village->buildings->map(function (Building $b) use ($sim, $workforce, $rules) { diff --git a/app/Websocket/Controllers/QuestController.php b/app/Websocket/Controllers/QuestController.php new file mode 100644 index 0000000..f72ed3a --- /dev/null +++ b/app/Websocket/Controllers/QuestController.php @@ -0,0 +1,42 @@ +play(fn () => app(ShowQuests::class)(auth()->user(), (int) request('village_id'))); + } + + public function claim() + { + return $this->play(fn () => $this->answer(app(ClaimQuest::class)(auth()->user(), (int) request('village_id'), (string) request('quest')))); + } + + public function collect() + { + $ids = request()->has('ids') ? array_map('intval', (array) request('ids')) : null; + + return $this->play(fn () => $this->answer(app(CollectRewards::class)(auth()->user(), (int) request('village_id'), $ids))); + } + + private function answer(Village $village): array + { + return [ + 'book' => app(ShowQuests::class)(auth()->user(), $village->id), + 'village' => VillagePresenter::present($village, now()->toImmutable()), + ]; + } +} diff --git a/config/game/quests.php b/config/game/quests.php new file mode 100644 index 0000000..509743f --- /dev/null +++ b/config/game/quests.php @@ -0,0 +1,130 @@ +.title|text). + */ + +return [ + // Every building level a player reaches for the first time (per building type, in + // any village) pays back this share of what that order cost. + 'level_reward_share' => 0.2, + + 'lines' => [ + 'construction' => [ + 'hq_2' => [ + 'goals' => [['building', 'headquarters', 2]], + 'reward' => ['wood' => 120, 'clay' => 120, 'iron' => 100], + ], + 'storage_farm_2' => [ + 'goals' => [['building', 'storage', 2], ['building', 'farm', 2]], + 'reward' => ['wood' => 150, 'clay' => 150, 'iron' => 150], + ], + 'resource_camps' => [ + 'goals' => [['building', 'timber_camp', 1], ['building', 'clay_pit', 1], ['building', 'iron_mine', 1]], + 'reward' => ['wood' => 200, 'clay' => 200, 'iron' => 150], + ], + 'camps_3' => [ + 'goals' => [['building', 'timber_camp', 3], ['building', 'clay_pit', 3], ['building', 'iron_mine', 3]], + 'reward' => ['wood' => 400, 'clay' => 400, 'iron' => 300], + ], + 'hq_3' => [ + 'goals' => [['building', 'headquarters', 3]], + 'reward' => ['wood' => 400, 'clay' => 350, 'iron' => 300], + ], + 'storage_farm_5' => [ + 'goals' => [['building', 'storage', 5], ['building', 'farm', 5]], + 'reward' => ['wood' => 800, 'clay' => 800, 'iron' => 700], + ], + 'hq_5' => [ + 'goals' => [['building', 'headquarters', 5]], + 'reward' => ['wood' => 1200, 'clay' => 1200, 'iron' => 1000], + ], + 'camps_8' => [ + 'goals' => [['building', 'timber_camp', 8], ['building', 'clay_pit', 8], ['building', 'iron_mine', 6]], + 'reward' => ['wood' => 1500, 'clay' => 1500, 'iron' => 1500], + ], + ], + + 'army' => [ + 'barracks' => [ + 'goals' => [['building', 'barracks', 1]], + 'reward' => ['wood' => 250, 'clay' => 220, 'iron' => 120], + ], + 'first_spears' => [ + 'goals' => [['counter', 'recruited.spear', 5, 'barracks']], + 'reward' => ['wood' => 250, 'clay' => 150, 'iron' => 50], + ], + 'rally_point' => [ + 'goals' => [['building', 'rally_point', 1]], + 'reward' => ['wood' => 100, 'clay' => 100, 'iron' => 100], + ], + 'first_raid' => [ + 'goals' => [['counter', 'attacks.barbarian', 1, 'rally_point']], + 'reward' => ['wood' => 300, 'clay' => 300, 'iron' => 300], + ], + 'wall_3' => [ + 'goals' => [['building', 'wall', 3]], + 'reward' => ['wood' => 300, 'clay' => 400, 'iron' => 150], + ], + 'barracks_3' => [ + 'goals' => [['building', 'barracks', 3]], + 'reward' => ['wood' => 600, 'clay' => 550, 'iron' => 400], + ], + 'stable' => [ + 'goals' => [['building', 'stable', 1]], + 'reward' => ['wood' => 700, 'clay' => 600, 'iron' => 600], + ], + 'first_scouts' => [ + 'goals' => [['counter', 'scouts.sent', 1, 'rally_point']], + 'reward' => ['wood' => 500, 'clay' => 500, 'iron' => 500], + ], + ], + + // What makes this game different from Die Stämme: names, staffing, a second + // instance of a building, the levy. + 'village' => [ + 'rename' => [ + 'goals' => [['counter', 'village.renamed', 1, 'village']], + 'reward' => ['wood' => 60, 'clay' => 60, 'iron' => 60], + ], + 'priority' => [ + 'goals' => [['counter', 'priority.set', 1, 'headquarters']], + 'reward' => ['wood' => 100, 'clay' => 100, 'iron' => 100], + ], + 'look_around' => [ + 'goals' => [['counter', 'map.viewed', 1, 'map']], + 'reward' => ['wood' => 100, 'clay' => 100, 'iron' => 80], + ], + 'hiding_place' => [ + 'goals' => [['building', 'hiding_place', 1]], + 'reward' => ['wood' => 120, 'clay' => 120, 'iron' => 120], + ], + 'second_camp' => [ + 'goals' => [['instances', 'timber_camp', 2]], + 'reward' => ['wood' => 250, 'clay' => 300, 'iron' => 200], + ], + 'read_report' => [ + 'goals' => [['counter', 'reports.read', 1, 'reports']], + 'reward' => ['wood' => 150, 'clay' => 150, 'iron' => 150], + ], + 'levy' => [ + 'goals' => [['counter', 'levy.called', 1, 'village']], + 'reward' => ['wood' => 200, 'clay' => 200, 'iron' => 200], + ], + 'second_farm' => [ + 'goals' => [['instances', 'farm', 2]], + 'reward' => ['wood' => 400, 'clay' => 400, 'iron' => 300], + ], + ], + ], +]; diff --git a/database/migrations/2026_10_30_120000_create_quest_tables.php b/database/migrations/2026_10_30_120000_create_quest_tables.php new file mode 100644 index 0000000..4ff1b19 --- /dev/null +++ b/database/migrations/2026_10_30_120000_create_quest_tables.php @@ -0,0 +1,52 @@ +id(); + $table->foreignId('player_id')->constrained()->cascadeOnDelete(); + $table->string('quest', 48); + $table->dateTime('claimed_at', 3); + $table->unique(['player_id', 'quest']); + }); + + // How often a player has done something a quest asks for (Counters::bump). + Schema::create('player_counters', function (Blueprint $table) { + $table->id(); + $table->foreignId('player_id')->constrained()->cascadeOnDelete(); + $table->string('key', 48); + $table->unsignedInteger('value')->default(0); + $table->unique(['player_id', 'key']); + }); + + // A building level reached for the first time pays back part of its cost, once + // per player, type and level, into the village it was reached in. + Schema::create('level_rewards', function (Blueprint $table) { + $table->id(); + $table->foreignId('player_id')->constrained()->cascadeOnDelete(); + $table->foreignId('village_id')->constrained()->cascadeOnDelete(); + $table->string('type', 32); + $table->unsignedSmallInteger('level'); + $table->json('reward'); + $table->dateTime('reached_at', 3); + $table->dateTime('claimed_at', 3)->nullable(); + $table->unique(['player_id', 'type', 'level']); + $table->index(['player_id', 'claimed_at']); + }); + } + + public function down(): void + { + Schema::dropIfExists('level_rewards'); + Schema::dropIfExists('player_counters'); + Schema::dropIfExists('player_quests'); + } +}; diff --git a/tests/Feature/QuestTest.php b/tests/Feature/QuestTest.php new file mode 100644 index 0000000..406e645 --- /dev/null +++ b/tests/Feature/QuestTest.php @@ -0,0 +1,132 @@ + $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00'))); + +function questBook(Village $village): array +{ + return app(ShowQuests::class)(owner($village), $village->id); +} + +function questLine(Village $village, string $line): array +{ + return collect(questBook($village)['lines'])->firstWhere('line', $line); +} + +/** Queue an upgrade of the village's first building of $type and let it finish. */ +function upgraded(Village $village, string $type): Village +{ + $building = $village->buildings()->where('type', $type)->first(); + app(QueueUpgrade::class)(owner($village), $village->id, $building->id); + test()->travel(1)->days(); + test()->artisan('game:events --once')->assertSuccessful(); + + return $village->fresh(); +} + +it('leaves a level reward the first time a player reaches a level', function () { + $village = upgraded(startVillage(), 'headquarters'); + $cost = (new BuildingRules($village->world->gameConfig()))->cost('headquarters', 2, 0); + + expect(questBook($village)['rewards'])->toHaveCount(1) + ->and(questBook($village)['rewards'][0])->toMatchArray([ + 'type' => 'headquarters', 'level' => 2, + 'reward' => array_map(fn (int $n) => (int) round($n * 0.2), $cost), + 'village' => ['id' => $village->id, 'name' => $village->name], + ]) + ->and(shown($village)['quests'])->toBe(['claimable' => 1, 'rewards' => 1]); +}); + +it('pays a level back only once per player, type and level', function () { + $village = startVillage(); + $village->update(['wood' => 500, 'clay' => 500, 'iron' => 500]); + app(QueueBuild::class)(owner($village), $village->id, 'timber_camp'); + app(QueueBuild::class)(owner($village), $village->id, 'timber_camp'); + $this->travel(1)->days(); + $this->artisan('game:events --once')->assertSuccessful(); + + expect($village->buildings()->where('type', 'timber_camp')->count())->toBe(2) + ->and(LevelReward::where('type', 'timber_camp')->count())->toBe(1); +}); + +it('pays nothing for demolishing', function () { + $village = upgraded(startVillage(), 'storage'); + LevelReward::query()->delete(); + app(QueueDemolish::class)(owner($village), $village->id, $village->buildings()->where('type', 'storage')->value('id')); + $this->travel(1)->days(); + $this->artisan('game:events --once')->assertSuccessful(); + + expect(LevelReward::count())->toBe(0); +}); + +it('collects level rewards into the village, up to the storage', function () { + $village = upgraded(startVillage(), 'headquarters'); + $before = shown($village)['resources']; + $reward = questBook($village)['rewards'][0]['reward']; + + $state = shown(app(CollectRewards::class)(owner($village), $village->id)); + expect($state['resources']['wood'])->toBe(min($state['storage_cap'], $before['wood'] + $reward['wood'])) + ->and($state['quests']['rewards'])->toBe(0) + ->and(questBook($village)['rewards'])->toBe([]); + + // Collected rewards are gone; collecting again changes nothing. + $again = shown(app(CollectRewards::class)(owner($village), $village->id)); + expect($again['resources']['wood'])->toBe($state['resources']['wood']); +}); + +it('claims a completed quest once and opens the next one', function () { + $village = startVillage(); + expect(rule(fn () => app(ClaimQuest::class)(owner($village), $village->id, 'hq_2')))->toBe('quest_open'); + + $village = upgraded($village, 'headquarters'); + $village->update(['wood' => 0, 'clay' => 0, 'iron' => 0, 'resources_at' => now()]); + $state = shown(app(ClaimQuest::class)(owner($village), $village->id, 'hq_2')); + + expect($state['resources'])->toMatchArray(['wood' => 120.0, 'clay' => 120.0, 'iron' => 100.0]) + ->and($state['quests']['claimable'])->toBe(0) + ->and(questLine($village, 'construction'))->toMatchArray(['done' => 1]) + ->and(questLine($village, 'construction')['quest']['key'])->toBe('storage_farm_2') + ->and(rule(fn () => app(ClaimQuest::class)(owner($village), $village->id, 'hq_2')))->toBe('quest_open'); +}); + +it('counts renames, map views and attacks on barbarians', function () { + $village = startVillage(); + app(RenameVillage::class)(owner($village), $village->id, 'Oakridge'); + app(ShowMap::class)(owner($village), $village->world_id, null, null, 15, 15); + app(ShowMap::class)(owner($village), $village->world_id, null, null, 15, 15); + + expect(questLine($village, 'village')['quest'])->toMatchArray(['key' => 'rename', 'complete' => true]); + app(ClaimQuest::class)(owner($village), $village->id, 'rename'); + $this->assertDatabaseHas('player_counters', ['key' => 'map.viewed', 'value' => 1]); + + $village->buildings()->create(['type' => 'rally_point', 'level' => 1]); + $village->troops()->create(['home_village_id' => $village->id, 'unit' => 'spear', 'count' => 5]); + $barbarian = app(VillageFactory::class)->create($village->world, null, 'Barbarian village', $village->x + 2, $village->y, ['headquarters' => 1, 'storage' => 1, 'farm' => 1]); + app(SendTroops::class)(owner($village), $village->id, 'attack', $barbarian->x, $barbarian->y, ['spear' => 5], null, null); + + $this->assertDatabaseHas('player_counters', ['key' => 'attacks.barbarian', 'value' => 1]); + $this->assertDatabaseHas('player_counters', ['key' => 'attacks.sent', 'value' => 1]); + $this->assertDatabaseMissing('player_counters', ['key' => 'scouts.sent']); +}); + +it('previews what the next level of each building pays back', function () { + $village = startVillage(); + $upcoming = collect(questBook($village)['upcoming'])->keyBy('type'); + + expect($upcoming->keys()->all())->toBe(['farm', 'headquarters', 'storage']) + ->and($upcoming['headquarters']['level'])->toBe(2); +}); diff --git a/tests/Pest.php b/tests/Pest.php index bc77dca..71667d3 100644 --- a/tests/Pest.php +++ b/tests/Pest.php @@ -30,6 +30,7 @@ function gameConfig(array $overrides = []): WorldConfig 'units' => require "$dir/units.php", 'combat' => require "$dir/combat.php", 'movement' => require "$dir/movement.php", + 'quests' => require "$dir/quests.php", ], $overrides); } diff --git a/tests/Unit/Game/QuestBookTest.php b/tests/Unit/Game/QuestBookTest.php new file mode 100644 index 0000000..22251b9 --- /dev/null +++ b/tests/Unit/Game/QuestBookTest.php @@ -0,0 +1,75 @@ +firstWhere('line', $line); +} + +it('starts every line at its first quest', function () { + $progress = book()->progress([], new Facts(['headquarters' => 1])); + + expect(array_column($progress, 'line'))->toBe(['construction', 'army', 'village']) + ->and(line($progress, 'construction')['quest'])->toMatchArray(['key' => 'hq_2', 'complete' => false]) + ->and(line($progress, 'construction')['quest']['goals'][0]) + ->toBe(['kind' => 'building', 'subject' => 'headquarters', 'have' => 1, 'need' => 2, 'met' => false, 'hint' => 'headquarters']); +}); + +it('completes a quest when every goal is met, and moves on once it is claimed', function () { + $facts = new Facts(['headquarters' => 2, 'storage' => 2, 'farm' => 1]); + + expect(book()->claimable('hq_2', [], $facts))->toBeTrue() + ->and(book()->claimable('storage_farm_2', [], $facts))->toBeFalse(); + + $line = line(book()->progress(['hq_2'], $facts), 'construction'); + expect($line)->toMatchArray(['done' => 1, 'total' => 8]) + ->and($line['quest']['key'])->toBe('storage_farm_2') + ->and(array_column($line['quest']['goals'], 'met'))->toBe([true, false]); +}); + +it('measures counters and instances, capping progress at the goal', function () { + $facts = new Facts([], ['timber_camp' => 1], ['recruited.spear' => 9, 'village.renamed' => 1]); + $army = line(book()->progress(['barracks'], $facts), 'army'); + $village = line(book()->progress(['rename', 'priority', 'look_around', 'hiding_place'], $facts), 'village'); + + expect($army['quest']['goals'][0])->toMatchArray(['have' => 5, 'need' => 5, 'met' => true, 'hint' => 'barracks']) + ->and($village['quest']['goals'][0])->toMatchArray(['kind' => 'instances', 'have' => 1, 'need' => 2, 'met' => false]); +}); + +it('only claims the current quest of a line', function () { + $facts = new Facts(['headquarters' => 3]); + + expect(book()->claimable('hq_3', [], $facts))->toBeFalse() + ->and(book()->claimableCount([], $facts))->toBe(1); +}); + +it('ends a line once every quest is claimed', function () { + $all = array_keys(gameConfig()->get('quests.lines.army')); + + expect(line(book()->progress($all, new Facts), 'army'))->toMatchArray(['done' => 8, 'quest' => null]); +}); + +it('pays back a share of a level cost', function () { + expect(book()->levelReward(['wood' => 113, 'clay' => 100, 'iron' => 88]))->toBe(['wood' => 23, 'clay' => 20, 'iron' => 18]); +}); + +it('reports quests that can never be completed', function () { + $config = gameConfig(['quests' => ['lines' => ['army' => ['wall_3' => ['goals' => [ + ['building', 'wall', 99], ['counter', 'cats.petted', 1, 'village'], ['instances', 'headquarters', 2], ['building', 'castle', 1], + ]]]]]]); + + expect(ConfigLint::check($config))->toContain( + 'Quest [army.wall_3] needs [wall] level 99, above its maximum.', + 'Quest [army.wall_3] counts [cats.petted], which no action bumps.', + 'Quest [army.wall_3] needs 2 [headquarters] in one village, which never fit.', + 'Quest [army.wall_3] needs unknown building [castle].', + ); +});