239 lines
9.0 KiB
PHP
239 lines
9.0 KiB
PHP
<?php
|
|
|
|
namespace App\Engine;
|
|
|
|
use App\Game\GameRuleViolation;
|
|
use App\Game\Military\UnitRules;
|
|
use App\Models\Building;
|
|
use App\Models\GameEvent;
|
|
use App\Models\RecruitOrder;
|
|
use App\Models\UnitStack;
|
|
use App\Models\Village;
|
|
use Carbon\CarbonImmutable;
|
|
|
|
/**
|
|
* Troops and recruiting of one village. Each military building instance runs its own
|
|
* queue; an order's times are fixed when it is queued, so units arrive lazily and
|
|
* settle() moves them into the village whenever it runs.
|
|
*/
|
|
final class Military
|
|
{
|
|
private UnitRules $units;
|
|
|
|
private function __construct(private readonly Village $village, private readonly Simulation $sim)
|
|
{
|
|
$this->units = new UnitRules($sim->config());
|
|
}
|
|
|
|
public static function of(Village $village, ?Simulation $sim = null): self
|
|
{
|
|
return new self($village, $sim ?? Simulation::of($village));
|
|
}
|
|
|
|
public function units(): UnitRules
|
|
{
|
|
return $this->units;
|
|
}
|
|
|
|
/** Move the units trained by $at from their queues into the village. */
|
|
public function settle(CarbonImmutable $at): void
|
|
{
|
|
foreach ($this->village->recruits as $order) {
|
|
$done = $order->doneAt($at);
|
|
if ($done > $order->done) {
|
|
$this->addTroops($order->unit, $done - $order->done);
|
|
$order->done = $done;
|
|
}
|
|
if ($order->done >= $order->count) {
|
|
$this->drop($order);
|
|
} elseif ($order->isDirty()) {
|
|
$order->save();
|
|
}
|
|
}
|
|
}
|
|
|
|
/** @return array<string, int> own units standing at home */
|
|
public function troopsAtHome(): array
|
|
{
|
|
return $this->village->troops
|
|
->where('home_village_id', $this->village->id)
|
|
->mapWithKeys(fn (UnitStack $s) => [$s->unit => $s->count])
|
|
->filter()
|
|
->all();
|
|
}
|
|
|
|
/** @return list<array{type: string, level: int}> */
|
|
public function missingRequirements(string $unit): array
|
|
{
|
|
$missing = [];
|
|
foreach ($this->units->requires($unit) as $type => $level) {
|
|
if (! $this->village->buildings->where('type', $type)->where('level', '>=', $level)->count()) {
|
|
$missing[] = ['type' => $type, 'level' => $level];
|
|
}
|
|
}
|
|
|
|
return $missing;
|
|
}
|
|
|
|
/** Most units of this type the village can pay for and spare villagers for now. */
|
|
public function maxRecruitable(string $unit): int
|
|
{
|
|
$cost = $this->units->cost($unit);
|
|
$byResources = min(array_map(
|
|
fn (string $r) => $cost[$r] > 0 ? (int) floor($this->village->{$r} / $cost[$r]) : PHP_INT_MAX,
|
|
array_keys($cost),
|
|
));
|
|
$byVillagers = (int) floor($this->sim->workforce()->undrafted() / $this->units->upkeep($unit));
|
|
|
|
return max(0, min($byResources, $byVillagers));
|
|
}
|
|
|
|
/** Seconds per unit at this building instance, from its level and staffing. */
|
|
public function secondsPerUnit(Building $building, string $unit): int
|
|
{
|
|
$staffing = $this->sim->staffingFactor($this->sim->workforce()->ratio($building->id));
|
|
|
|
return $this->units->seconds($unit, $building->level, $staffing);
|
|
}
|
|
|
|
/** Queue units at a military building. Pays up front; the villagers stop working at once. */
|
|
public function recruit(Building $building, string $unit, int $count, CarbonImmutable $now): RecruitOrder
|
|
{
|
|
if (! $this->units->exists($unit) || $this->units->building($unit) !== $building->type) {
|
|
throw new GameRuleViolation('not_found', "This building cannot train [$unit].");
|
|
}
|
|
if ($count < 1) {
|
|
throw new GameRuleViolation('count', 'Recruit at least one unit.');
|
|
}
|
|
if ($this->missingRequirements($unit)) {
|
|
throw new GameRuleViolation('requires', 'Requirements not met.');
|
|
}
|
|
if ($count * $this->units->upkeep($unit) > $this->sim->workforce()->undrafted()) {
|
|
throw new GameRuleViolation('villagers', 'Not enough villagers to train that many.');
|
|
}
|
|
$this->sim->pay($this->units->cost($unit, $count));
|
|
|
|
$seconds = $this->secondsPerUnit($building, $unit);
|
|
$last = $this->village->recruits->where('building_id', $building->id)->last();
|
|
$starts = $last && $last->finishes_at->greaterThan($now) ? $last->finishes_at : $now;
|
|
$order = $this->village->recruits()->create([
|
|
'building_id' => $building->id,
|
|
'unit' => $unit,
|
|
'count' => $count,
|
|
'done' => 0,
|
|
'seconds_per_unit' => $seconds,
|
|
'cost' => $this->units->cost($unit),
|
|
'starts_at' => $starts,
|
|
'finishes_at' => $starts->addSeconds($seconds * $count),
|
|
]);
|
|
$this->village->recruits->push($order);
|
|
$this->schedule($order);
|
|
|
|
return $order;
|
|
}
|
|
|
|
/**
|
|
* Cancel what is left of an order with a full refund for the untrained units, and
|
|
* move the later orders at the same building forward.
|
|
*/
|
|
public function cancel(RecruitOrder $order, CarbonImmutable $now): void
|
|
{
|
|
$this->settle($now);
|
|
if (! $this->village->recruits->contains($order)) {
|
|
return;
|
|
}
|
|
$this->sim->refund(array_map(fn (int $n) => $n * ($order->count - $order->done), $order->cost));
|
|
$this->drop($order);
|
|
|
|
// Orders queued after it at this building haven't started yet: they follow on
|
|
// from the one before it, or from now.
|
|
$queue = $this->village->recruits->where('building_id', $order->building_id);
|
|
$before = $queue->where('id', '<', $order->id)->last();
|
|
$from = $before && $before->finishes_at->greaterThan($now) ? $before->finishes_at : $now;
|
|
foreach ($queue->where('id', '>', $order->id) as $later) {
|
|
$later->starts_at = $from;
|
|
$later->finishes_at = $from->addSeconds($later->seconds_per_unit * $later->count);
|
|
$later->save();
|
|
$this->reschedule($later);
|
|
$from = $later->finishes_at;
|
|
}
|
|
}
|
|
|
|
/** Seconds a levy lasts on this world. */
|
|
public function levySeconds(): int
|
|
{
|
|
return max(1, (int) ceil($this->sim->config()->get('economy.levy.duration', 6 * 3600) / $this->sim->config()->speed()));
|
|
}
|
|
|
|
/**
|
|
* Draft villagers as militia. They stop working at once (the caller settled the
|
|
* village to $now) and return on their own when the levy ends.
|
|
*/
|
|
public function levy(int $count, CarbonImmutable $now): void
|
|
{
|
|
if ($this->village->militia > 0) {
|
|
throw new GameRuleViolation('levy_active', 'A levy is already under way.');
|
|
}
|
|
if ($count < 1) {
|
|
throw new GameRuleViolation('count', 'Draft at least one villager.');
|
|
}
|
|
if ($count > $this->sim->workforce()->villagers) {
|
|
throw new GameRuleViolation('villagers', 'Not that many villagers.');
|
|
}
|
|
$this->village->militia = $count;
|
|
$this->village->levy_until = $now->addSeconds($this->levySeconds());
|
|
GameEvent::create([
|
|
'world_id' => $this->village->world_id,
|
|
'village_id' => $this->village->id,
|
|
'type' => GameEvent::LEVY_ENDS,
|
|
'subject_id' => $this->village->id,
|
|
'fire_at' => $this->village->levy_until,
|
|
]);
|
|
}
|
|
|
|
/** Send the militia back to work, on the timer or early; the village is settled to $at first. */
|
|
public function endLevy(CarbonImmutable $at): void
|
|
{
|
|
$this->sim->settle($at);
|
|
$this->village->militia = 0;
|
|
$this->village->levy_until = null;
|
|
GameEvent::where('type', GameEvent::LEVY_ENDS)->where('village_id', $this->village->id)->whereNull('processed_at')->delete();
|
|
}
|
|
|
|
private function addTroops(string $unit, int $count): void
|
|
{
|
|
$stack = $this->village->troops->first(fn (UnitStack $s) => $s->unit === $unit && $s->home_village_id === $this->village->id);
|
|
if ($stack) {
|
|
$stack->increment('count', $count);
|
|
|
|
return;
|
|
}
|
|
$stack = $this->village->troops()->create(['home_village_id' => $this->village->id, 'unit' => $unit, 'count' => $count]);
|
|
$this->village->troops->push($stack);
|
|
}
|
|
|
|
private function drop(RecruitOrder $order): void
|
|
{
|
|
GameEvent::where('type', GameEvent::RECRUIT_FINISHED)->where('subject_id', $order->id)->whereNull('processed_at')->delete();
|
|
$order->delete();
|
|
$this->village->setRelation('recruits', $this->village->recruits->reject(fn (RecruitOrder $o) => $o->is($order))->values());
|
|
}
|
|
|
|
private function schedule(RecruitOrder $order): void
|
|
{
|
|
GameEvent::create([
|
|
'world_id' => $this->village->world_id,
|
|
'village_id' => $this->village->id,
|
|
'type' => GameEvent::RECRUIT_FINISHED,
|
|
'subject_id' => $order->id,
|
|
'fire_at' => $order->finishes_at,
|
|
]);
|
|
}
|
|
|
|
private function reschedule(RecruitOrder $order): void
|
|
{
|
|
GameEvent::where('type', GameEvent::RECRUIT_FINISHED)->where('subject_id', $order->id)->whereNull('processed_at')
|
|
->update(['fire_at' => Engine::stamp($order->finishes_at)]);
|
|
}
|
|
}
|