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); }); } }