From b79dcb81e7756c65bca821d5e645848a44d43729 Mon Sep 17 00:00:00 2001 From: "Fabian @ Blax Software" Date: Sat, 31 Oct 2026 10:59:34 +0100 Subject: [PATCH] feat: market: merchants carry resources between villages, offers between players, repeating trade routes Trades are movements (trade, trade_return) that arrive by the target's movement.arrives event; they stay out of the rally lists, the map and the rally cancel. A trade.route event sends a route's next shipment. A village that changes hands loses its trades under way, offers and routes. WS: market.show|preview|send|offers|offer|cancelOffer|accept|routeCreate|routeUpdate|routeDelete; the village payload carries market {building_id, level, merchants, free, carry}. Co-Authored-By: Claude Opus 5.5 (1M context) --- app/Actions/ListOffers.php | 57 +++ app/Actions/MarketDeals.php | 52 ++ app/Actions/MarketRoutes.php | 38 ++ app/Actions/PlanTrade.php | 34 ++ app/Actions/Reports.php | 4 +- app/Actions/ShowMap.php | 1 + app/Actions/ShowMarket.php | 20 + app/Engine/Engine.php | 3 +- app/Engine/Market.php | 458 ++++++++++++++++++ app/Engine/Nobility.php | 8 +- app/Engine/Rally.php | 3 +- app/Models/GameEvent.php | 3 + app/Models/Movement.php | 13 +- app/Models/Report.php | 3 + app/Models/TradeOffer.php | 30 ++ app/Models/TradeRoute.php | 46 ++ app/Presenters/MarketPresenter.php | 119 +++++ app/Presenters/RallyPresenter.php | 1 + app/Presenters/VillagePresenter.php | 1 + .../Controllers/MarketController.php | 108 +++++ .../2026_11_03_120000_create_market.php | 67 +++ 21 files changed, 1061 insertions(+), 8 deletions(-) create mode 100644 app/Actions/ListOffers.php create mode 100644 app/Actions/MarketDeals.php create mode 100644 app/Actions/MarketRoutes.php create mode 100644 app/Actions/PlanTrade.php create mode 100644 app/Actions/ShowMarket.php create mode 100644 app/Engine/Market.php create mode 100644 app/Models/TradeOffer.php create mode 100644 app/Models/TradeRoute.php create mode 100644 app/Presenters/MarketPresenter.php create mode 100644 app/Websocket/Controllers/MarketController.php create mode 100644 database/migrations/2026_11_03_120000_create_market.php diff --git a/app/Actions/ListOffers.php b/app/Actions/ListOffers.php new file mode 100644 index 0000000..fa713c3 --- /dev/null +++ b/app/Actions/ListOffers.php @@ -0,0 +1,57 @@ +find($villageId); + if (! $village || $village->player?->user_id !== $user->id) { + throw new GameRuleViolation('not_found', 'Village not found.'); + } + $rules = new TradeRules($village->world->gameConfig()); + [$x, $y] = [$village->x, $village->y]; + + $offers = TradeOffer::with('village.player') + ->select('trade_offers.*') + ->join('villages', 'villages.id', '=', 'trade_offers.village_id') + ->where('trade_offers.world_id', $village->world_id) + ->when($give, fn ($q) => $q->where('trade_offers.give_resource', $give)) + ->when($want, fn ($q) => $q->where('trade_offers.want_resource', $want)) + ->orderByRaw('(villages.x - ?) * (villages.x - ?) + (villages.y - ?) * (villages.y - ?)', [$x, $x, $y, $y]) + ->orderBy('trade_offers.id') + ->limit(self::LIMIT) + ->get(); + + return [ + 'server_time' => MarketPresenter::iso(now()), + 'offers' => $offers->map(function (TradeOffer $o) use ($village, $rules, $x, $y) { + $distance = TravelTime::distance($x, $y, $o->village->x, $o->village->y); + + return [ + 'id' => $o->id, + 'village' => Rally::summary($o->village), + 'give' => ['resource' => $o->give_resource, 'amount' => $o->give_amount], + 'want' => ['resource' => $o->want_resource, 'amount' => $o->want_amount], + 'count' => $o->count, + 'distance' => round($distance, 2), + 'seconds' => $rules->seconds($distance), + 'own' => $o->village->player_id === $village->player_id, + ]; + })->values()->all(), + ]; + } +} diff --git a/app/Actions/MarketDeals.php b/app/Actions/MarketDeals.php new file mode 100644 index 0000000..66f4cb4 --- /dev/null +++ b/app/Actions/MarketDeals.php @@ -0,0 +1,52 @@ + $amounts wood, clay, iron */ + public function send(User $user, int $villageId, int $x, int $y, array $amounts): Village + { + return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($x, $y, $amounts) { + $market = Market::of($village, $sim); + $market->requireMarket(); + $market->send(self::target($village, $x, $y), $amounts, $now); + }); + } + + public function offer(User $user, int $villageId, string $give, int $giveAmount, string $want, int $wantAmount, int $count): Village + { + return $this->mutate($user, $villageId, function (Simulation $sim, Village $village) use ($give, $giveAmount, $want, $wantAmount, $count) { + Market::of($village, $sim)->offer($give, $giveAmount, $want, $wantAmount, $count); + }); + } + + public function cancelOffer(User $user, int $villageId, int $offerId): Village + { + return $this->mutate($user, $villageId, function (Simulation $sim, Village $village) use ($offerId) { + Market::of($village, $sim)->cancelOffer($offerId); + }); + } + + public function accept(User $user, int $villageId, int $offerId, int $count): Village + { + return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($offerId, $count) { + Market::of($village, $sim)->accept($offerId, $count, $now); + }); + } + + /** The village at x|y on the same world. */ + public static function target(Village $village, int $x, int $y): Village + { + return Village::with('player')->where('world_id', $village->world_id)->where('x', $x)->where('y', $y)->first() + ?? throw new GameRuleViolation('not_found', 'No village there.'); + } +} diff --git a/app/Actions/MarketRoutes.php b/app/Actions/MarketRoutes.php new file mode 100644 index 0000000..4d56ea0 --- /dev/null +++ b/app/Actions/MarketRoutes.php @@ -0,0 +1,38 @@ + $amounts wood, clay, iron */ + public function create(User $user, int $villageId, int $x, int $y, array $amounts, int $every): Village + { + return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($x, $y, $amounts, $every) { + $market = Market::of($village, $sim); + $market->requireMarket(); + $market->createRoute(MarketDeals::target($village, $x, $y), $amounts, $every, $now); + }); + } + + /** @param array{wood?: int|null, clay?: int|null, iron?: int|null, every?: int|null, paused?: bool|null} $changes null leaves a field as it is */ + public function update(User $user, int $villageId, int $routeId, array $changes): Village + { + return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($routeId, $changes) { + Market::of($village, $sim)->updateRoute($routeId, $changes, $now); + }); + } + + public function delete(User $user, int $villageId, int $routeId): Village + { + return $this->mutate($user, $villageId, function (Simulation $sim, Village $village) use ($routeId) { + Market::of($village, $sim)->deleteRoute($routeId); + }); + } +} diff --git a/app/Actions/PlanTrade.php b/app/Actions/PlanTrade.php new file mode 100644 index 0000000..0a028c3 --- /dev/null +++ b/app/Actions/PlanTrade.php @@ -0,0 +1,34 @@ +find($villageId); + if (! $village || $village->player?->user_id !== $user->id) { + throw new GameRuleViolation('not_found', 'Village not found.'); + } + $target = Village::with('player')->where('world_id', $village->world_id)->where('x', $x)->where('y', $y)->first() + ?? throw new GameRuleViolation('not_found', 'No village there.'); + $market = Market::of($village); + $market->checkTarget($target); + $plan = $market->plan($target, now()->toImmutable()); + + return [ + 'target' => Rally::summary($target), + 'distance' => round($plan['distance'], 2), + 'seconds' => $plan['seconds'], + 'arrives_at' => MarketPresenter::iso($plan['arrives_at']), + ]; + } +} diff --git a/app/Actions/Reports.php b/app/Actions/Reports.php index 705a242..33a881e 100644 --- a/app/Actions/Reports.php +++ b/app/Actions/Reports.php @@ -15,7 +15,7 @@ final class Reports public const PER_PAGE = 25; /** - * A page of reports, newest first; `type` keeps one kind (attack, defense, support). + * A page of reports, newest first; `type` keeps one kind (attack, defense, support, trade). * The unread count is over every kind. * * @return array{reports: list>, page: int, pages: int, unread: int} @@ -23,7 +23,7 @@ final class Reports public function list(User $user, int $worldId, int $page = 1, ?string $type = null): array { $query = $this->of($user, $worldId)->orderByDesc('happened_at')->orderByDesc('id'); - if (in_array($type, [Report::ATTACK, Report::DEFENSE, Report::SUPPORT], true)) { + if (in_array($type, [Report::ATTACK, Report::DEFENSE, Report::SUPPORT, Report::TRADE], true)) { $query->where('type', $type); } $pages = max(1, (int) ceil($query->count() / self::PER_PAGE)); diff --git a/app/Actions/ShowMap.php b/app/Actions/ShowMap.php index 2615da1..4cf3501 100644 --- a/app/Actions/ShowMap.php +++ b/app/Actions/ShowMap.php @@ -114,6 +114,7 @@ final class ShowMap return Movement::with(['origin:id,name,x,y', 'target:id,name,x,y']) ->where('world_id', $world->id) + ->whereNotIn('type', Movement::TRADES) ->where(fn ($q) => $q->where('player_id', $me->id) ->orWhere(fn ($q) => $q->whereIn('target_id', $mine)->where('type', '!=', Movement::RETURN)->where('visible_at', '<=', Engine::stamp($now)))) ->where('arrives_at', '>', Engine::stamp($now)) diff --git a/app/Actions/ShowMarket.php b/app/Actions/ShowMarket.php new file mode 100644 index 0000000..7b7b4a6 --- /dev/null +++ b/app/Actions/ShowMarket.php @@ -0,0 +1,20 @@ +mutate($user, $villageId, fn () => null); + } + + protected function readOnly(): bool + { + return true; + } +} diff --git a/app/Engine/Engine.php b/app/Engine/Engine.php index cde7e3e..3e586b2 100644 --- a/app/Engine/Engine.php +++ b/app/Engine/Engine.php @@ -38,7 +38,7 @@ final class Engine public function catchUpAround(int $villageId, CarbonImmutable $now): void { $targets = Movement::where('origin_id', $villageId) - ->whereIn('type', [Movement::ATTACK, Movement::SUPPORT]) + ->whereIn('type', [Movement::ATTACK, Movement::SUPPORT, Movement::TRADE]) ->where('arrives_at', '<=', self::stamp($now)) ->distinct()->pluck('target_id'); foreach ($targets as $target) { @@ -129,6 +129,7 @@ final class Engine // 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), + GameEvent::TRADE_ROUTE => Market::of($village)->runRoute($event), }; } diff --git a/app/Engine/Market.php b/app/Engine/Market.php new file mode 100644 index 0000000..db4e138 --- /dev/null +++ b/app/Engine/Market.php @@ -0,0 +1,458 @@ +rules = new TradeRules($sim->config()); + } + + public static function of(Village $village, ?Simulation $sim = null): self + { + return new self($village, $sim ?? Simulation::of($village)); + } + + public function rules(): TradeRules + { + return $this->rules; + } + + public function building(): ?Building + { + return $this->village->buildings->firstWhere('type', TradeRules::BUILDING); + } + + /** Merchants the market's level gives, 0 without a market. */ + public function merchants(): int + { + return $this->rules->merchants($this->building()?->level ?? 0); + } + + /** Merchants on this village's trades, out and back, and reserved by its open offers. */ + public function busy(): int + { + $id = $this->village->id; + $moving = (int) Movement::where(fn ($q) => $q + ->where(fn ($q) => $q->where('origin_id', $id)->where('type', Movement::TRADE)) + ->orWhere(fn ($q) => $q->where('target_id', $id)->where('type', Movement::TRADE_RETURN))) + ->sum('merchants'); + $reserved = (int) TradeOffer::where('village_id', $id)->sum(DB::raw('count * merchants')); + + return $moving + $reserved; + } + + public function free(): int + { + return TradeRules::free($this->merchants(), $this->busy()); + } + + public function requireMarket(): void + { + if (! $this->building()) { + throw new GameRuleViolation('no_market', 'Build a market first.'); + } + } + + /** Merchants go to another player village of the same world. */ + public function checkTarget(Village $target): void + { + if ($target->id === $this->village->id || $target->world_id !== $this->village->world_id) { + throw new GameRuleViolation('same_village', 'Pick another village.'); + } + if ($target->player_id === null) { + throw new GameRuleViolation('barbarian', 'Barbarian villages don\'t trade.'); + } + } + + /** @return array{distance: float, seconds: int, arrives_at: CarbonImmutable} */ + public function plan(Village $target, CarbonImmutable $now): array + { + $distance = TravelTime::distance($this->village->x, $this->village->y, $target->x, $target->y); + $seconds = $this->rules->seconds($distance); + + return ['distance' => $distance, 'seconds' => $seconds, 'arrives_at' => $now->addSeconds($seconds)]; + } + + /** + * Send resources from the stock to $target; the merchants leave at once. + * + * @param array $amounts + */ + public function send(Village $target, array $amounts, CarbonImmutable $now): Movement + { + $this->requireMarket(); + $this->checkTarget($target); + $cargo = $this->rules->cargo($amounts); + if (array_sum($cargo) <= 0) { + throw new GameRuleViolation('nothing', 'Send at least one resource.'); + } + if (! $this->sim->canPay($cargo)) { + throw new GameRuleViolation('resources', 'Not enough resources.'); + } + $merchants = $this->rules->needed(array_sum($cargo)); + if ($merchants > $this->free()) { + throw new GameRuleViolation('merchants', 'Not enough free merchants.'); + } + $this->sim->pay($cargo); + + return $this->dispatch($this->village, $target, $cargo, $merchants, $now); + } + + // Offers + + /** Offer count times giveAmount of one resource for wantAmount of another; the goods and merchants are reserved. */ + public function offer(string $give, int $giveAmount, string $want, int $wantAmount, int $count): TradeOffer + { + $this->requireMarket(); + $this->rules->checkOffer($give, $giveAmount, $want, $wantAmount, $count); + $reserve = $this->rules->cargo([$give => $giveAmount * $count]); + if (! $this->sim->canPay($reserve)) { + throw new GameRuleViolation('resources', 'Not enough resources.'); + } + $merchants = $this->rules->needed($giveAmount); + if ($merchants * $count > $this->free()) { + throw new GameRuleViolation('merchants', 'Not enough free merchants.'); + } + $this->sim->pay($reserve); + + return TradeOffer::create([ + 'world_id' => $this->village->world_id, + 'village_id' => $this->village->id, + 'give_resource' => $give, + 'give_amount' => $giveAmount, + 'want_resource' => $want, + 'want_amount' => $wantAmount, + 'count' => $count, + 'merchants' => $merchants, + ]); + } + + /** Take an own offer back: the goods of the open count return as far as the storage holds them. */ + public function cancelOffer(int $offerId): void + { + $offer = TradeOffer::whereKey($offerId)->lockForUpdate()->first(); + if (! $offer || $offer->village_id !== $this->village->id) { + throw new GameRuleViolation('not_found', 'No such offer.'); + } + $this->sim->refund([$offer->give_resource => $offer->give_amount * $offer->count]); + $offer->delete(); + } + + /** + * Take $count of another player's offer: this village's merchants carry what it asks + * for, the offer's reserved merchants carry what it gives, and both leave at once. + * The offer row stays locked, so two buyers can't take the same count. + */ + public function accept(int $offerId, int $count, CarbonImmutable $now): void + { + $this->requireMarket(); + $offer = TradeOffer::whereKey($offerId)->lockForUpdate()->first(); + $seller = $offer ? Village::with('player')->find($offer->village_id) : null; + if (! $offer || ! $seller || $offer->world_id !== $this->village->world_id || $offer->count < 1) { + throw new GameRuleViolation('not_found', 'That offer is gone.'); + } + if ($seller->player_id === $this->village->player_id) { + throw new GameRuleViolation('own_offer', 'That is your own offer.'); + } + if ($count < 1 || $count > $offer->count) { + throw new GameRuleViolation('count', 'Not that many of this offer are open.'); + } + $pay = $this->rules->cargo([$offer->want_resource => $offer->want_amount * $count]); + if (! $this->sim->canPay($pay)) { + throw new GameRuleViolation('resources', 'Not enough resources.'); + } + $merchants = $this->rules->needed(array_sum($pay)); + if ($merchants > $this->free()) { + throw new GameRuleViolation('merchants', 'Not enough free merchants.'); + } + $this->sim->pay($pay); + $this->dispatch($this->village, $seller, $pay, $merchants, $now, null, true); + $goods = $this->rules->cargo([$offer->give_resource => $offer->give_amount * $count]); + $this->dispatch($seller, $this->village, $goods, $offer->merchants * $count, $now, null, true); + + $offer->count -= $count; + $offer->count > 0 ? $offer->save() : $offer->delete(); + Push::queue($seller->id, $this->village->id); + } + + // Arrivals + + /** + * Merchants reach this village (the caller settled it). With cargo they unload into + * the storage, where what doesn't fit is lost, and turn round, taking as long home as + * they took here. Empty ones are home and free again. + */ + public function arrive(Movement $movement, CarbonImmutable $at): void + { + if ($movement->type === Movement::TRADE_RETURN) { + $movement->delete(); + Push::queue($this->village->id); + + return; + } + $this->sim->refund($movement->cargo ?? []); + $this->report($movement, $at); + + $took = $movement->arrives_at->getTimestampMs() - $movement->sent_at->getTimestampMs(); + $home = $movement->origin_id; + $movement->update([ + 'type' => Movement::TRADE_RETURN, + 'origin_id' => $this->village->id, + 'target_id' => $home, + 'cargo' => null, + 'sent_at' => $at, + 'arrives_at' => $at->addMilliseconds($took), + 'visible_at' => $at, + ]); + $this->schedule($movement, $home, $movement->arrives_at); + Push::queue($this->village->id, $home); + } + + /** Both players hear of a delivery between them; one player's own villages write nothing. */ + private function report(Movement $movement, CarbonImmutable $at): void + { + if ($this->village->player_id === $movement->player_id) { + return; + } + $origin = Village::with('player')->find($movement->origin_id); + $payload = [ + 'from' => Rally::summary($origin), + 'to' => Rally::summary($this->village), + 'cargo' => $movement->cargo, + 'offer' => $movement->offer, + ]; + Report::write($this->village->player_id, Report::TRADE, $payload, $at); + Report::write($movement->player_id, Report::TRADE, $payload, $at); + } + + // Trade routes + + /** + * A shipment repeated every $every real seconds, the first $every from now. + * + * @param array $amounts + */ + public function createRoute(Village $target, array $amounts, int $every, CarbonImmutable $now): TradeRoute + { + $this->requireMarket(); + $this->checkTarget($target); + $cargo = $this->rules->cargo($amounts); + if (array_sum($cargo) <= 0) { + throw new GameRuleViolation('nothing', 'Send at least one resource.'); + } + $this->rules->checkEvery($every); + if (TradeRoute::where('village_id', $this->village->id)->count() >= $this->rules->maxRoutes()) { + throw new GameRuleViolation('max_routes', 'This village runs as many routes as it can.'); + } + $route = TradeRoute::create([ + 'village_id' => $this->village->id, + 'target_id' => $target->id, + 'target_player_id' => $target->player_id, + ...$cargo, + 'every' => $every, + 'next_at' => $now->addSeconds($every), + ]); + $this->planRoute($route); + + return $route; + } + + /** + * Change a route's amounts, interval or pause. A new interval or a resume plans the + * next run that far from now; resuming accepts the target's owner as it is now. + * + * @param array{wood?: int|null, clay?: int|null, iron?: int|null, every?: int|null, paused?: bool|null} $changes + */ + public function updateRoute(int $routeId, array $changes, CarbonImmutable $now): void + { + $route = $this->route($routeId); + $amounts = $route->amounts(); + foreach (TradeRules::CARGO as $resource) { + if (isset($changes[$resource])) { + $amounts[$resource] = $changes[$resource]; + } + } + $cargo = $this->rules->cargo($amounts); + if (array_sum($cargo) <= 0) { + throw new GameRuleViolation('nothing', 'Send at least one resource.'); + } + $every = $changes['every'] ?? $route->every; + $this->rules->checkEvery($every); + $replan = $every !== $route->every; + $route->fill([...$cargo, 'every' => $every]); + + $paused = $changes['paused'] ?? $route->paused; + if ($paused && ! $route->paused) { + $route->fill(['paused' => true, 'paused_reason' => null]); + } elseif (! $paused && $route->paused) { + $target = Village::find($route->target_id); + if (! $target || $target->player_id === null) { + throw new GameRuleViolation('barbarian', 'Barbarian villages don\'t trade.'); + } + $route->fill(['paused' => false, 'paused_reason' => null, 'target_player_id' => $target->player_id]); + $replan = true; + } + + if ($route->paused) { + self::dropRouteEvents($route->id); + $route->save(); + + return; + } + if ($replan) { + $route->next_at = $now->addSeconds($route->every); + } + $route->save(); + if ($replan) { + $this->planRoute($route); + } + } + + public function deleteRoute(int $routeId): void + { + $route = $this->route($routeId); + self::dropRouteEvents($route->id); + $route->delete(); + } + + /** + * The trade.route handler: send what the stock and the free merchants allow, then plan + * the next run `every` seconds after this one. A target with another owner than when + * the route was made pauses it instead. Runs once per event row: a route moved to + * another time or paused meanwhile ignores the old event. + */ + public function runRoute(GameEvent $event): void + { + $at = $event->fire_at; + $route = TradeRoute::whereKey($event->subject_id)->lockForUpdate()->first(); + if (! $route || $route->village_id !== $this->village->id || $route->paused + || $route->next_at->getTimestampMs() !== $at->getTimestampMs() || $this->village->world->ended_at) { + return; + } + $target = Village::find($route->target_id); + if (! $target || $target->player_id !== $route->target_player_id) { + $route->update(['paused' => true, 'paused_reason' => TradeRoute::OWNER_CHANGED]); + Push::queue($this->village->id); + + return; + } + + $this->sim->settle($at); + $free = $this->building() ? $this->free() : 0; + $cargo = $this->rules->routeCargo($route->amounts(), $this->village->resources(), $free); + if (array_sum($cargo) > 0) { + $this->sim->pay($cargo); + $this->dispatch($this->village, $target, $cargo, $this->rules->needed(array_sum($cargo)), $at, $route->id); + } + // An empty run is recorded too, so the player sees the route found nothing to send. + $route->fill(['last_sent_at' => $at, 'last_cargo' => $cargo, 'next_at' => $at->addSeconds($route->every)])->save(); + $this->planRoute($route); + } + + /** + * What a village loses with its owner on the market: its open offers with the goods + * they reserved, and its routes. Its trades under way go with its other commands + * (Nobility::release); trades coming to it still arrive. + */ + public static function release(Village $village): void + { + TradeOffer::where('village_id', $village->id)->delete(); + foreach (TradeRoute::where('village_id', $village->id)->pluck('id') as $id) { + self::dropRouteEvents($id); + } + TradeRoute::where('village_id', $village->id)->delete(); + } + + private function route(int $routeId): TradeRoute + { + $route = TradeRoute::whereKey($routeId)->lockForUpdate()->first(); + if (! $route || $route->village_id !== $this->village->id) { + throw new GameRuleViolation('not_found', 'No such route.'); + } + + return $route; + } + + private function planRoute(TradeRoute $route): void + { + self::dropRouteEvents($route->id); + GameEvent::create([ + 'world_id' => $this->village->world_id, + 'village_id' => $route->village_id, + 'type' => GameEvent::TRADE_ROUTE, + 'subject_id' => $route->id, + 'fire_at' => $route->next_at, + ]); + } + + private static function dropRouteEvents(int $routeId): void + { + GameEvent::where('type', GameEvent::TRADE_ROUTE)->where('subject_id', $routeId)->whereNull('processed_at')->delete(); + } + + /** + * Merchants leave $from for $to with this cargo. Their arrival is an event on the + * target, and the target sees them from the start. + * + * @param array{wood: int, clay: int, iron: int} $cargo + */ + private function dispatch(Village $from, Village $to, array $cargo, int $merchants, CarbonImmutable $at, ?int $routeId = null, bool $offer = false): Movement + { + $seconds = $this->rules->seconds(TravelTime::distance($from->x, $from->y, $to->x, $to->y)); + $movement = Movement::create([ + 'world_id' => $from->world_id, + 'player_id' => $from->player_id, + 'type' => Movement::TRADE, + // Merchants have one pace; the column wants a mode. + 'mode' => (new TravelTime($this->sim->config()))->defaultMode(), + 'origin_id' => $from->id, + 'target_id' => $to->id, + 'units' => [], + 'cargo' => $cargo, + 'merchants' => $merchants, + 'route_id' => $routeId, + 'offer' => $offer, + 'sent_at' => $at, + 'arrives_at' => $at->addSeconds($seconds), + 'visible_at' => $at, + ]); + $this->schedule($movement, $to->id, $movement->arrives_at); + Push::queue($to->id); + + return $movement; + } + + private function schedule(Movement $movement, int $villageId, CarbonImmutable $at): void + { + GameEvent::create([ + 'world_id' => $movement->world_id, + 'village_id' => $villageId, + 'type' => GameEvent::MOVEMENT_ARRIVES, + 'subject_id' => $movement->id, + 'fire_at' => $at, + ]); + } +} diff --git a/app/Engine/Nobility.php b/app/Engine/Nobility.php index 576ddae..34e0430 100644 --- a/app/Engine/Nobility.php +++ b/app/Engine/Nobility.php @@ -104,10 +104,12 @@ final class Nobility $village->levy_until = null; $village->starving_since = null; Hospital::clear($village); + // Its offers (with the goods they reserved) and its trade routes. + Market::release($village); - // The old owner's commands from here and troops on their way home here. - $lost = Movement::where(fn ($q) => $q->where('origin_id', $village->id)->whereIn('type', [Movement::ATTACK, Movement::SUPPORT])) - ->orWhere(fn ($q) => $q->where('target_id', $village->id)->where('type', Movement::RETURN)) + // The old owner's commands and merchants from here, and troops and merchants on their way home here. + $lost = Movement::where(fn ($q) => $q->where('origin_id', $village->id)->whereIn('type', [Movement::ATTACK, Movement::SUPPORT, Movement::TRADE])) + ->orWhere(fn ($q) => $q->where('target_id', $village->id)->whereIn('type', [Movement::RETURN, Movement::TRADE_RETURN])) ->get(); foreach ($lost as $movement) { GameEvent::whereIn('type', [GameEvent::MOVEMENT_ARRIVES, GameEvent::MOVEMENT_SPOTTED]) diff --git a/app/Engine/Rally.php b/app/Engine/Rally.php index 33f5b5c..7051080 100644 --- a/app/Engine/Rally.php +++ b/app/Engine/Rally.php @@ -203,7 +203,7 @@ final class Rally 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) { + if (! $movement || $movement->origin_id !== $this->village->id || ! in_array($movement->type, [Movement::ATTACK, Movement::SUPPORT], true)) { throw new GameRuleViolation('not_found', 'No such command.'); } if ($now->greaterThan($movement->sent_at->addSeconds($this->cancelWindow())) || ! $movement->arrives_at->greaterThan($now)) { @@ -276,6 +276,7 @@ final class Rally Movement::ATTACK => $this->battle($movement, $at), Movement::SUPPORT => $this->station($movement, $at), Movement::RETURN => $this->homecoming($movement), + Movement::TRADE, Movement::TRADE_RETURN => Market::of($this->village, $this->sim)->arrive($movement, $at), }; } diff --git a/app/Models/GameEvent.php b/app/Models/GameEvent.php index 7f32fcb..9b8d57b 100644 --- a/app/Models/GameEvent.php +++ b/app/Models/GameEvent.php @@ -38,6 +38,9 @@ class GameEvent extends Model // The owner calls support back: village_id is the host, subject_id the support's home village. public const SUPPORT_RECALLED = 'support.recalled'; + // A trade route sends its next shipment: village_id is where it starts, subject_id the route. + public const TRADE_ROUTE = 'trade.route'; + protected $guarded = []; protected $dateFormat = 'Y-m-d H:i:s.v'; diff --git a/app/Models/Movement.php b/app/Models/Movement.php index 1788842..c8a245a 100644 --- a/app/Models/Movement.php +++ b/app/Models/Movement.php @@ -14,6 +14,14 @@ class Movement extends Model public const RETURN = 'return'; + // Merchants with cargo on their way to another village, and empty on their way home. + public const TRADE = 'trade'; + + public const TRADE_RETURN = 'trade_return'; + + /** Merchants, not troops: they never fight and stay out of the rally lists, the map and the noble slots. */ + public const TRADES = [self::TRADE, self::TRADE_RETURN]; + protected $guarded = []; protected $dateFormat = 'Y-m-d H:i:s.v'; @@ -24,6 +32,9 @@ class Movement extends Model 'units' => 'array', 'cargo' => 'array', 'rng_seed' => 'integer', + 'merchants' => 'integer', + 'route_id' => 'integer', + 'offer' => 'boolean', 'sent_at' => 'immutable_datetime', 'arrives_at' => 'immutable_datetime', 'visible_at' => 'immutable_datetime', @@ -43,6 +54,6 @@ class Movement extends Model /** 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; + return in_array($this->type, [self::RETURN, self::TRADE_RETURN], true) ? $this->target_id : $this->origin_id; } } diff --git a/app/Models/Report.php b/app/Models/Report.php index d63d82e..67a63bf 100644 --- a/app/Models/Report.php +++ b/app/Models/Report.php @@ -14,6 +14,9 @@ class Report extends Model public const SUPPORT = 'support'; + // Merchants delivered resources between two players' villages. + public const TRADE = 'trade'; + protected $guarded = []; protected $dateFormat = 'Y-m-d H:i:s.v'; diff --git a/app/Models/TradeOffer.php b/app/Models/TradeOffer.php new file mode 100644 index 0000000..a4a2596 --- /dev/null +++ b/app/Models/TradeOffer.php @@ -0,0 +1,30 @@ + 'integer', + 'want_amount' => 'integer', + 'count' => 'integer', + 'merchants' => 'integer', + ]; + } + + public function village(): BelongsTo + { + return $this->belongsTo(Village::class); + } +} diff --git a/app/Models/TradeRoute.php b/app/Models/TradeRoute.php new file mode 100644 index 0000000..ec31328 --- /dev/null +++ b/app/Models/TradeRoute.php @@ -0,0 +1,46 @@ + 'integer', + 'clay' => 'integer', + 'iron' => 'integer', + 'every' => 'integer', + 'paused' => 'boolean', + 'next_at' => 'immutable_datetime', + 'last_sent_at' => 'immutable_datetime', + 'last_cargo' => 'array', + ]; + } + + public function village(): BelongsTo + { + return $this->belongsTo(Village::class); + } + + public function target(): BelongsTo + { + return $this->belongsTo(Village::class, 'target_id'); + } + + /** @return array{wood: int, clay: int, iron: int} */ + public function amounts(): array + { + return ['wood' => $this->wood, 'clay' => $this->clay, 'iron' => $this->iron]; + } +} diff --git a/app/Presenters/MarketPresenter.php b/app/Presenters/MarketPresenter.php new file mode 100644 index 0000000..1add1f2 --- /dev/null +++ b/app/Presenters/MarketPresenter.php @@ -0,0 +1,119 @@ +building(); + if (! $building) { + return null; + } + $merchants = $market->merchants(); + + return [ + 'building_id' => $building->id, + 'level' => $building->level, + 'merchants' => $merchants, + 'free' => TradeRules::free($merchants, $market->busy()), + 'carry' => $market->rules()->carry(), + ]; + } + + public static function present(Village $village, CarbonImmutable $now): array + { + $sim = Simulation::of($village); + $market = Market::of($village, $sim); + $rules = $market->rules(); + $building = $market->building(); + $config = $sim->config(); + $id = $village->id; + + $merchants = $market->merchants(); + $busy = $building ? $market->busy() : 0; + + return [ + 'server_time' => self::iso($now), + 'market' => $building ? [ + 'building_id' => $building->id, + 'level' => $building->level, + 'merchants' => $merchants, + 'free' => TradeRules::free($merchants, $busy), + 'busy' => $busy, + 'carry' => $rules->carry(), + // At this world's speed, like the rest of the payload's durations. + 'minutes_per_field' => round($rules->minutesPerField() / ($config->speed() * $config->get('movement.unit_speed', 1.0)), 4), + 'resources' => $rules->resources(), + 'max_ratio' => $rules->maxRatio(), + 'route' => ['min_every' => $rules->minEvery(), 'max_every' => $rules->maxEvery(), 'max_routes' => $rules->maxRoutes()], + ] : null, + // out: this village's merchants on the way there; back: on their way home; in: + // anyone's merchants coming here with cargo. + 'trades' => Movement::with(['origin.player', 'target.player']) + ->where(fn ($q) => $q + ->where(fn ($q) => $q->where('origin_id', $id)->where('type', Movement::TRADE)) + ->orWhere(fn ($q) => $q->where('target_id', $id)->whereIn('type', Movement::TRADES))) + ->orderBy('arrives_at')->orderBy('id') + ->get() + ->map(fn (Movement $m) => [ + 'id' => $m->id, + 'kind' => $m->type === Movement::TRADE_RETURN ? 'back' : ($m->origin_id === $id ? 'out' : 'in'), + 'from' => Rally::summary($m->origin), + 'to' => Rally::summary($m->target), + 'cargo' => $m->cargo, + 'merchants' => $m->merchants, + 'sent_at' => self::iso($m->sent_at), + 'arrives_at' => self::iso($m->arrives_at), + 'route_id' => $m->route_id, + 'offer' => $m->offer, + ])->values()->all(), + 'offers' => TradeOffer::where('village_id', $id)->orderBy('id')->get() + ->map(fn (TradeOffer $o) => [ + 'id' => $o->id, + 'give' => ['resource' => $o->give_resource, 'amount' => $o->give_amount], + 'want' => ['resource' => $o->want_resource, 'amount' => $o->want_amount], + 'count' => $o->count, + // Per unit of count. + 'merchants' => $o->merchants, + 'created_at' => self::iso($o->created_at), + ])->values()->all(), + 'routes' => TradeRoute::with('target.player')->where('village_id', $id)->orderBy('id')->get() + ->map(fn (TradeRoute $r) => [ + 'id' => $r->id, + 'to' => Rally::summary($r->target), + 'resources' => $r->amounts(), + 'every' => $r->every, + 'next_at' => self::iso($r->next_at), + 'paused' => $r->paused, + 'paused_reason' => $r->paused_reason, + 'last_sent_at' => $r->last_sent_at ? self::iso($r->last_sent_at) : null, + 'last_cargo' => $r->last_cargo, + ])->values()->all(), + ]; + } + + public static function iso(DateTimeInterface $at): string + { + return CarbonImmutable::instance($at)->utc()->format('Y-m-d\TH:i:s.v\Z'); + } +} diff --git a/app/Presenters/RallyPresenter.php b/app/Presenters/RallyPresenter.php index 6192dc5..cf04226 100644 --- a/app/Presenters/RallyPresenter.php +++ b/app/Presenters/RallyPresenter.php @@ -22,6 +22,7 @@ final class RallyPresenter $window = Rally::of($village)->cancelWindow(); return Movement::with(['origin.player', 'target.player']) + ->whereNotIn('type', Movement::TRADES) ->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)) diff --git a/app/Presenters/VillagePresenter.php b/app/Presenters/VillagePresenter.php index 7473e9f..0f0e6c7 100644 --- a/app/Presenters/VillagePresenter.php +++ b/app/Presenters/VillagePresenter.php @@ -77,6 +77,7 @@ final class VillagePresenter 'movements' => RallyPresenter::movements($village, $now), 'support' => RallyPresenter::support($village), 'rally' => RallyPresenter::rally($village, $now), + 'market' => MarketPresenter::summary($village, $sim), 'loyalty' => (int) floor(Nobility::of($village)->loyalty($village, $now)), 'conquest' => self::conquest($village), // The player's villages in this world, for the switcher. diff --git a/app/Websocket/Controllers/MarketController.php b/app/Websocket/Controllers/MarketController.php new file mode 100644 index 0000000..11012a0 --- /dev/null +++ b/app/Websocket/Controllers/MarketController.php @@ -0,0 +1,108 @@ +market(fn ($user, $id) => app(ShowMarket::class)($user, $id)); + } + + public function preview() + { + return $this->play(fn () => app(PlanTrade::class)(auth()->user(), (int) request('village_id'), (int) request('x'), (int) request('y'))); + } + + public function offers() + { + return $this->play(fn () => app(ListOffers::class)( + auth()->user(), + (int) request('village_id'), + request('give') ? (string) request('give') : null, + request('want') ? (string) request('want') : null, + )); + } + + public function send() + { + return $this->market(fn ($user, $id) => app(MarketDeals::class)->send($user, $id, (int) request('x'), (int) request('y'), $this->amounts())); + } + + public function offer() + { + $give = (array) request('give', []); + $want = (array) request('want', []); + + return $this->market(fn ($user, $id) => app(MarketDeals::class)->offer( + $user, + $id, + (string) ($give['resource'] ?? ''), + (int) ($give['amount'] ?? 0), + (string) ($want['resource'] ?? ''), + (int) ($want['amount'] ?? 0), + (int) request('count', 1), + )); + } + + public function cancelOffer() + { + return $this->market(fn ($user, $id) => app(MarketDeals::class)->cancelOffer($user, $id, (int) request('offer_id'))); + } + + public function accept() + { + return $this->market(fn ($user, $id) => app(MarketDeals::class)->accept($user, $id, (int) request('offer_id'), (int) request('count', 1))); + } + + public function routeCreate() + { + return $this->market(fn ($user, $id) => app(MarketRoutes::class)->create($user, $id, (int) request('x'), (int) request('y'), $this->amounts(), (int) request('every'))); + } + + public function routeUpdate() + { + $changes = []; + foreach (['wood', 'clay', 'iron', 'every'] as $key) { + $changes[$key] = request($key) === null ? null : (int) request($key); + } + $changes['paused'] = request('paused') === null ? null : filter_var(request('paused'), FILTER_VALIDATE_BOOLEAN); + + return $this->market(fn ($user, $id) => app(MarketRoutes::class)->update($user, $id, (int) request('route_id'), $changes)); + } + + public function routeDelete() + { + return $this->market(fn ($user, $id) => app(MarketRoutes::class)->delete($user, $id, (int) request('route_id'))); + } + + /** @return array{wood: int, clay: int, iron: int} */ + private function amounts(): array + { + return ['wood' => (int) request('wood', 0), 'clay' => (int) request('clay', 0), 'iron' => (int) request('iron', 0)]; + } + + /** Runs a market intent and answers with the market as it is afterwards. */ + private function market(Closure $action) + { + return $this->play(fn () => MarketPresenter::present($action(auth()->user(), (int) request('village_id')), now()->toImmutable())); + } +} diff --git a/database/migrations/2026_11_03_120000_create_market.php b/database/migrations/2026_11_03_120000_create_market.php new file mode 100644 index 0000000..b1c6bdf --- /dev/null +++ b/database/migrations/2026_11_03_120000_create_market.php @@ -0,0 +1,67 @@ +unsignedInteger('merchants')->default(0); + // The trade route that sent them, if one did (no foreign key: the trip outlives a deleted route). + $table->unsignedBigInteger('route_id')->nullable(); + // Sent for an accepted offer. + $table->boolean('offer')->default(false); + }); + + // An open offer: count times give_amount of give_resource for want_amount of + // want_resource. The resources and merchants for the open count are reserved. + Schema::create('trade_offers', function (Blueprint $table) { + $table->id(); + $table->foreignId('world_id')->constrained()->cascadeOnDelete(); + $table->foreignId('village_id')->constrained()->cascadeOnDelete(); + $table->string('give_resource', 8); + $table->unsignedInteger('give_amount'); + $table->string('want_resource', 8); + $table->unsignedInteger('want_amount'); + $table->unsignedInteger('count'); + // Reserved per unit of count: ceil(give_amount / carry) when it was made. + $table->unsignedInteger('merchants'); + $table->timestamps(); + $table->index(['world_id', 'give_resource', 'want_resource']); + }); + + // A shipment repeated every `every` real seconds; a trade.route event at next_at sends it. + Schema::create('trade_routes', function (Blueprint $table) { + $table->id(); + $table->foreignId('village_id')->constrained()->cascadeOnDelete(); + $table->foreignId('target_id')->constrained('villages')->cascadeOnDelete(); + // The target's owner when the route was made; another owner pauses the route. No + // foreign key, so a deleted player still counts as a change. + $table->unsignedBigInteger('target_player_id')->nullable(); + $table->unsignedInteger('wood')->default(0); + $table->unsignedInteger('clay')->default(0); + $table->unsignedInteger('iron')->default(0); + $table->unsignedInteger('every'); + $table->dateTime('next_at', 3); + $table->boolean('paused')->default(false); + $table->string('paused_reason', 32)->nullable(); + $table->dateTime('last_sent_at', 3)->nullable(); + $table->json('last_cargo')->nullable(); + $table->timestamps(); + }); + } + + public function down(): void + { + Schema::dropIfExists('trade_routes'); + Schema::dropIfExists('trade_offers'); + Schema::table('movements', function (Blueprint $table) { + $table->dropColumn(['merchants', 'route_id', 'offer']); + }); + } +};