feat: quest book with construction, army and village lines, and a reward for every building level reached the first time

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-29 10:05:55 +01:00
parent b7b209692d
commit 2336d746ff
25 changed files with 932 additions and 4 deletions

View File

@ -0,0 +1,29 @@
<?php
namespace App\Actions;
use App\Engine\Quests;
use App\Engine\Simulation;
use App\Game\GameRuleViolation;
use App\Game\Quests\QuestBook;
use App\Models\User;
use App\Models\Village;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
/** Claim a completed quest: its reward goes into this village, up to what the storage holds. */
final class ClaimQuest extends VillageAction
{
public function __invoke(User $user, int $villageId, string $quest): Village
{
return $this->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']);
});
}
}

View File

@ -0,0 +1,27 @@
<?php
namespace App\Actions;
use App\Engine\Simulation;
use App\Models\LevelReward;
use App\Models\User;
use App\Models\Village;
use Carbon\CarbonImmutable;
/** Collect level rewards (the given ones, or all) into this village, up to what the storage holds. */
final class CollectRewards extends VillageAction
{
/** @param list<int>|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]);
}
});
}
}

View File

@ -3,6 +3,7 @@
namespace App\Actions; namespace App\Actions;
use App\Engine\Military; use App\Engine\Military;
use App\Engine\Quests;
use App\Engine\Simulation; use App\Engine\Simulation;
use App\Models\User; use App\Models\User;
use App\Models\Village; 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) { return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($count) {
Military::of($village, $sim)->levy($count, $now); Military::of($village, $sim)->levy($count, $now);
Quests::bump($village->player_id, 'levy.called');
}); });
} }
} }

View File

@ -3,6 +3,7 @@
namespace App\Actions; namespace App\Actions;
use App\Engine\Military; use App\Engine\Military;
use App\Engine\Quests;
use App\Engine\Simulation; use App\Engine\Simulation;
use App\Models\User; use App\Models\User;
use App\Models\Village; 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) { 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); Military::of($village, $sim)->recruit($this->building($village, $buildingId), $unit, $count, $now);
Quests::bump($village->player_id, "recruited.$unit", $count);
}); });
} }
} }

View File

@ -2,6 +2,7 @@
namespace App\Actions; namespace App\Actions;
use App\Engine\Quests;
use App\Engine\Simulation; use App\Engine\Simulation;
use App\Game\GameRuleViolation; use App\Game\GameRuleViolation;
use App\Models\User; 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) { return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($name) {
$village->name = $name; $village->name = $name;
Quests::bump($village->player_id, 'village.renamed');
}); });
} }
} }

View File

@ -2,6 +2,7 @@
namespace App\Actions; namespace App\Actions;
use App\Engine\Quests;
use App\Game\GameRuleViolation; use App\Game\GameRuleViolation;
use App\Models\Player; use App\Models\Player;
use App\Models\Report; 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() $report = Report::whereKey($reportId)->whereIn('player_id', Player::where('user_id', $user->id)->select('id'))->first()
?? throw new GameRuleViolation('not_found', 'Report not found.'); ?? throw new GameRuleViolation('not_found', 'Report not found.');
if (! $report->read_at) {
Quests::bump($report->player_id, 'reports.read');
}
$report->read_at ??= now(); $report->read_at ??= now();
$report->save(); $report->save();

View File

@ -2,9 +2,11 @@
namespace App\Actions; namespace App\Actions;
use App\Engine\Quests;
use App\Engine\Rally; use App\Engine\Rally;
use App\Engine\Simulation; use App\Engine\Simulation;
use App\Game\GameRuleViolation; use App\Game\GameRuleViolation;
use App\Models\Movement;
use App\Models\User; use App\Models\User;
use App\Models\Village; use App\Models\Village;
use Carbon\CarbonImmutable; 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() $target = Village::where('world_id', $village->world_id)->where('x', $x)->where('y', $y)->first()
?? throw new GameRuleViolation('not_found', 'No village there.'); ?? throw new GameRuleViolation('not_found', 'No village there.');
$rally = Rally::of($village, $sim); $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<string> */
private function scoutUnits(Village $village): array
{
return array_keys(array_filter($village->world->gameConfig()->get('units', []), fn (array $u) => $u['scout'] ?? false));
}
} }

View File

@ -2,6 +2,7 @@
namespace App\Actions; namespace App\Actions;
use App\Engine\Quests;
use App\Engine\Simulation; use App\Engine\Simulation;
use App\Models\User; use App\Models\User;
use App\Models\Village; 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) { return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($buildingId, $priority) {
$building = $this->building($village, $buildingId); $building = $this->building($village, $buildingId);
$building->update(['priority' => max(0, min(9, $priority))]); $building->update(['priority' => max(0, min(9, $priority))]);
Quests::bump($village->player_id, 'priority.set');
}); });
} }
} }

