From 120d6dcd2232a0c5cf3267737e31f5e66c9bbabe Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Wed, 28 Oct 2026 23:56:55 +0100 Subject: [PATCH] feat: rally point: send attacks and support, battles with loot and siege, return trips, recall, reports Co-Authored-By: Claude Opus 5.5 --- app/Actions/CancelMovement.php | 20 + app/Actions/PlanMarch.php | 46 ++ app/Actions/Reports.php | 76 +++ app/Actions/SendSupportHome.php | 25 + app/Actions/SendTroops.php | 25 + app/Actions/VillageAction.php | 12 +- app/Actions/WithdrawSupport.php | 46 ++ app/Console/Commands/ProcessGameEvents.php | 17 +- app/Engine/Engine.php | 31 ++ app/Engine/Push.php | 51 ++ app/Engine/Rally.php | 491 ++++++++++++++++++ app/Engine/Starvation.php | 24 +- app/Models/GameEvent.php | 9 + app/Models/Movement.php | 48 ++ app/Models/Report.php | 37 ++ app/Models/UnitStack.php | 5 + app/Models/Village.php | 2 +- app/Presenters/RallyPresenter.php | 96 ++++ app/Presenters/VillagePresenter.php | 5 + app/Websocket/Controllers/RallyController.php | 66 +++ .../Controllers/ReportController.php | 34 ++ ...30_090000_create_movements_and_reports.php | 54 ++ docs/architecture.md | 30 +- tests/Feature/RallyTest.php | 228 ++++++++ 24 files changed, 1450 insertions(+), 28 deletions(-) create mode 100644 app/Actions/CancelMovement.php create mode 100644 app/Actions/PlanMarch.php create mode 100644 app/Actions/Reports.php create mode 100644 app/Actions/SendSupportHome.php create mode 100644 app/Actions/SendTroops.php create mode 100644 app/Actions/WithdrawSupport.php create mode 100644 app/Engine/Push.php create mode 100644 app/Engine/Rally.php create mode 100644 app/Models/Movement.php create mode 100644 app/Models/Report.php create mode 100644 app/Presenters/RallyPresenter.php create mode 100644 app/Websocket/Controllers/RallyController.php create mode 100644 app/Websocket/Controllers/ReportController.php create mode 100644 database/migrations/2026_10_30_090000_create_movements_and_reports.php create mode 100644 tests/Feature/RallyTest.php diff --git a/app/Actions/CancelMovement.php b/app/Actions/CancelMovement.php new file mode 100644 index 0000000..1aa9949 --- /dev/null +++ b/app/Actions/CancelMovement.php @@ -0,0 +1,20 @@ +mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($movementId) { + Rally::of($village, $sim)->cancel($movementId, $now); + }); + } +} diff --git a/app/Actions/PlanMarch.php b/app/Actions/PlanMarch.php new file mode 100644 index 0000000..0c3518d --- /dev/null +++ b/app/Actions/PlanMarch.php @@ -0,0 +1,46 @@ + $units */ + public function __invoke(User $user, int $villageId, int $x, int $y, array $units, ?string $mode): array + { + $village = Village::with('player')->find($villageId); + if (! $village || $village->player?->user_id !== $user->id) { + throw new GameRuleViolation('not_found', 'Village not found.'); + } + $rally = Rally::of($village); + $travel = $rally->travel(); + $mode = $mode && $travel->hasMode($mode) ? $mode : $travel->defaultMode(); + $known = new UnitRules($village->world->gameConfig()); + $picked = array_filter( + array_map('intval', array_filter($units, fn ($n, $unit) => $known->exists((string) $unit), ARRAY_FILTER_USE_BOTH)), + fn (int $n) => $n > 0, + ); + $target = Village::with('player')->where('world_id', $village->world_id)->where('x', $x)->where('y', $y)->first(); + $distance = TravelTime::distance($village->x, $village->y, $x, $y); + $seconds = $picked && $distance > 0 ? $travel->seconds($picked, $distance, $mode) : null; + + return [ + 'x' => $x, + 'y' => $y, + 'target' => $target ? Rally::summary($target) : null, + 'mode' => $mode, + 'distance' => round($distance, 2), + 'seconds' => $seconds, + ]; + } +} diff --git a/app/Actions/Reports.php b/app/Actions/Reports.php new file mode 100644 index 0000000..e301d8a --- /dev/null +++ b/app/Actions/Reports.php @@ -0,0 +1,76 @@ +>, page: int, pages: int, unread: int} */ + public function list(User $user, int $worldId, int $page = 1): array + { + $query = $this->of($user, $worldId)->orderByDesc('happened_at')->orderByDesc('id'); + $pages = max(1, (int) ceil($query->count() / self::PER_PAGE)); + $page = max(1, min($pages, $page)); + + return [ + 'reports' => $query->forPage($page, self::PER_PAGE)->get()->map(fn (Report $r) => self::present($r))->all(), + 'page' => $page, + 'pages' => $pages, + 'unread' => $this->of($user, $worldId)->whereNull('read_at')->count(), + ]; + } + + /** One report in full; opening it marks it read. */ + public function show(User $user, int $reportId): array + { + $report = Report::whereKey($reportId)->whereIn('player_id', Player::where('user_id', $user->id)->select('id'))->first() + ?? throw new GameRuleViolation('not_found', 'Report not found.'); + $report->read_at ??= now(); + $report->save(); + + return self::present($report); + } + + /** @param list $ids */ + public function delete(User $user, int $worldId, array $ids): array + { + $this->of($user, $worldId)->whereIn('id', $ids)->delete(); + + return $this->list($user, $worldId); + } + + public function readAll(User $user, int $worldId): array + { + $this->of($user, $worldId)->whereNull('read_at')->update(['read_at' => now()]); + + return $this->list($user, $worldId); + } + + public static function present(Report $report): array + { + return [ + 'id' => $report->id, + 'type' => $report->type, + 'happened_at' => $report->happened_at->utc()->format('Y-m-d\TH:i:s.v\Z'), + 'read' => $report->read_at !== null, + 'payload' => $report->payload, + ]; + } + + /** @return Builder */ + private function of(User $user, int $worldId): Builder + { + $player = Player::where('user_id', $user->id)->where('world_id', $worldId)->first() + ?? throw new GameRuleViolation('not_found', 'Not on this world.'); + + return Report::where('player_id', $player->id); + } +} diff --git a/app/Actions/SendSupportHome.php b/app/Actions/SendSupportHome.php new file mode 100644 index 0000000..bef8ca8 --- /dev/null +++ b/app/Actions/SendSupportHome.php @@ -0,0 +1,25 @@ +mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($homeVillageId) { + if ($homeVillageId === $village->id || ! $village->troops->contains(fn (UnitStack $s) => $s->home_village_id === $homeVillageId)) { + throw new GameRuleViolation('not_found', 'No support from there.'); + } + Rally::of($village, $sim)->sendHome($homeVillageId, $now); + }); + } +} diff --git a/app/Actions/SendTroops.php b/app/Actions/SendTroops.php new file mode 100644 index 0000000..5304390 --- /dev/null +++ b/app/Actions/SendTroops.php @@ -0,0 +1,25 @@ + $units */ + public function __invoke(User $user, int $villageId, string $type, int $x, int $y, array $units, ?string $mode, ?string $catapultTarget): Village + { + return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($type, $x, $y, $units, $mode, $catapultTarget) { + $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); + }); + } +} diff --git a/app/Actions/VillageAction.php b/app/Actions/VillageAction.php index 2dd88a6..d447f2d 100644 --- a/app/Actions/VillageAction.php +++ b/app/Actions/VillageAction.php @@ -4,6 +4,7 @@ namespace App\Actions; use App\Engine\Engine; use App\Engine\Military; +use App\Engine\Push; use App\Engine\Simulation; use App\Engine\Starvation; use App\Game\GameRuleViolation; @@ -23,8 +24,17 @@ abstract class VillageAction protected function mutate(User $user, int $villageId, Closure $change): Village { $now = now()->toImmutable(); - $this->engine->catchUp($villageId, $now); + $this->engine->catchUpAround($villageId, $now); + try { + return $this->locked($user, $villageId, $change, $now); + } finally { + Push::flush(); + } + } + + private function locked(User $user, int $villageId, Closure $change, CarbonImmutable $now): Village + { return DB::transaction(function () use ($user, $villageId, $change, $now) { $village = Village::whereKey($villageId)->lockForUpdate()->first(); if (! $village || $village->player?->user_id !== $user->id) { diff --git a/app/Actions/WithdrawSupport.php b/app/Actions/WithdrawSupport.php new file mode 100644 index 0000000..1f39797 --- /dev/null +++ b/app/Actions/WithdrawSupport.php @@ -0,0 +1,46 @@ +find($villageId); + if (! $home || $home->player?->user_id !== $user->id) { + throw new GameRuleViolation('not_found', 'Village not found.'); + } + $now = now()->toImmutable(); + // Support that should have arrived by now has. + $this->engine->catchUpAround($villageId, $now); + $stationed = UnitStack::where('village_id', $hostId)->where('home_village_id', $villageId)->where('count', '>', 0)->exists(); + if ($hostId === $villageId || ! $stationed) { + throw new GameRuleViolation('not_found', 'No support there.'); + } + GameEvent::create([ + 'world_id' => $home->world_id, + 'village_id' => $hostId, + 'type' => GameEvent::SUPPORT_RECALLED, + 'subject_id' => $villageId, + 'fire_at' => $now, + ]); + $this->engine->catchUp($hostId, $now); + Push::villages([$hostId]); + + return app(ShowVillage::class)($user, $villageId); + } +} diff --git a/app/Console/Commands/ProcessGameEvents.php b/app/Console/Commands/ProcessGameEvents.php index db77a97..61eeab6 100644 --- a/app/Console/Commands/ProcessGameEvents.php +++ b/app/Console/Commands/ProcessGameEvents.php @@ -3,8 +3,7 @@ namespace App\Console\Commands; use App\Engine\Engine; -use App\Models\Village; -use BlaxSoftware\LaravelWebSockets\Services\WebsocketService; +use App\Engine\Push; use Illuminate\Console\Command; use Throwable; @@ -30,7 +29,7 @@ class ProcessGameEvents extends Command report($e); $engine->recordFailure($villageId, $now); } - $this->push($villageId); + Push::villages([$villageId]); } if ($this->option('once')) { @@ -43,16 +42,4 @@ class ProcessGameEvents extends Command usleep((int) (max(0.05, min(1.0, $wait)) * 1_000_000)); } while (true); } - - private function push(int $villageId): void - { - if (! ws_available()) { - return; - } - $userId = Village::with('player')->find($villageId)?->player?->user_id; - $sockets = $userId ? WebsocketService::getUserSocketIds($userId) : []; - if ($sockets) { - ws_whisper('village:updated', ['village_id' => $villageId], $sockets); - } - } } diff --git a/app/Engine/Engine.php b/app/Engine/Engine.php index 7a0d7d6..f26e05c 100644 --- a/app/Engine/Engine.php +++ b/app/Engine/Engine.php @@ -4,6 +4,7 @@ namespace App\Engine; use App\Game\Map\BarbarianGrowth; use App\Models\GameEvent; +use App\Models\Movement; use App\Models\Village; use Carbon\CarbonImmutable; use Illuminate\Support\Facades\DB; @@ -26,6 +27,22 @@ final class Engine return $count; } + /** + * Catch up a village and the targets of its own groups that are due: their arrival + * runs on the target's queue, so the owner never sees a group that should be back. + */ + public function catchUpAround(int $villageId, CarbonImmutable $now): void + { + $targets = Movement::where('origin_id', $villageId) + ->whereIn('type', [Movement::ATTACK, Movement::SUPPORT]) + ->where('arrives_at', '<=', self::stamp($now)) + ->distinct()->pluck('target_id'); + foreach ($targets as $target) { + $this->catchUp($target, $now); + } + $this->catchUp($villageId, $now); + } + /** The village with the oldest due event, for the worker. */ public function nextDueVillage(CarbonImmutable $now): ?int { @@ -57,6 +74,16 @@ final class Engine } private function processNext(int $villageId, CarbonImmutable $now): bool + { + // Other villages an event touched (an attacker's home, a supporter) hear about it after the commit. + try { + return $this->processLocked($villageId, $now); + } finally { + Push::flush(); + } + } + + private function processLocked(int $villageId, CarbonImmutable $now): bool { return DB::transaction(function () use ($villageId, $now) { $village = Village::whereKey($villageId)->lockForUpdate()->first(); @@ -91,6 +118,10 @@ final class Engine // The stock just hit 0; the sync() after every event starts the grace timer. GameEvent::FOOD_RUNS_OUT => null, GameEvent::DESERTION => Starvation::of($village)->wave($event->fire_at), + GameEvent::MOVEMENT_ARRIVES => Rally::of($village)->arrive((int) $event->subject_id, $event->fire_at), + // The target starts to see an incoming group; the worker's push is all it takes. + GameEvent::MOVEMENT_SPOTTED => null, + GameEvent::SUPPORT_RECALLED => Rally::of($village)->sendHome((int) $event->subject_id, $event->fire_at), }; } diff --git a/app/Engine/Push.php b/app/Engine/Push.php new file mode 100644 index 0000000..40f215c --- /dev/null +++ b/app/Engine/Push.php @@ -0,0 +1,51 @@ + */ + private static array $queued = []; + + public static function queue(int ...$villageIds): void + { + foreach ($villageIds as $id) { + self::$queued[$id] = true; + } + } + + public static function flush(): void + { + $ids = array_keys(self::$queued); + self::$queued = []; + self::villages($ids); + } + + /** @param list $villageIds */ + public static function villages(array $villageIds): void + { + if (! $villageIds || ! ws_available()) { + return; + } + foreach (Village::with('player')->whereIn('id', $villageIds)->get() as $village) { + $userId = $village->player?->user_id; + try { + $sockets = $userId ? WebsocketService::getUserSocketIds($userId) : []; + if ($sockets) { + ws_whisper('village:updated', ['village_id' => $village->id], $sockets); + } + } catch (Throwable $e) { + // A push is a hint to refetch; the game state is already saved. + report($e); + } + } + } +} diff --git a/app/Engine/Rally.php b/app/Engine/Rally.php new file mode 100644 index 0000000..fdd4e3f --- /dev/null +++ b/app/Engine/Rally.php @@ -0,0 +1,491 @@ +travel = new TravelTime($sim->config()); + } + + public static function of(Village $village, ?Simulation $sim = null): self + { + return new self($village, $sim ?? Simulation::of($village)); + } + + public function travel(): TravelTime + { + return $this->travel; + } + + public function hasRallyPoint(): bool + { + return $this->village->buildings->contains('type', 'rally_point'); + } + + /** Fields around the village within which incoming groups are seen. */ + public function detection(): float + { + $rules = $this->sim->rules(); + + return (float) $this->sim->config()->get('movement.detection', 0) + + $this->village->buildings->sum(fn (Building $b) => $rules->detection($b->type, $b->level)); + } + + /** Wood, clay and iron each that raiders can't take. */ + public function hidden(): float + { + $rules = $this->sim->rules(); + + return $this->village->buildings->sum(fn (Building $b) => $rules->hides($b->type, $b->level)); + } + + /** When beginner protection ends for this player. */ + public function protectedUntil(Player $player): CarbonImmutable + { + $seconds = $this->sim->config()->get('combat.beginner_protection', 0) / $this->sim->config()->speed(); + + return $player->created_at->toImmutable()->addSeconds((int) ceil($seconds)); + } + + public function cancelWindow(): int + { + return (int) $this->sim->config()->get('movement.cancel_window', 600); + } + + /** + * Distance, travel time and arrival for these units from here to $target. + * + * @param array $units + * @return array{distance: float, seconds: int, arrives_at: CarbonImmutable} + */ + public function plan(Village $target, array $units, string $mode, CarbonImmutable $now): array + { + $distance = TravelTime::distance($this->village->x, $this->village->y, $target->x, $target->y); + $seconds = $this->travel->seconds($units, $distance, $mode); + + return ['distance' => $distance, 'seconds' => $seconds, 'arrives_at' => $now->addSeconds($seconds)]; + } + + /** + * The units the player picked, checked against what stands at home. + * + * @param array $units + * @return array + */ + public function pick(array $units): array + { + $home = Military::of($this->village, $this->sim)->troopsAtHome(); + $picked = []; + foreach ($units as $unit => $count) { + $count = (int) $count; + if ($count <= 0) { + continue; + } + if ($count > ($home[$unit] ?? 0)) { + throw new GameRuleViolation('troops', 'Not that many troops at home.'); + } + $picked[(string) $unit] = $count; + } + if (! $picked) { + throw new GameRuleViolation('count', 'Send at least one unit.'); + } + + return $picked; + } + + /** + * Send an attack or support from here. The troops leave at once; the arrival is an + * event on the target, and the target sees it coming from visible_at on. + * + * @param array $units + */ + public function send(string $type, Village $target, array $units, string $mode, ?string $catapultTarget, CarbonImmutable $now): Movement + { + if (! in_array($type, [Movement::ATTACK, Movement::SUPPORT], true)) { + throw new GameRuleViolation('not_found', 'Attack or support.'); + } + if (! $this->hasRallyPoint()) { + throw new GameRuleViolation('no_rally_point', 'Build a rally point first.'); + } + if (! $this->travel->hasMode($mode)) { + throw new GameRuleViolation('not_found', "Unknown travel mode [$mode]."); + } + if ($target->id === $this->village->id || $target->world_id !== $this->village->world_id) { + throw new GameRuleViolation('same_village', 'Pick another village.'); + } + $units = $this->pick($units); + $this->checkTarget($type, $target, $now); + if ($catapultTarget !== null && ! $this->sim->config()->hasBuilding($catapultTarget)) { + throw new GameRuleViolation('not_found', "Unknown building [$catapultTarget]."); + } + + $this->take($units); + $plan = $this->plan($target, $units, $mode, $now); + $warning = $this->travel->warningSeconds($plan['seconds'], $plan['distance'], $mode, self::of($target)->detection()); + $movement = Movement::create([ + 'world_id' => $this->village->world_id, + 'player_id' => $this->village->player_id, + 'type' => $type, + 'mode' => $mode, + 'origin_id' => $this->village->id, + 'target_id' => $target->id, + 'units' => $units, + 'catapult_target' => isset($units['catapult']) && $type === Movement::ATTACK ? ($catapultTarget ?? 'headquarters') : null, + 'rng_seed' => random_int(1, 2_000_000_000), + 'sent_at' => $now, + 'arrives_at' => $plan['arrives_at'], + 'visible_at' => $plan['arrives_at']->subSeconds($warning), + ]); + $this->schedule(GameEvent::MOVEMENT_ARRIVES, $movement, $target->id, $movement->arrives_at); + if ($movement->visible_at->greaterThan($now)) { + $this->schedule(GameEvent::MOVEMENT_SPOTTED, $movement, $target->id, $movement->visible_at); + } else { + Push::queue($target->id); + } + + return $movement; + } + + /** Call an attack or support back within the cancel window: it turns around where it is. */ + public function cancel(int $movementId, CarbonImmutable $now): void + { + $movement = Movement::whereKey($movementId)->lockForUpdate()->first(); + if (! $movement || $movement->origin_id !== $this->village->id || $movement->type === Movement::RETURN) { + throw new GameRuleViolation('not_found', 'No such command.'); + } + if ($now->greaterThan($movement->sent_at->addSeconds($this->cancelWindow())) || ! $movement->arrives_at->greaterThan($now)) { + throw new GameRuleViolation('too_late', 'Too late to call it back.'); + } + GameEvent::whereIn('type', [GameEvent::MOVEMENT_ARRIVES, GameEvent::MOVEMENT_SPOTTED]) + ->where('subject_id', $movement->id)->whereNull('processed_at')->delete(); + Push::queue($movement->target_id); + + $elapsed = $now->getTimestampMs() - $movement->sent_at->getTimestampMs(); + $movement->update([ + 'type' => Movement::RETURN, + 'origin_id' => $movement->target_id, + 'target_id' => $this->village->id, + 'catapult_target' => null, + 'sent_at' => $now, + 'arrives_at' => $now->addMilliseconds($elapsed), + 'visible_at' => $now, + ]); + $this->schedule(GameEvent::MOVEMENT_ARRIVES, $movement, $this->village->id, $movement->arrives_at); + } + + /** Send the support of one home village stationed here back home (by the host, the owner or hunger). */ + public function sendHome(int $homeId, CarbonImmutable $at): void + { + $stacks = $this->village->troops->filter(fn (UnitStack $s) => $s->home_village_id === $homeId && $homeId !== $this->village->id); + $home = Village::find($homeId); + if ($stacks->isEmpty() || ! $home) { + return; + } + $this->sim->settle($at); + $units = $stacks->mapWithKeys(fn (UnitStack $s) => [$s->unit => $s->count])->filter()->all(); + $stacks->each->delete(); + $this->village->setRelation('troops', $this->village->troops->diff($stacks)->values()); + + $mode = $this->travel->defaultMode(); + $seconds = $this->plan($home, $units, $mode, $at)['seconds']; + $movement = Movement::create([ + 'world_id' => $this->village->world_id, + 'player_id' => $home->player_id, + 'type' => Movement::RETURN, + 'mode' => $mode, + 'origin_id' => $this->village->id, + 'target_id' => $homeId, + 'units' => $units, + 'sent_at' => $at, + 'arrives_at' => $at->addSeconds($seconds), + 'visible_at' => $at, + ]); + $this->schedule(GameEvent::MOVEMENT_ARRIVES, $movement, $homeId, $movement->arrives_at); + Push::queue($homeId); + } + + /** A movement reaches this village: battle, support moving in, or troops coming home. */ + public function arrive(int $movementId, CarbonImmutable $at): void + { + $movement = Movement::whereKey($movementId)->lockForUpdate()->first(); + // Called back or already handled. + if (! $movement || $movement->target_id !== $this->village->id || $movement->arrives_at->greaterThan($at)) { + return; + } + $this->sim->settle($at); + Military::of($this->village, $this->sim)->settle($at); + + match ($movement->type) { + Movement::ATTACK => $this->battle($movement, $at), + Movement::SUPPORT => $this->station($movement, $at), + Movement::RETURN => $this->homecoming($movement), + }; + } + + private function battle(Movement $movement, CarbonImmutable $at): void + { + $config = $this->sim->config(); + $combat = new CombatResolver($config); + $stacks = $this->village->troops->filter(fn (UnitStack $s) => $s->count > 0); + $defense = []; + foreach ($stacks as $stack) { + $defense[$stack->unit] = ($defense[$stack->unit] ?? 0) + $stack->count; + } + if ($this->village->militia > 0) { + $defense['militia'] = (int) $this->village->militia; + } + $wall = $this->village->buildings->firstWhere('type', 'wall'); + $defenderPoints = $this->village->player_id ? (int) Village::where('player_id', $this->village->player_id)->sum('points') : null; + mt_srand($movement->rng_seed); + $luck = $combat->luck(mt_rand() / (mt_getrandmax() + 1)); + $morale = $combat->morale($defenderPoints, (int) Village::where('player_id', $movement->player_id)->sum('points')); + $night = $combat->night($at); + $battle = $combat->fight($movement->units, $defense, $wall?->level ?? 0, $morale, $luck, $night); + + // Defenders fall in every stack alike, support included. + $defenseLost = []; + $supporters = []; + foreach ($stacks as $stack) { + if ($stack->home_village_id !== $this->village->id) { + $supporters[$stack->home_village_id] = true; + } + $dead = Battle::dead([$stack->unit => $stack->count], $battle->defenseLoss)[$stack->unit]; + $defenseLost[$stack->unit] = ($defenseLost[$stack->unit] ?? 0) + $dead; + $stack->count -= $dead; + $stack->count > 0 ? $stack->save() : $stack->delete(); + } + $this->village->setRelation('troops', $this->village->troops->filter(fn (UnitStack $s) => $s->count > 0)->values()); + if (isset($defense['militia'])) { + $defenseLost['militia'] = Battle::dead(['militia' => $defense['militia']], $battle->defenseLoss)['militia']; + $this->village->militia -= $defenseLost['militia']; + if ($this->village->militia <= 0) { + Military::of($this->village, $this->sim)->endLevy($at); + } + } + + $damaged = false; + if ($wall && $battle->wallAfter < $wall->level) { + $this->damage($wall, $battle->wallAfter, $at); + $damaged = true; + } + $attackLost = Battle::dead($movement->units, $battle->attackLoss); + $survivors = []; + foreach ($movement->units as $unit => $count) { + if ($count > $attackLost[$unit]) { + $survivors[$unit] = $count - $attackLost[$unit]; + } + } + + $hit = null; + if ($battle->attackerWon && ($survivors['catapult'] ?? 0) > 0 && $movement->catapult_target) { + $building = $this->village->buildings->where('type', $movement->catapult_target)->sortByDesc('level')->first(); + if ($building) { + $after = $combat->siege('catapult', $building->level, $survivors['catapult']); + $hit = ['type' => $building->type, 'before' => $building->level, 'after' => $after]; + if ($after < $building->level) { + $this->damage($building, $after, $at); + $damaged = true; + } + } + } + + $loot = ['wood' => 0, 'clay' => 0, 'iron' => 0]; + $capacity = 0; + if ($battle->attackerWon) { + $capacity = (new LootCalculator($config))->capacity($survivors); + $stock = ['wood' => $this->village->wood, 'clay' => $this->village->clay, 'iron' => $this->village->iron]; + $loot = LootCalculator::take($stock, $this->hidden(), $capacity); + foreach ($loot as $resource => $amount) { + $this->village->{$resource} -= $amount; + } + } + if ($damaged) { + $this->village->points = $this->sim->points(); + } + + $origin = Village::with('player')->find($movement->origin_id); + $report = [ + 'won' => $battle->attackerWon, + 'luck' => round($luck * 100, 1), + 'morale' => (int) round($morale * 100), + 'night' => $night > 1, + 'attacker' => ['village' => self::summary($origin), 'units' => $movement->units, 'lost' => $attackLost], + 'defender' => ['village' => self::summary($this->village), 'units' => $defense, 'lost' => $defenseLost], + 'wall' => $wall ? ['before' => $battle->wallBefore, 'after' => $wall->level] : null, + 'building' => $hit, + 'loot' => $loot, + 'capacity' => $capacity, + ]; + // An attacker with no survivors learns nothing about the defence. + $seen = $survivors ? $report : ['defender' => ['village' => $report['defender']['village'], 'units' => null, 'lost' => null], 'wall' => null] + $report; + Report::write($movement->player_id, Report::ATTACK, $seen, $at); + Report::write($this->village->player_id, Report::DEFENSE, $report, $at); + foreach (Village::whereIn('id', array_keys($supporters))->get() as $home) { + if ($home->player_id !== $this->village->player_id) { + Report::write($home->player_id, Report::DEFENSE, $report, $at); + } + Push::queue($home->id); + } + Push::queue($movement->origin_id); + + $survivors ? $this->turnBack($movement, $survivors, $loot, $at) : $movement->delete(); + } + + /** Support moves in: the host feeds it from now on. */ + private function station(Movement $movement, CarbonImmutable $at): void + { + $this->put($movement->origin_id, $movement->units); + $origin = Village::with('player')->find($movement->origin_id); + $report = ['from' => self::summary($origin), 'to' => self::summary($this->village), 'units' => $movement->units]; + Report::write($movement->player_id, Report::SUPPORT, $report, $at); + if ($this->village->player_id !== $movement->player_id) { + Report::write($this->village->player_id, Report::SUPPORT, $report, $at); + } + Push::queue($movement->origin_id); + $movement->delete(); + } + + /** Troops back home, with whatever they carry; what doesn't fit the storage is lost. */ + private function homecoming(Movement $movement): void + { + $this->put($this->village->id, $movement->units); + if ($movement->cargo) { + $this->sim->refund($movement->cargo); + } + $movement->delete(); + } + + /** + * The survivors head home with their loot, taking as long as they took to get here. + * + * @param array $units + * @param array $cargo + */ + private function turnBack(Movement $movement, array $units, array $cargo, CarbonImmutable $at): void + { + $took = $movement->arrives_at->getTimestampMs() - $movement->sent_at->getTimestampMs(); + $home = $movement->origin_id; + $movement->update([ + 'type' => Movement::RETURN, + 'origin_id' => $movement->target_id, + 'target_id' => $home, + 'units' => $units, + 'cargo' => array_sum($cargo) > 0 ? $cargo : null, + 'catapult_target' => null, + 'sent_at' => $at, + 'arrives_at' => $at->addMilliseconds($took), + 'visible_at' => $at, + ]); + $this->schedule(GameEvent::MOVEMENT_ARRIVES, $movement, $home, $movement->arrives_at); + } + + /** + * Rams or catapults took a building down to $level. Its queued orders no longer fit + * and are cancelled with a full refund; the builders move on to the next ones. + */ + private function damage(Building $building, int $level, CarbonImmutable $at): void + { + $queued = $this->village->orders->firstWhere('building_id', $building->id); + if ($queued) { + $this->sim->cancel($queued); + } + $building->level = $level; + $building->save(); + $this->sim->startWaitingOrders($at); + } + + /** @param array $units */ + private function take(array $units): void + { + foreach ($units as $unit => $count) { + $stack = $this->village->troops->first(fn (UnitStack $s) => $s->unit === $unit && $s->home_village_id === $this->village->id); + $stack->count -= $count; + $stack->count > 0 ? $stack->save() : $stack->delete(); + } + $this->village->setRelation('troops', $this->village->troops->filter(fn (UnitStack $s) => $s->count > 0)->values()); + } + + /** @param array $units */ + private function put(int $homeId, array $units): void + { + foreach ($units as $unit => $count) { + $stack = $this->village->troops->first(fn (UnitStack $s) => $s->unit === $unit && $s->home_village_id === $homeId); + if ($stack) { + $stack->increment('count', $count); + + continue; + } + $this->village->troops->push($this->village->troops()->create(['home_village_id' => $homeId, 'unit' => $unit, 'count' => $count])); + } + } + + /** Attacks on own villages, support for barbarians, and anything during beginner protection are refused. */ + private function checkTarget(string $type, Village $target, CarbonImmutable $now): void + { + if ($type === Movement::SUPPORT) { + if ($target->player_id === null) { + throw new GameRuleViolation('barbarian', 'Barbarian villages take no support.'); + } + + return; + } + if ($target->player_id === null) { + return; + } + if ($target->player_id === $this->village->player_id) { + throw new GameRuleViolation('own_village', 'That is your own village.'); + } + if ($this->protectedUntil($target->player)->greaterThan($now)) { + throw new GameRuleViolation('protected', 'That player is under beginner protection.'); + } + if ($this->protectedUntil($this->village->player)->greaterThan($now)) { + throw new GameRuleViolation('protected_self', 'Under beginner protection you can only attack barbarians.'); + } + } + + private function schedule(string $type, Movement $movement, int $villageId, CarbonImmutable $at): void + { + GameEvent::create([ + 'world_id' => $this->village->world_id, + 'village_id' => $villageId, + 'type' => $type, + 'subject_id' => $movement->id, + 'fire_at' => $at, + ]); + } + + /** @return array{id: int, name: string, x: int, y: int, player: array{id: int, name: string}|null} */ + public static function summary(Village $village): array + { + return [ + 'id' => $village->id, + 'name' => $village->name, + 'x' => $village->x, + 'y' => $village->y, + 'player' => $village->player ? ['id' => $village->player->id, 'name' => $village->player->name] : null, + ]; + } +} diff --git a/app/Engine/Starvation.php b/app/Engine/Starvation.php index ee4f8c2..3b01471 100644 --- a/app/Engine/Starvation.php +++ b/app/Engine/Starvation.php @@ -62,11 +62,12 @@ final class Starvation } /** - * One desertion wave at $at: own soldiers at home leave, highest upkeep first, as - * few as it takes for income to cover upkeep; if that isn't enough, the levy ends. - * When the village still goes hungry, the next wave follows after `wave_every`. + * One desertion wave at $at: support stationed here is sent home first, group by + * group; then own soldiers at home leave, highest upkeep first, as few as it takes + * for income to cover upkeep; if that isn't enough, the levy ends. When the village + * still goes hungry, the next wave follows after `wave_every`. * - * @return array what left, by unit; `militia` for an ended levy + * @return array what left, by unit; `support` for units sent home, `militia` for an ended levy */ public function wave(CarbonImmutable $at): array { @@ -76,10 +77,23 @@ final class Starvation } $units = new UnitRules($this->sim->config()); + $gone = []; + // Support goes home first, the hungriest group first. + $support = $this->village->troops + ->filter(fn (UnitStack $s) => $s->home_village_id !== $this->village->id) + ->groupBy('home_village_id') + ->sortByDesc(fn ($group) => $group->sum(fn (UnitStack $s) => $units->upkeep($s->unit) * $s->count)); + foreach ($support as $homeId => $group) { + if ($this->fed()) { + break; + } + Rally::of($this->village, $this->sim)->sendHome((int) $homeId, $at); + $gone['support'] = ($gone['support'] ?? 0) + $group->sum('count'); + } + $stacks = $this->village->troops ->where('home_village_id', $this->village->id) ->sortByDesc(fn (UnitStack $s) => $units->upkeep($s->unit)); - $gone = []; foreach ($stacks as $stack) { if ($this->fed()) { break; diff --git a/app/Models/GameEvent.php b/app/Models/GameEvent.php index 2350c70..24d9fd0 100644 --- a/app/Models/GameEvent.php +++ b/app/Models/GameEvent.php @@ -20,6 +20,15 @@ class GameEvent extends Model public const DESERTION = 'starvation.desertion'; + // subject_id is the movement; village_id the village it arrives at. + public const MOVEMENT_ARRIVES = 'movement.arrives'; + + // The target starts to see an incoming group; only pushes the change. + public const MOVEMENT_SPOTTED = 'movement.spotted'; + + // The owner calls support back: village_id is the host, subject_id the support's home village. + public const SUPPORT_RECALLED = 'support.recalled'; + protected $guarded = []; protected $dateFormat = 'Y-m-d H:i:s.v'; diff --git a/app/Models/Movement.php b/app/Models/Movement.php new file mode 100644 index 0000000..1788842 --- /dev/null +++ b/app/Models/Movement.php @@ -0,0 +1,48 @@ + 'array', + 'cargo' => 'array', + 'rng_seed' => 'integer', + 'sent_at' => 'immutable_datetime', + 'arrives_at' => 'immutable_datetime', + 'visible_at' => 'immutable_datetime', + ]; + } + + public function origin(): BelongsTo + { + return $this->belongsTo(Village::class, 'origin_id'); + } + + public function target(): BelongsTo + { + return $this->belongsTo(Village::class, 'target_id'); + } + + /** Where the troops belong: a return trip goes there, the others start there. */ + public function homeId(): int + { + return $this->type === self::RETURN ? $this->target_id : $this->origin_id; + } +} diff --git a/app/Models/Report.php b/app/Models/Report.php new file mode 100644 index 0000000..d63d82e --- /dev/null +++ b/app/Models/Report.php @@ -0,0 +1,37 @@ + 'array', + 'happened_at' => 'immutable_datetime', + 'read_at' => 'immutable_datetime', + ]; + } + + /** @param array $payload */ + public static function write(?int $playerId, string $type, array $payload, CarbonImmutable $at): void + { + if ($playerId !== null) { + self::create(['player_id' => $playerId, 'type' => $type, 'payload' => $payload, 'happened_at' => $at]); + } + } +} diff --git a/app/Models/UnitStack.php b/app/Models/UnitStack.php index 8c6ea73..30543fc 100644 --- a/app/Models/UnitStack.php +++ b/app/Models/UnitStack.php @@ -19,4 +19,9 @@ class UnitStack extends Model { return $this->belongsTo(Village::class); } + + public function home(): BelongsTo + { + return $this->belongsTo(Village::class, 'home_village_id'); + } } diff --git a/app/Models/Village.php b/app/Models/Village.php index 3baf908..eff2dec 100644 --- a/app/Models/Village.php +++ b/app/Models/Village.php @@ -48,7 +48,7 @@ class Village extends Model return $this->hasMany(BuildOrder::class)->orderBy('id'); } - /** Troops standing here, own and (from M4) supporting. */ + /** Troops standing here: own (home_village_id is this village) and support from elsewhere. */ public function troops(): HasMany { return $this->hasMany(UnitStack::class)->orderBy('id'); diff --git a/app/Presenters/RallyPresenter.php b/app/Presenters/RallyPresenter.php new file mode 100644 index 0000000..7ffdd34 --- /dev/null +++ b/app/Presenters/RallyPresenter.php @@ -0,0 +1,96 @@ +id; + $window = Rally::of($village)->cancelWindow(); + + return Movement::with(['origin.player', 'target.player']) + ->where(fn ($q) => $q + ->where(fn ($q) => $q->where('origin_id', $id)->where('type', '!=', Movement::RETURN)) + ->orWhere(fn ($q) => $q->where('target_id', $id)->where('type', Movement::RETURN)) + ->orWhere(fn ($q) => $q->where('target_id', $id)->where('type', '!=', Movement::RETURN)->where('visible_at', '<=', Engine::stamp($now)))) + ->orderBy('arrives_at')->orderBy('id') + ->get() + ->map(function (Movement $m) use ($village, $now, $window) { + $incoming = $m->target_id === $village->id && $m->type !== Movement::RETURN; + $mine = $m->player_id === $village->player_id; + $cancelUntil = $m->sent_at->addSeconds($window); + + return [ + 'id' => $m->id, + 'type' => $m->type, + 'direction' => $incoming ? 'in' : ($m->type === Movement::RETURN ? 'home' : 'out'), + 'mode' => $mine ? $m->mode : null, + 'from' => Rally::summary($m->origin), + 'to' => Rally::summary($m->target), + 'units' => $mine ? $m->units : null, + 'cargo' => $mine ? $m->cargo : null, + 'sent_at' => $mine ? self::iso($m->sent_at) : null, + 'arrives_at' => self::iso($m->arrives_at), + 'cancel_until' => $mine && ! $incoming && $m->type !== Movement::RETURN && $cancelUntil->greaterThan($now) ? self::iso($cancelUntil) : null, + ]; + })->values()->all(); + } + + /** Support stationed here, by home village, and this village's troops stationed elsewhere. */ + public static function support(Village $village): array + { + $here = $village->troops->filter(fn (UnitStack $s) => $s->home_village_id !== $village->id && $s->count > 0)->load('home.player'); + $away = UnitStack::with('village.player')->where('home_village_id', $village->id)->where('village_id', '!=', $village->id)->where('count', '>', 0)->get(); + + return [ + 'here' => self::grouped($here, 'home_village_id', 'home'), + 'away' => self::grouped($away, 'village_id', 'village'), + ]; + } + + public static function rally(Village $village, CarbonImmutable $now): array + { + $rally = Rally::of($village); + $travel = $rally->travel(); + $protected = $village->player ? $rally->protectedUntil($village->player) : null; + + return [ + 'has_rally_point' => $rally->hasRallyPoint(), + 'modes' => array_map(fn (string $mode) => ['mode' => $mode, ...$travel->mode($mode)], $travel->modes()), + 'default_mode' => $travel->defaultMode(), + 'detection' => round($rally->detection(), 1), + 'cancel_window' => $rally->cancelWindow(), + 'protected_until' => $protected && $protected->greaterThan($now) ? self::iso($protected) : null, + ]; + } + + /** @param iterable $stacks */ + private static function grouped(iterable $stacks, string $key, string $relation): array + { + $groups = []; + foreach ($stacks as $stack) { + $groups[$stack->{$key}] ??= ['village' => Rally::summary($stack->{$relation}), 'units' => []]; + $groups[$stack->{$key}]['units'][$stack->unit] = $stack->count; + } + + return array_values(array_map(fn (array $g) => ['village' => $g['village'], 'units' => (object) $g['units']], $groups)); + } + + private static function iso(CarbonImmutable $at): string + { + return $at->utc()->format('Y-m-d\TH:i:s.v\Z'); + } +} diff --git a/app/Presenters/VillagePresenter.php b/app/Presenters/VillagePresenter.php index 9866269..bf20ce7 100644 --- a/app/Presenters/VillagePresenter.php +++ b/app/Presenters/VillagePresenter.php @@ -9,6 +9,7 @@ use App\Game\Map\Continent; use App\Models\Building; use App\Models\BuildOrder; use App\Models\RecruitOrder; +use App\Models\Report; use App\Models\Village; use Carbon\CarbonImmutable; @@ -65,6 +66,10 @@ final class VillagePresenter ], 'troops' => (object) $troops, 'military' => self::military($village, $military, $now), + 'movements' => RallyPresenter::movements($village, $now), + 'support' => RallyPresenter::support($village), + 'rally' => RallyPresenter::rally($village, $now), + '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) { $output = $sim->output($b, $workforce); diff --git a/app/Websocket/Controllers/RallyController.php b/app/Websocket/Controllers/RallyController.php new file mode 100644 index 0000000..3199a75 --- /dev/null +++ b/app/Websocket/Controllers/RallyController.php @@ -0,0 +1,66 @@ +play(fn () => app(PlanMarch::class)( + auth()->user(), + (int) request('village_id'), + (int) request('x'), + (int) request('y'), + (array) request('units', []), + request('mode'), + )); + } + + public function send() + { + return $this->village(fn () => app(SendTroops::class)( + auth()->user(), + (int) request('village_id'), + (string) request('type'), + (int) request('x'), + (int) request('y'), + (array) request('units', []), + request('mode'), + request('catapult_target'), + )); + } + + public function cancel() + { + return $this->village(fn () => app(CancelMovement::class)(auth()->user(), (int) request('village_id'), (int) request('movement_id'))); + } + + public function sendHome() + { + return $this->village(fn () => app(SendSupportHome::class)(auth()->user(), (int) request('village_id'), (int) request('home_village_id'))); + } + + public function withdraw() + { + return $this->village(fn () => app(WithdrawSupport::class)(auth()->user(), (int) request('village_id'), (int) request('host_village_id'))); + } + + private function village(\Closure $action) + { + return $this->play(fn () => VillagePresenter::present($action(), now()->toImmutable())); + } +} diff --git a/app/Websocket/Controllers/ReportController.php b/app/Websocket/Controllers/ReportController.php new file mode 100644 index 0000000..f9f193f --- /dev/null +++ b/app/Websocket/Controllers/ReportController.php @@ -0,0 +1,34 @@ +play(fn () => app(Reports::class)->list(auth()->user(), (int) request('world_id'), (int) (request('page') ?: 1))); + } + + public function show() + { + return $this->play(fn () => app(Reports::class)->show(auth()->user(), (int) request('id'))); + } + + public function delete() + { + return $this->play(fn () => app(Reports::class)->delete( + auth()->user(), + (int) request('world_id'), + array_map('intval', (array) request('ids', [])), + )); + } + + public function readAll() + { + return $this->play(fn () => app(Reports::class)->readAll(auth()->user(), (int) request('world_id'))); + } +} diff --git a/database/migrations/2026_10_30_090000_create_movements_and_reports.php b/database/migrations/2026_10_30_090000_create_movements_and_reports.php new file mode 100644 index 0000000..f581069 --- /dev/null +++ b/database/migrations/2026_10_30_090000_create_movements_and_reports.php @@ -0,0 +1,54 @@ +id(); + $table->foreignId('world_id')->constrained()->cascadeOnDelete(); + // Whose troops they are. + $table->foreignId('player_id')->constrained()->cascadeOnDelete(); + $table->string('type', 16); + $table->string('mode', 16); + $table->foreignId('origin_id')->constrained('villages')->cascadeOnDelete(); + $table->foreignId('target_id')->constrained('villages')->cascadeOnDelete(); + $table->json('units'); + // Loot on a return trip. + $table->json('cargo')->nullable(); + $table->string('catapult_target', 32)->nullable(); + // Seeds the battle's luck, so a replayed event fights the same battle. + $table->unsignedInteger('rng_seed')->default(0); + $table->dateTime('sent_at', 3); + $table->dateTime('arrives_at', 3); + // From when the target sees it coming. + $table->dateTime('visible_at', 3); + $table->timestamps(); + $table->index(['target_id', 'arrives_at']); + $table->index(['origin_id', 'arrives_at']); + }); + + Schema::create('reports', function (Blueprint $table) { + $table->id(); + $table->foreignId('player_id')->constrained()->cascadeOnDelete(); + $table->string('type', 16); + $table->json('payload'); + $table->dateTime('happened_at', 3); + $table->dateTime('read_at')->nullable(); + $table->timestamps(); + $table->index(['player_id', 'happened_at']); + }); + } + + public function down(): void + { + Schema::dropIfExists('reports'); + Schema::dropIfExists('movements'); + } +}; diff --git a/docs/architecture.md b/docs/architecture.md index 7440fa1..c389f02 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -67,9 +67,9 @@ Each village has `builders` (default 2, +1 at the HQ levels listed in world conf ### Starvation -When upkeep exceeds income, the food stock drains. `AppngineStarvation::sync()` runs after every mutation and every event: it keeps a `food.runs_out` event at the exact moment the stock reaches 0. Once the stock is empty and the village is still in deficit, `villages.starving_since` is set and the grace timer runs (`economy.starvation.grace`, default 24h, divided by world speed). When it runs out, a `starvation.desertion` wave fires, and further waves follow every `economy.starvation.wave_every` (1h) while the deficit lasts. +When upkeep exceeds income, the food stock drains. `Starvation::sync()` runs after every mutation and every event: it keeps a `food.runs_out` event at the exact moment the stock reaches 0. Once the stock is empty and the village is still in deficit, `villages.starving_since` is set and the grace timer runs (`economy.starvation.grace`, default 24h, divided by world speed). When it runs out, a `starvation.desertion` wave fires, and further waves follow every `economy.starvation.wave_every` (1h) while the deficit lasts. -A wave takes the fewest units that make income cover upkeep again: foreign support first (M5), then own soldiers at home from the highest upkeep down. Villagers are not stored, they follow the food budget, so they never desert; soldiers leaving frees villagers who staff the farms again. If no soldier is left and the village still goes hungry, the levy ends. Units still in training don't desert, but they finish and stand at home by the next wave. The timer stops as soon as income covers upkeep again or food comes in. +A wave takes the fewest units that make income cover upkeep again: support stationed in the village first (whole groups go home, the hungriest first), then own soldiers at home from the highest upkeep down. Villagers are not stored, they follow the food budget, so they never desert; soldiers leaving frees villagers who staff the farms again. If no soldier is left and the village still goes hungry, the levy ends. Units still in training don't desert, but they finish and stand at home by the next wave. The timer stops as soon as income covers upkeep again or food comes in. ## Village space @@ -143,9 +143,9 @@ A building entry looks like this (numbers start TW-like): | `unit_stacks` | village_id (where they stand), home_village_id (owner), unit, count. unique(village_id, home_village_id, unit) | | `recruit_orders` | village_id, building_id, unit, count, done, seconds_per_unit, starts_at, finishes_at, game_event_id | | `food_deliveries` | village_id, amount, delivered_at. Feeds the 24h import average; each row's expiry is an event | -| `movements` | world_id, player_id, type (attack/support/return/trade), mode, origin_id, target_id, units json, merchants, cargo json, catapult_target, rng_seed, sent_at, arrives_at, visible_at, destroyed_at null | +| `movements` | world_id, player_id (whose troops), type (attack/support/return), mode, origin_id, target_id, units json, cargo json null, catapult_target null, rng_seed, sent_at, arrives_at, visible_at. Trade, merchants and destroyed_at come with M5 | | `tribes`, `tribe_members`, `tribe_relations` | name, tag; player_id, role; tribe_id, other_tribe_id, state (ally/nap/enemy). Arrives in M6 | -| `reports` | player_id, type, payload json, read_at | +| `reports` | player_id, type (attack/defense/support), payload json (a snapshot with village names, units, losses, loot), happened_at, read_at | | `game_events` | world_id, type, subject_type, subject_id, fire_at datetime(3), processed_at null, attempts. index(processed_at, fire_at) | ## Event engine @@ -170,6 +170,17 @@ New players spawn on the spawn ring (`SpawnRing`): radius `start_radius + sqrt(p Every group on the map is a `movement`: an attack, support, return, or trade caravan (merchants, optionally with an escort). It moves in a straight line at constant speed, so its position at time t is a linear interpolation between origin and target. +### Sending troops + +- The rally point sends an attack or support from the units at home to the village at x|y (`rally.send`; `rally.preview` shows the target, distance and travel time first). A village needs a rally point to send anything. Travel time is the slowest unit's minutes per field × distance / (world speed × `movement.unit_speed` × mode speed), with the distance as the crow flies. +- The troops leave at once. Their arrival is a `movement.arrives` event on the target, so it runs under the target's lock and in the target's event order; a `movement.spotted` event at `visible_at` only pushes the change. Reading a village first catches up the targets of its own due groups, so the owner never sees a group that should have arrived. +- Within `movement.cancel_window` (10 real minutes) the sender can call a command back. It turns around and takes as long to get home as it had been under way. +- An attack with survivors turns into its own return trip with the loot, taking as long as the way there. Loot that doesn't fit the storage is lost on arrival. +- Support stands in the host village as unit stacks with their own `home_village_id`. The host feeds it (it counts against the host's food budget), and hunger sends it home before any own soldier deserts. The host can send any support home (`rally.sendHome`), and the owner can withdraw it (`rally.withdraw`, a `support.recalled` event on the host's queue); both start a return trip. Groups under way eat nothing. +- Barbarian villages take no support, and own villages can't be attacked. +- Beginner protection: for `combat.beginner_protection` (3 days, divided by world speed) after joining, a player can't be attacked by players and can only attack barbarians themselves. +- Every battle and every arriving support writes reports (`report.index|show|delete|readAll`): for the attacker, the defender, and every player whose support stood in the village. An attacker with no survivors learns nothing about the defence. The village payload carries the unread count, and the engine pushes `village:updated` to every village an event touched (an attacker's home, a supporter's village). + ### Travel modes Each movement has a mode, defined in `config/game/movement.php`: @@ -180,7 +191,7 @@ Each movement has a mode, defined in `config/game/movement.php`: | cautious | slower | small | | normal | 1.0 | normal | | fast | faster | large | -| fighting march | much faster | very large | +| forced (fighting march) | much faster | very large | The visibility radius decides two things: @@ -201,4 +212,11 @@ Tribes arrive in M6, with ally, NAP (non-aggression pact), and enemy states betw ## Combat -Combat uses the TW model. Attack strength is split into infantry, cavalry, and archer. Defense is weighted by the attacker's composition. Then the wall bonus applies, plus morale and luck (±25%, from world config). Losses follow `(weaker / stronger)^1.5`. Rams lower the wall before the fight, catapults hit a building after it. All of this lives in `CombatResolver` as a pure function and is tested with fixed luck. +Combat uses the TW model, in `CombatResolver` (pure, tested with fixed luck) and `config/game/combat.php`: + +- Attack strength is split into infantry, cavalry and archer by each unit's class. Every defender, own or support, counts with its defence against each class, weighted by the attacker's mix. Levied militia defend with `combat.militia.defense` per head. +- The wall at level L adds `basic_defense × L` and multiplies the defence by `factor^L` (20 and 1.037). Rams lower the wall before the battle: each level L down needs `base × factor^(L − 1)` rams (2 and 1.09). Nothing drops below level 1. +- The attack is multiplied by morale and (1 + luck). Luck is drawn evenly from ±`combat.luck` (25%) with the movement's seed, so a replayed event fights the same battle. Morale is `min(1, 0.3 + 3 × defender points / attacker points)` and always 1 against barbarians. Worlds with a night bonus multiply the defence at night. +- The winner loses `(loser / winner)^1.5` of every unit, rounded per stack; the loser loses everything. Dead militia shrink the levy. +- After a won battle, surviving catapults hit the highest instance of the chosen type (headquarters by default) by the same siege rule. A damaged building's queued orders are cancelled with a full refund, since their levels no longer fit. +- `LootCalculator`: survivors carry `carry` per unit. They take wood, clay and iron evenly, above what the hiding places protect (`hides` per resource; instances add up). Food is not looted. diff --git a/tests/Feature/RallyTest.php b/tests/Feature/RallyTest.php new file mode 100644 index 0000000..895b347 --- /dev/null +++ b/tests/Feature/RallyTest.php @@ -0,0 +1,228 @@ + $this->travelTo(CarbonImmutable::parse('2026-10-29 12:00:00'))); + +/** A rally point and own troops at home. */ +function rallied(Village $village, array $units = []): Village +{ + $village->buildings()->create(['type' => 'rally_point', 'level' => 1]); + foreach ($units as $unit => $count) { + $village->troops()->create(['home_village_id' => $village->id, 'unit' => $unit, 'count' => $count]); + } + + return $village->fresh(); +} + +function barbarianNear(Village $near, int $dx, int $dy): Village +{ + return app(VillageFactory::class)->create($near->world, null, 'Barbarian village', $near->x + $dx, $near->y + $dy, ['headquarters' => 1, 'storage' => 1, 'farm' => 1]); +} + +function worldRules(Village $village, array $config): void +{ + World::whereKey($village->world_id)->update(['config' => $config]); +} + +function send(Village $from, Village $to, array $units, string $type = 'attack', ?string $mode = null, ?string $catapultTarget = null): Village +{ + return app(SendTroops::class)(owner($from), $from->id, $type, $to->x, $to->y, $units, $mode, $catapultTarget); +} + +it('raids an empty barbarian village and carries the loot home', function () { + $village = rallied(startVillage(), ['spear' => 10]); + $barbarian = barbarianNear($village, 3, 4); + + // 5 fields at 18 minutes each. + $state = VillagePresenter::present(send($village, $barbarian, ['spear' => 10]), now()->toImmutable()); + expect((array) $state['troops'])->toBe([]) + ->and($state['movements'])->toHaveCount(1) + ->and($state['movements'][0])->toMatchArray(['type' => 'attack', 'direction' => 'out', 'units' => ['spear' => 10], 'arrives_at' => '2026-10-29T13:30:00.000Z']); + + $this->travel(5400)->seconds(); + $this->artisan('game:events --once')->assertSuccessful(); + $state = shown($village); + // 250 carry, split evenly over 507 of each. + expect($state['movements'][0])->toMatchArray(['type' => 'return', 'direction' => 'home', 'cargo' => ['wood' => 84, 'clay' => 83, 'iron' => 83], 'arrives_at' => '2026-10-29T15:00:00.000Z']) + ->and($state['unread_reports'])->toBe(1) + ->and(Report::sole()->payload)->toMatchArray(['won' => true, 'loot' => ['wood' => 84, 'clay' => 83, 'iron' => 83], 'capacity' => 250]) + ->and($barbarian->fresh()->wood)->toEqualWithDelta(507.5 - 84, 0.01); + + $this->travel(5399)->seconds(); + $before = shown($village)['resources']['wood']; + $this->travel(1)->seconds(); + $this->artisan('game:events --once')->assertSuccessful(); + $state = shown($village); + expect((array) $state['troops'])->toBe(['spear' => 10]) + ->and($state['movements'])->toBe([]) + ->and($state['resources']['wood'])->toEqualWithDelta($before + 84, 0.1); +}); + +it('loses an attack against a stronger defence, and both sides get a report', function () { + $attacker = rallied(startVillage(), ['spear' => 10]); + $defender = startVillage(); + $defender->troops()->create(['home_village_id' => $defender->id, 'unit' => 'sword', 'count' => 20]); + worldRules($attacker, ['combat' => ['beginner_protection' => 0, 'luck' => 0]]); + + send($attacker, $defender, ['spear' => 10]); + $this->travel(1)->days(); + $this->artisan('game:events --once')->assertSuccessful(); + + expect((array) shown($attacker)['troops'])->toBe([]) + ->and(shown($attacker)['movements'])->toBe([]) + ->and((array) shown($defender)['troops'])->toBe(['sword' => 19]); + $attack = Report::where('player_id', $attacker->player_id)->sole(); + $defense = Report::where('player_id', $defender->player_id)->sole(); + expect($attack->type)->toBe('attack') + ->and($attack->payload['won'])->toBeFalse() + ->and($attack->payload['defender']['units'])->toBeNull() + ->and($defense->type)->toBe('defense') + ->and($defense->payload['defender'])->toMatchArray(['units' => ['sword' => 20], 'lost' => ['sword' => 1]]) + ->and($defense->payload['attacker']['lost'])->toBe(['spear' => 10]); +}); + +it('stations support at the host, who feeds it and can send it home', function () { + $home = rallied(startVillage(), ['spear' => 5]); + $host = startVillage(); + + send($home, $host, ['spear' => 5], 'support'); + $this->travel(1)->days(); + $state = shown($host); + expect($state['support']['here'])->toHaveCount(1) + ->and($state['support']['here'][0]['village']['id'])->toBe($home->id) + ->and((array) $state['support']['here'][0]['units'])->toBe(['spear' => 5]) + ->and($state['population']['villagers'])->toBe(19) + ->and(shown($home)['support']['away'][0]['village']['id'])->toBe($host->id) + ->and(Report::where('type', 'support')->count())->toBe(2); + + app(SendSupportHome::class)(owner($host), $host->id, $home->id); + expect(shown($host)['support']['here'])->toBe([]) + ->and(shown($home)['movements'][0])->toMatchArray(['type' => 'return', 'direction' => 'home', 'units' => ['spear' => 5]]); + $this->travel(1)->days(); + expect((array) shown($home)['troops'])->toBe(['spear' => 5]); +}); + +it('lets the owner call support back from the host', function () { + $home = rallied(startVillage(), ['spear' => 5]); + $host = startVillage(); + send($home, $host, ['spear' => 5], 'support'); + $this->travel(1)->days(); + + $state = VillagePresenter::present(app(WithdrawSupport::class)(owner($home), $home->id, $host->id), now()->toImmutable()); + expect($state['movements'][0])->toMatchArray(['direction' => 'home', 'units' => ['spear' => 5]]) + ->and($state['support']['away'])->toBe([]) + ->and(shown($host)['support']['here'])->toBe([]); + $this->travel(1)->days(); + expect((array) shown($home)['troops'])->toBe(['spear' => 5]); +}); + +it('calls an attack back within the cancel window', function () { + $village = rallied(startVillage(), ['spear' => 10]); + $barbarian = barbarianNear($village, 3, 4); + send($village, $barbarian, ['spear' => 10]); + + $this->travel(60)->seconds(); + app(CancelMovement::class)(owner($village), $village->id, Movement::sole()->id); + expect(shown($village)['movements'][0])->toMatchArray(['direction' => 'home', 'arrives_at' => '2026-10-29T12:02:00.000Z', 'cancel_until' => null]) + ->and(GameEvent::where('type', GameEvent::MOVEMENT_ARRIVES)->whereNull('processed_at')->count())->toBe(1); + $this->travel(60)->seconds(); + expect((array) shown($village)['troops'])->toBe(['spear' => 10]) + ->and(Report::count())->toBe(0); + + send($village, $barbarian, ['spear' => 10]); + $this->travel(11)->minutes(); + expect(rule(fn () => app(CancelMovement::class)(owner($village), $village->id, Movement::sole()->id)))->toBe('too_late'); +}); + +it('refuses what the rally point cannot do', function () { + $village = startVillage(); + $other = startVillage(); + $village->troops()->create(['home_village_id' => $village->id, 'unit' => 'spear', 'count' => 5]); + expect(rule(fn () => send($village, $other, ['spear' => 5])))->toBe('no_rally_point'); + + rallied($village); + expect(rule(fn () => send($village, $other, ['spear' => 6])))->toBe('troops') + ->and(rule(fn () => send($village, $other, ['spear' => 0])))->toBe('count') + ->and(rule(fn () => send($village, $village, ['spear' => 5])))->toBe('same_village') + ->and(rule(fn () => send($village, $other, ['spear' => 5])))->toBe('protected') + ->and(rule(fn () => send($village, barbarianNear($village, 3, 4), ['spear' => 5], 'support')))->toBe('barbarian') + ->and(Movement::count())->toBe(0); + + // Beginner protection lasts three days at world speed 1. + $this->travel(4)->days(); + send($village, $other, ['spear' => 5]); + expect(Movement::count())->toBe(1); +}); + +it('shows an incoming attack once it is within sight, a sneaky one only on arrival', function () { + $attacker = rallied(startVillage(), ['spear' => 10]); + $defender = startVillage(); + $defender->update(['x' => $attacker->x + 34, 'y' => $attacker->y]); + worldRules($attacker, ['combat' => ['beginner_protection' => 0]]); + + send($attacker, $defender->fresh(), ['spear' => 5]); + send($attacker, $defender->fresh(), ['spear' => 5], 'attack', 'sneaky'); + expect(shown($defender)['movements'])->toBe([]); + + // 34 fields; normal visibility 15 plus detection 2 is 17: spotted halfway. + $this->travel(18 * 17)->minutes(); + $incoming = shown($defender)['movements']; + expect($incoming)->toHaveCount(1) + ->and($incoming[0])->toMatchArray(['direction' => 'in', 'type' => 'attack', 'units' => null, 'mode' => null, 'sent_at' => null]); +}); + +it('rams the wall down first and lets catapults hit the chosen building, refunding its queued orders', function () { + $attacker = rallied(startVillage(), ['light_cavalry' => 50, 'ram' => 20, 'catapult' => 20]); + $defender = startVillage(); + worldRules($attacker, ['combat' => ['beginner_protection' => 0, 'luck' => 0]]); + $defender->update(['x' => $attacker->x + 1, 'y' => $attacker->y, 'wood' => 10000, 'clay' => 10000, 'iron' => 10000]); + $defender->buildings()->where('type', 'headquarters')->update(['level' => 20]); + $defender->buildings()->where('type', 'storage')->update(['level' => 15]); + $defender->buildings()->create(['type' => 'wall', 'level' => 10]); + app(QueueUpgrade::class)(owner($defender), $defender->id, $defender->buildings()->where('type', 'headquarters')->value('id')); + expect(shown($defender)['queue'])->toHaveCount(1); + + send($attacker, $defender->fresh(), ['light_cavalry' => 50, 'ram' => 20, 'catapult' => 20], 'attack', null, 'headquarters'); + $this->travel(30)->minutes(); + $this->artisan('game:events --once')->assertSuccessful(); + + $report = Report::where('player_id', $defender->player_id)->sole()->payload; + $state = shown($defender); + $levels = collect($state['buildings'])->pluck('level', 'type'); + expect($report['won'])->toBeTrue() + ->and($report['wall'])->toBe(['before' => 10, 'after' => 5]) + ->and($report['building'])->toBe(['type' => 'headquarters', 'before' => 20, 'after' => 18]) + ->and($state['queue'])->toBe([]) + ->and($levels['headquarters'])->toBe(18) + ->and($levels['wall'])->toBe(5); +}); + +it('sends hungry support home before own soldiers desert', function () { + $home = startVillage(); + $host = startVillage(); + $host->troops()->create(['home_village_id' => $home->id, 'unit' => 'spear', 'count' => 30]); + $host->troops()->create(['home_village_id' => $host->id, 'unit' => 'spear', 'count' => 2]); + $host->update(['food' => 0]); + expect(shown($host)['starvation']['since'])->not->toBeNull(); + + $this->travel(24)->hours(); + $this->artisan('game:events --once')->assertSuccessful(); + $state = shown($host); + expect($state['support']['here'])->toBe([]) + ->and((array) $state['troops'])->toBe(['spear' => 2]) + ->and($state['starvation']['since'])->toBeNull() + ->and(shown($home)['movements'][0])->toMatchArray(['type' => 'return', 'units' => ['spear' => 30]]); +});