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

45 lines
1.6 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 1 if its building space is free. Pays up front. */
final class QueueBuild extends VillageAction
{
public function __invoke(User $user, int $villageId, string $type): Village
{
return $this->mutate($user, $villageId, function (Simulation $sim, Village $village, CarbonImmutable $now) use ($type) {
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.');
}
if (! $sim->spaceFits($type)) {
throw new GameRuleViolation('no_space', 'Not enough building space.');
}
$cost = $rules->cost($type, 1, $sim->instanceIndex($type));
$sim->pay($cost);
$sim->enqueue([
'building_id' => null,
'type' => $type,
'action' => BuildOrder::BUILD,
'target_level' => 1,
'cost' => $cost,
], $now);
});
}
}