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, ]); } }