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

78 lines
2.6 KiB
PHP

<?php
namespace App\Engine;
use App\Game\GameRuleViolation;
use App\Models\Player;
use App\Models\Village;
use App\Models\World;
/** Creates villages for players and barbarians, and finds free map coordinates for them. */
final class VillageFactory
{
/**
* A village with the given building levels (type => level, one instance each),
* start resources and the matching points.
*
* @param array<string, int> $levels
*/
public function create(World $world, ?Player $player, string $name, int $x, int $y, array $levels): Village
{
$config = $world->gameConfig();
$village = Village::create([
'world_id' => $world->id,
'player_id' => $player?->id,
'name' => $name,
'x' => $x,
'y' => $y,
'space' => $config->get('world.village.space'),
...$config->get('world.village.start_resources'),
'resources_at' => now()->toImmutable(),
]);
foreach ($levels as $type => $level) {
$village->buildings()->create(['type' => $type, 'level' => $level]);
}
$village->update(['points' => Simulation::of($village)->points()]);
return $village;
}
/**
* First free coordinate on square rings around the map centre, every second field
* so villages don't touch. Stand-in for M2's spawn ring that moves outward as the
* world fills.
*
* @param array<string, true> $taken "x|y" => true, updated with the result
* @return array{0: int, 1: int}
*/
public static function freeSpot(World $world, array &$taken): array
{
$size = $world->gameConfig()->get('world.map.size', 1000);
$centre = intdiv($size, 2);
for ($r = 0; $r <= $centre / 2; $r++) {
for ($dy = -$r; $dy <= $r; $dy++) {
for ($dx = -$r; $dx <= $r; $dx++) {
if (max(abs($dx), abs($dy)) !== $r) {
continue;
}
$x = $centre + $dx * 2;
$y = $centre + $dy * 2;
if (! isset($taken["$x|$y"])) {
$taken["$x|$y"] = true;
return [$x, $y];
}
}
}
}
throw new GameRuleViolation('world_full', 'This world is full.');
}
/** @return array<string, true> */
public static function takenSpots(World $world): array
{
return $world->villages()->get(['x', 'y'])->mapWithKeys(fn (Village $v) => ["{$v->x}|{$v->y}" => true])->all();
}
}