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

53 lines
1.9 KiB
PHP
Raw Normal View History

<?php
namespace App\Actions;
use App\Engine\VillageFactory;
use App\Models\World;
use Illuminate\Support\Facades\DB;
/**
* Scatters barbarian villages around the map centre, once per world. The RNG is
* seeded from the world's slug, so a world always gets the same layout.
*/
final class SeedBarbarians
{
private const BUILDINGS = ['headquarters', 'storage', 'farm', 'timber_camp', 'clay_pit', 'iron_mine'];
public function __construct(private readonly VillageFactory $villages) {}
/** @return int villages created */
public function __invoke(World $world): int
{
if ($world->villages()->whereNull('player_id')->exists()) {
return 0;
}
$config = $world->gameConfig()->get('world.map.barbarians');
$centre = intdiv($world->gameConfig()->get('world.map.size', 1000), 2);
mt_srand(crc32($world->slug));
return DB::transaction(function () use ($world, $config, $centre) {
$taken = VillageFactory::takenSpots($world);
$created = 0;
for ($tries = 0; $created < $config['count'] && $tries < $config['count'] * 20; $tries++) {
$x = $centre + mt_rand(-$config['radius'], $config['radius']);
$y = $centre + mt_rand(-$config['radius'], $config['radius']);
// Leave the centre ring free for player spawns (even coordinates near the middle).
if (isset($taken["$x|$y"]) || (abs($x - $centre) < 6 && abs($y - $centre) < 6)) {
continue;
}
$taken["$x|$y"] = true;
$levels = [];
foreach (self::BUILDINGS as $type) {
$levels[$type] = mt_rand(0, $config['max_level']);
}
$this->villages->create($world, null, 'Barbarian village', $x, $y, $levels);
$created++;
}
return $created;
});
}
}