game-village-politics-backend/app/Actions/QueueBuild.php

54 lines
2.0 KiB
PHP
Raw Normal View History

<?php
namespace App\Actions;
use App\Engine\Simulation;
use App\Game\GameRuleViolation;
use App\Models\BuildOrder;
use App\Models\User;
use App\Models\Village;
use Carbon\CarbonImmutable;
/** Queue a new instance at level 0, at (x, y) or the first free slot. Pays up front. */
final class QueueBuild extends VillageAction
{
public function __invoke(User $user, int $villageId, string $type, ?int $x = null, ?int $y = null): Village
{
return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($type, $x, $y) {
if (! $sim->config()->hasBuilding($type)) {
throw new GameRuleViolation('not_found', "Unknown building type [$type].");
}
$rules = $sim->rules();
$max = $rules->maxPerVillage($type);
if ($max !== null && $sim->instances($type) >= $max) {
throw new GameRuleViolation('max_per_village', 'Only one of these per village.');
}
if (! $sim->meetsRequirements($type)) {
throw new GameRuleViolation('requires', 'Requirements not met.');
}
[$w, $h] = $rules->footprint($type);
$grid = $sim->grid();
if ($w === 0 || $h === 0) {
$at = ['x' => 0, 'y' => 0];
} elseif ($x !== null && $y !== null) {
$at = $grid->fits($w, $h, $x, $y) ? ['x' => $x, 'y' => $y] : throw new GameRuleViolation('no_space', 'That spot is taken.');
} else {
$at = $grid->freeSlot($w, $h) ?? throw new GameRuleViolation('no_space', 'No free space.');
}
$cost = $rules->cost($type, 0, $sim->instanceIndex($type));
$sim->pay($cost);
$sim->enqueue([
'building_id' => null,
'type' => $type,
'action' => BuildOrder::BUILD,
'target_level' => 0,
'x' => $at['x'],
'y' => $at['y'],
'cost' => $cost,
], $now);
});
}
}