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