game-village-politics-backend/app/Engine/Rally.php

572 lines
25 KiB
PHP
Raw Normal View History

<?php
namespace App\Engine;
use App\Game\Combat\Battle;
use App\Game\Combat\CombatResolver;
use App\Game\Combat\LootCalculator;
use App\Game\GameRuleViolation;
use App\Game\Travel\TravelTime;
use App\Models\Building;
use App\Models\GameEvent;
use App\Models\Movement;
use App\Models\Player;
use App\Models\Report;
use App\Models\UnitStack;
use App\Models\Village;
use Carbon\CarbonImmutable;
/**
* Troops leaving and arriving at one village (architecture.md, "Movements" and "Combat").
* Sending runs with the origin locked; an arrival runs as the target's event with the
* target locked, so a battle sees the village exactly as it is at that moment.
*/
final class Rally
{
private TravelTime $travel;
private function __construct(private readonly Village $village, private readonly Simulation $sim)
{
$this->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<string, int> $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<string, mixed> $units
* @return array<string, int>
*/
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<string, mixed> $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 || $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));
// 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);
// 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) : null;
$won = $battle ? $battle->attackerWon : $through;
// 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 ?? 0.0)[$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 ?? 0.0)['militia'];
$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::dead($army, $battle->attackLoss) : []),
...Battle::dead($scouts, $scouts ? $scoutsLost / array_sum($scouts) : 0.0),
];
$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.
$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));
}
$conquered = $after <= 0;
$this->village->loyalty = $conquered ? $nobility->rules()->afterConquest() : $after;
$this->village->loyalty_at = $at;
$loyalty = ['before' => (int) floor($before), 'after' => $conquered ? 0 : (int) floor($after), 'conquered' => $conquered];
}
$conquered = $loyalty['conquered'] ?? false;
$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();
}
$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],
'wall' => $wall && $battle ? ['before' => $battle->wallBefore, 'after' => $wall->level] : null,
'building' => $hit,
'loot' => $loot,
'capacity' => $capacity,
'loyalty' => $loyalty,
// 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;
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();
}
/**
* The attacker takes the village: one nobleman settles, the other survivors stay as
* support from the village they came from.
*
* @param array<string, int> $survivors
*/
private function conquer(Movement $movement, array $survivors, CarbonImmutable $at): void
{
$nobility = Nobility::of($this->village);
$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<string, int> $units
* @param array<string, int> $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<string, int> $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<string, int> $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,
];
}
}