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; a copy hides at its instance share. */ public function hidden(): float { $rules = $this->sim->rules(); return $this->village->buildings->sum(fn (Building $b) => $rules->hides($b->type, $b->level) * $this->sim->share($b)); } /** * Who defends the village: every unit standing in it, support included, and the * levied villagers as `militia`. * * @return array */ public function defense(): array { $defense = []; foreach ($this->village->troops as $stack) { if ($stack->count > 0) { $defense[$stack->unit] = ($defense[$stack->unit] ?? 0) + $stack->count; } } if ($this->village->militia > 0) { $defense['militia'] = (int) $this->village->militia; } return $defense; } /** When beginner protection ends for this player: real seconds, on every world speed. */ public function protectedUntil(Player $player): CarbonImmutable { $seconds = $this->sim->config()->get('combat.beginner_protection', 0); // From joining, and again from a restart after losing every village. $since = $player->protected_since ?? $player->created_at->toImmutable(); return $since->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); $conquest = Nobility::of($this->village)->rules(); if ($conquest->maxDistance() > 0 && array_intersect_key($units, array_flip($conquest->nobleUnits())) && $plan['distance'] > $conquest->maxDistance()) { throw new GameRuleViolation('too_far', 'Noblemen don\'t march that far.'); } $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 || ! 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)) { 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); // Home on the same line at the same pace: as if it had left the target as long ago // as it still had to go, so a straight line from sent_at to arrives_at puts it where // it turned round. $elapsed = $now->getTimestampMs() - $movement->sent_at->getTimestampMs(); $left = $movement->arrives_at->getTimestampMs() - $now->getTimestampMs(); $movement->update([ 'type' => Movement::RETURN, 'origin_id' => $movement->target_id, 'target_id' => $this->village->id, 'catapult_target' => null, 'sent_at' => $now->subMilliseconds($left), '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), Movement::TRADE, Movement::TRADE_RETURN => Market::of($this->village, $this->sim)->arrive($movement, $at), }; } private function battle(Movement $movement, CarbonImmutable $at): void { $config = $this->sim->config(); // Raiders are as strong as their camp is when they arrive; a beaten camp's band scatters. $raid = $movement->player_id === null; if ($raid) { $units = Raiders::of($this->village, $this->sim)->muster($movement); if (! $units) { $this->scatter($movement, $at); return; } $movement->units = $units; } $combat = new CombatResolver($config); $stacks = $this->village->troops->filter(fn (UnitStack $s) => $s->count > 0); $defense = $this->defense(); $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)); // Raiders (no player) attack at full strength. $morale = $combat->morale($defenderPoints, $movement->player_id ? (int) Village::where('player_id', $movement->player_id)->sum('points') : 0); $night = $combat->night($at); // A military village's defenders fight harder. $fort = 1 + $this->sim->specialisation()->defenseBonus($this->sim->role()); // Scouts meet the defending scouts first and never fight; the rest of the army does. $isScout = fn (string $unit) => (bool) $config->get("units.$unit.scout", false); $scouts = array_filter($movement->units, fn (int $n, string $unit) => $isScout($unit), ARRAY_FILTER_USE_BOTH); $army = array_diff_key($movement->units, $scouts); $watchers = array_sum(array_filter($defense, fn (int $n, string $unit) => $isScout($unit), ARRAY_FILTER_USE_BOTH)); [$through, $scoutsLost] = $combat->scout(array_sum($scouts), $watchers); $battle = $army ? $combat->fight($army, $defense, $wall?->level ?? 0, $morale, $luck, $night * $fort) : null; $won = $battle ? $battle->attackerWon : $through; // What each home village had standing here, for its part of the opponents defeated. $defeated = new Defeated($config); $standing = []; foreach ($stacks as $stack) { $standing[$stack->home_village_id] = ($standing[$stack->home_village_id] ?? 0) + $defeated->weight([$stack->unit => $stack->count]); } if (isset($defense['militia'])) { $standing[$this->village->id] = ($standing[$this->village->id] ?? 0) + $defeated->weight(['militia' => $defense['militia']]); } // Defenders fall in every stack alike, support included: the volley's share, then // the melee's share of the rest, rounded per stack. $defenseLost = []; $defenseShot = []; $ownLost = []; $supporters = []; foreach ($stacks as $stack) { if ($stack->home_village_id !== $this->village->id) { $supporters[$stack->home_village_id] = true; } $group = [$stack->unit => $stack->count]; $dead = $battle ? $battle->defenseDead($group)[$stack->unit] : 0; $defenseLost[$stack->unit] = ($defenseLost[$stack->unit] ?? 0) + $dead; $defenseShot[$stack->unit] = ($defenseShot[$stack->unit] ?? 0) + ($battle ? $battle->defenseVolleyDead($group)[$stack->unit] : 0); if ($stack->home_village_id === $this->village->id && $dead > 0) { $ownLost[$stack->unit] = $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 ? $battle->defenseDead(['militia' => $defense['militia']])['militia'] : 0; $defenseShot['militia'] = $battle ? $battle->defenseVolleyDead(['militia' => $defense['militia']])['militia'] : 0; $this->village->militia -= $defenseLost['militia']; if ($this->village->militia <= 0) { Military::of($this->village, $this->sim)->endLevy($at); } } $damaged = false; if ($wall && $battle && $battle->wallAfter < $wall->level) { $this->damage($wall, $battle->wallAfter, $at); $damaged = true; } $attackLost = [ ...($battle ? $battle->attackDead($army) : []), ...Battle::dead($scouts, $scouts ? $scoutsLost / array_sum($scouts) : 0.0), ]; Quests::bump($movement->player_id, 'defeated.attack', $defeated->points($defenseLost)); $owners = Village::whereIn('id', array_keys($standing))->pluck('player_id', 'id'); foreach (Defeated::share($defeated->points($attackLost), $standing) as $homeId => $points) { Quests::bump($owners[$homeId] ?? null, 'defeated.defense', $points); } $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; } } } // Surviving noblemen of a won attack lower loyalty; at 0 the village changes hands // if the attacker's coins pay for one more. If not, it holds out at 0. $loyalty = null; $nobility = Nobility::of($this->village); $nobles = array_sum(array_intersect_key($survivors, array_flip($nobility->rules()->nobleUnits()))); if ($battle?->attackerWon && $nobles > 0) { $before = $nobility->loyalty($this->village, $at); $after = $before; for ($i = 0; $i < $nobles; $i++) { $after -= $nobility->rules()->drop(mt_rand() / (mt_getrandmax() + 1)); } $fallen = $after <= 0; $conquered = $fallen && $nobility->canTake($movement->player_id); $this->village->loyalty = $conquered ? $nobility->rules()->afterConquest() : max(0, $after); $this->village->loyalty_at = $at; $loyalty = ['before' => (int) floor($before), 'after' => $fallen ? 0 : (int) floor($after), 'conquered' => $conquered, 'no_coins' => $fallen && ! $conquered]; } $conquered = $loyalty['conquered'] ?? false; // Part of the own fallen come back wounded, unless the village falls with them. $wounded = $conquered ? null : Hospital::of($this->village, $this->sim)->admit($ownLost, $at); $loot = ['wood' => 0, 'clay' => 0, 'iron' => 0]; $capacity = 0; // Conquerors stay, so they carry nothing off. if ($battle?->attackerWon && ! $conquered) { $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(); } // A beaten band leaves its bounty behind. $bounty = null; if ($raid && $battle && ! $battle->attackerWon) { $bounty = (new Raids($config))->bounty($army); $this->sim->refund($bounty); } $origin = Village::with('player')->find($movement->origin_id); $scouted = $through && $scoutsLost < array_sum($scouts); $report = [ 'won' => $won, '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], // Of the lost, the ones the other side's volley killed before the melee. 'volley' => $battle?->volleyed() ? ['attacker' => $battle->attackVolleyDead($movement->units), 'defender' => $defenseShot] : null, // Of the lost, the ones in the defender's hospital, and when they stand again. 'wounded' => $wounded ? ['units' => $wounded->units, 'heals_at' => $wounded->heals_at->utc()->format('Y-m-d\TH:i:s.v\Z')] : null, 'wall' => $wall && $battle ? ['before' => $battle->wallBefore, 'after' => $wall->level] : null, 'building' => $hit, 'loot' => $loot, 'capacity' => $capacity, 'loyalty' => $loyalty, 'raid' => $raid, 'bounty' => $bounty, // What scouts that got through saw, after the battle. 'scouting' => $scouts ? [ 'sent' => array_sum($scouts), 'lost' => $scoutsLost, 'through' => $scouted, 'resources' => $scouted ? array_map(fn (float $n) => (int) floor($n), ['wood' => $this->village->wood, 'clay' => $this->village->clay, 'iron' => $this->village->iron]) : null, 'buildings' => $scouted ? $this->village->buildings->groupBy('type')->map(fn ($b) => $b->pluck('level')->sortDesc()->values()->all())->all() : null, ] : null, ]; // An attacker learns about the defence from survivors of the battle or scouts that got through. $informed = ($battle && array_diff_key($survivors, $scouts)) || $scouted; $seen = $informed ? $report : ['defender' => ['village' => $report['defender']['village'], 'units' => null, 'lost' => null], 'wall' => null] + $report; if (! $informed && $seen['volley']) { $seen['volley']['defender'] = null; } // The hospital stays the defender's business. $seen['wounded'] = null; 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); // A barbarian garrison that lost men starts to regroup. if (! $conquered) { Barbarians::of($this->village, $this->sim)->scheduleRegroup($at); } if ($conquered) { $this->conquer($movement, $survivors, $at); return; } $survivors ? $this->turnBack($movement, $survivors, $loot, $at) : $movement->delete(); } /** A band whose camp was beaten down never arrives; the village hears of it. */ private function scatter(Movement $movement, CarbonImmutable $at): void { $origin = Village::with('player')->find($movement->origin_id); if ($origin) { Report::write($this->village->player_id, Report::DEFENSE, [ 'raid' => true, 'scattered' => true, 'attacker' => ['village' => self::summary($origin), 'units' => null, 'lost' => null], 'defender' => ['village' => self::summary($this->village), 'units' => null, 'lost' => null], ], $at); } $movement->delete(); } /** * The attacker takes the village: one nobleman settles, the other survivors stay as * support from the village they came from. * * @param array $survivors */ private function conquer(Movement $movement, array $survivors, CarbonImmutable $at): void { $nobility = Nobility::of($this->village); // The old owner hears of it right away (the report tells the rest). $old = $this->village->player; if ($old) { $by = Player::find($movement->player_id); Push::lost($old->user_id, ['world_id' => $this->village->world_id, 'village_id' => $this->village->id, 'name' => $this->village->name, 'x' => $this->village->x, 'y' => $this->village->y, 'by' => $by?->name]); } $noble = collect($nobility->rules()->nobleUnits())->first(fn (string $u) => ($survivors[$u] ?? 0) > 0); $survivors[$noble]--; $oldHome = $this->village->troops->filter(fn (UnitStack $s) => $s->home_village_id === $this->village->id); foreach ($oldHome as $stack) { $stack->delete(); } $this->village->setRelation('troops', $this->village->troops->diff($oldHome)->values()); Push::queue(...$nobility->handOver($this->village, $movement->player_id, $at)); $this->put($movement->origin_id, array_filter($survivors)); $movement->delete(); Push::queue($this->village->id); } /** 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); } // Raiders back at their camp stay only as far as its garrison has room. if ($this->village->player_id === null) { Barbarians::of($this->village, $this->sim)->trim(); } $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, on the own tribe and on allies or NAP partners, 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.'); } // Tribe members, allies and NAP partners keep the peace. $relation = Tribes::between($this->village->player, $target->player, $now); if (Diplomacy::protects($relation)) { throw new GameRuleViolation($relation === Diplomacy::TRIBE ? 'own_tribe' : 'pact', 'Your tribes are at peace.'); } 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, ]; } }