79 lines
2.9 KiB
PHP
79 lines
2.9 KiB
PHP
<?php
|
|
|
|
namespace App\Actions;
|
|
|
|
use App\Engine\VillageFactory;
|
|
use App\Game\Map\BarbarianGrowth;
|
|
use App\Models\GameEvent;
|
|
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) {}
|
|
|
|
/**
|
|
* Give every barbarian village without one a pending growth event, spread over one
|
|
* interval so they don't all grow at once. Safe to run on every deploy.
|
|
*
|
|
* @return int events scheduled
|
|
*/
|
|
public function scheduleGrowth(World $world): int
|
|
{
|
|
$interval = (new BarbarianGrowth($world->gameConfig()))->interval();
|
|
$waiting = GameEvent::where('type', GameEvent::BARBARIAN_GROWS)->whereNull('processed_at')->select('village_id');
|
|
$villages = $world->villages()->whereNull('player_id')->whereNotIn('id', $waiting)->pluck('id');
|
|
$now = now()->toImmutable();
|
|
foreach ($villages as $id) {
|
|
GameEvent::create([
|
|
'world_id' => $world->id,
|
|
'village_id' => $id,
|
|
'type' => GameEvent::BARBARIAN_GROWS,
|
|
'fire_at' => $now->addSeconds((int) round($interval * (0.5 + mt_rand() / (mt_getrandmax() + 1)))),
|
|
]);
|
|
}
|
|
|
|
return $villages->count();
|
|
}
|
|
|
|
/** @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(1, $config['max_level']);
|
|
}
|
|
$this->villages->create($world, null, 'Barbarian village', $x, $y, $levels);
|
|
$created++;
|
|
}
|
|
|
|
return $created;
|
|
});
|
|
}
|
|
}
|