View File

@ -2,6 +2,7 @@
namespace App\Actions; namespace App\Actions;
use App\Engine\Quests;
use App\Game\GameRuleViolation; use App\Game\GameRuleViolation;
use App\Game\Map\Continent; use App\Game\Map\Continent;
use App\Game\Map\MapBounds; use App\Game\Map\MapBounds;
@ -27,6 +28,8 @@ final class ShowMap
$w = max(1, min($max, $w)); $w = max(1, min($max, $w));
$h = max(1, min($max, $h)); $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) { if ($x === null || $y === null) {
$home = Village::whereIn('player_id', Player::where('user_id', $user->id)->where('world_id', $world->id)->select('id')) $home = Village::whereIn('player_id', Player::where('user_id', $user->id)->where('world_id', $world->id)->select('id'))
->orderBy('id')->first(); ->orderBy('id')->first();

View File

@ -0,0 +1,66 @@
<?php
namespace App\Actions;
use App\Engine\Quests;
use App\Game\Buildings\BuildingRules;
use App\Game\GameRuleViolation;
use App\Game\Quests\QuestBook;
use App\Models\LevelReward;
use App\Models\User;
use App\Models\Village;
/**
* The `quest.index` payload: every line with its current quest and goal progress, the
* level rewards waiting to be collected, and what the next level of each building in
* this village would pay back.
*/
final class ShowQuests
{
public function __invoke(User $user, int $villageId): array
{
$village = Village::with(['world', 'player', 'buildings'])->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),
];
}
}

View File

@ -158,7 +158,7 @@ final class Engine
return; return;
} }
$sim->settle($event->fire_at); $sim->settle($event->fire_at);
$sim->finish($order); $sim->finish($order, $event->fire_at);
$sim->startWaitingOrders($event->fire_at); $sim->startWaitingOrders($event->fire_at);
} }

102
app/Engine/Quests.php Normal file
View File

@ -0,0 +1,102 @@
<?php
namespace App\Engine;
use App\Game\Quests\Facts;
use App\Game\Quests\QuestBook;
use App\Models\Building;
use App\Models\LevelReward;
use App\Models\Village;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\DB;
/** The rows behind the quest book: counters, claimed quests, level rewards. */
final class Quests
{
/** Count an action a quest may ask for. Keys are listed in config/game/quests.php. */
public static function bump(?int $playerId, string $key, int $by = 1): void
{
if ($playerId === null || $by < 1) {
return;
}
DB::table('player_counters')->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<string> */
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<string, int> $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),
]);
}
}

View File

@ -344,11 +344,17 @@ final class Simulation
: $this->rules->buildSeconds($order->type, $order->target_level, $this->hqLevel(), $this->hqStaffing()); : $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->applyFinished($order);
$this->village->points = $this->points(); $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. */ /** Points shown on the map: the sum over buildings of their level's points. */

View File

@ -24,9 +24,56 @@ final class ConfigLint
...self::requirementsReachable($config, $rules), ...self::requirementsReachable($config, $rules),
...self::unitsTrainable($config, $rules), ...self::unitsTrainable($config, $rules),
...self::timersRun($config), ...self::timersRun($config),
...self::questsReachable($config, $rules),
]; ];
} }
/** Counter keys the actions bump (App\Engine\Quests::bump), besides recruited.<unit>. */
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. */ /** 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 private static function timersRun(WorldConfig $config): array
{ {

18
app/Game/Quests/Facts.php Normal file
View File

@ -0,0 +1,18 @@
<?php
namespace App\Game\Quests;
/** What the quest goals are measured against, gathered across a player's villages. */
final class Facts
{
/**
* @param array<string, int> $levels highest level per building type
* @param array<string, int> $instances most buildings of a type in one village
* @param array<string, int> $counters action counters (Counters::bump keys)
*/
public function __construct(
public readonly array $levels = [],
public readonly array $instances = [],
public readonly array $counters = [],
) {}
}

View File

@ -0,0 +1,127 @@
<?php
namespace App\Game\Quests;
use App\Game\WorldConfig;
/**
* The quest lines and how far a player is in each, from facts about the player:
* the highest level per building type, the most instances of a type in one village,
* and the action counters. A line's current quest is its first unclaimed one; it is
* complete while every goal is met. Nothing is stored but which quests were claimed.
*/
final class QuestBook
{
public function __construct(private readonly WorldConfig $config) {}
/** @return array<string, array<string, array{goals: list<array>, reward: array<string, int>}>> */
public function lines(): array
{
return $this->config->get('quests.lines', []);
}
/** @return array{goals: list<array>, reward: array<string, int>}|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<string> $claimed
* @return list<array{line: string, done: int, total: int, quest: array|null}>
*/
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<string, int> $cost
* @return array<string, int>
*/
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);
}
}

View File

@ -0,0 +1,30 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
/** Part of a building level's cost, paid back the first time a player reaches that level. */
class LevelReward extends Model
{
public $timestamps = false;
protected $guarded = [];
protected $dateFormat = 'Y-m-d H:i:s.v';
protected function casts(): array
{
return [
'reward' => 'array',
'reached_at' => 'immutable_datetime',
'claimed_at' => 'immutable_datetime',
];
}
public function village(): BelongsTo
{
return $this->belongsTo(Village::class);
}
}

View File

@ -29,6 +29,7 @@ class World extends Model
'units' => config('game.units'), 'units' => config('game.units'),
'combat' => config('game.combat'), 'combat' => config('game.combat'),
'movement' => config('game.movement'), 'movement' => config('game.movement'),
'quests' => config('game.quests'),
], $this->config ?? []); ], $this->config ?? []);
} }

View File

@ -3,6 +3,7 @@
namespace App\Presenters; namespace App\Presenters;
use App\Engine\Military; use App\Engine\Military;
use App\Engine\Quests;
use App\Engine\Simulation; use App\Engine\Simulation;
use App\Engine\Starvation; use App\Engine\Starvation;
use App\Game\Map\Continent; use App\Game\Map\Continent;
@ -69,6 +70,7 @@ final class VillagePresenter
'movements' => RallyPresenter::movements($village, $now), 'movements' => RallyPresenter::movements($village, $now),
'support' => RallyPresenter::support($village), 'support' => RallyPresenter::support($village),
'rally' => RallyPresenter::rally($village, $now), 'rally' => RallyPresenter::rally($village, $now),
'quests' => Quests::summary($village),
'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(),
'buildings' => $village->buildings->map(function (Building $b) use ($sim, $workforce, $rules) { 'buildings' => $village->buildings->map(function (Building $b) use ($sim, $workforce, $rules) {

View File

@ -0,0 +1,42 @@
<?php
namespace App\Websocket\Controllers;
use App\Actions\ClaimQuest;
use App\Actions\CollectRewards;
use App\Actions\ShowQuests;
use App\Models\Village;
use App\Presenters\VillagePresenter;
use App\Websocket\GameController;
/**
* quest.index {village_id}, quest.claim {village_id, quest}, quest.collect {village_id, ids?}.
* Claims answer with the book and the fresh village, since resources changed.
*/
class QuestController extends GameController
{
public function index()
{
return $this->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()),
];
}
}

130
config/game/quests.php Normal file
View File

@ -0,0 +1,130 @@
<?php
/*
* The quest book: parallel lines of quests a player works through in order. A line
* shows its first unclaimed quest; claiming it pays the reward into the village the
* player is looking at and opens the next one.
*
* Goals:
* ['building', type, level] a building of that type at that level in any village
* ['instances', type, count] that many buildings of one type in one village
* ['counter', key, count, hint] something done that often (Counters::bump keys);
* hint names the screen the client points at
*
* Titles and story texts live in the client's i18n (quests.<key>.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],
],
],
],
];

View File

@ -0,0 +1,52 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
// Quests a player has claimed. Progress is never stored: it follows from the
// player's buildings and counters on every read.
Schema::create('player_quests', function (Blueprint $table) {
$table->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');
}
};

132
tests/Feature/QuestTest.php Normal file
View File

@ -0,0 +1,132 @@
<?php
use App\Actions\ClaimQuest;
use App\Actions\CollectRewards;
use App\Actions\QueueBuild;
use App\Actions\QueueDemolish;
use App\Actions\QueueUpgrade;
use App\Actions\RenameVillage;
use App\Actions\SendTroops;
use App\Actions\ShowMap;
use App\Actions\ShowQuests;
use App\Engine\VillageFactory;
use App\Game\Buildings\BuildingRules;
use App\Models\LevelReward;
use App\Models\Village;
use Carbon\CarbonImmutable;
beforeEach(fn () => $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);
});

View File

@ -30,6 +30,7 @@ function gameConfig(array $overrides = []): WorldConfig
'units' => require "$dir/units.php", 'units' => require "$dir/units.php",
'combat' => require "$dir/combat.php", 'combat' => require "$dir/combat.php",
'movement' => require "$dir/movement.php", 'movement' => require "$dir/movement.php",
'quests' => require "$dir/quests.php",
], $overrides); ], $overrides);
} }

View File

@ -0,0 +1,75 @@
<?php
use App\Game\ConfigLint;
use App\Game\Quests\Facts;
use App\Game\Quests\QuestBook;
function book(): QuestBook
{
return new QuestBook(gameConfig());
}
function line(array $progress, string $line): array
{
return collect($progress)->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].',
);
});