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

83 lines
3.0 KiB
PHP
Raw Normal View History

<?php
namespace App\Actions;
use App\Engine\VillageFactory;
use App\Game\Map\BarbarianGrowth;
use App\Game\Map\Frontier;
use App\Models\GameEvent;
use App\Models\Village;
use App\Models\World;
/**
* Barbarian villages come with the players, as in Die Stämme: each joining player brings
* `barbarians.per_join` of them on average, here placed within a few fields of the new
* village so even a small world has something to loot from the start. They then grow
* by themselves (BarbarianGrowth).
*/
final class SpawnBarbarians
{
private const BUILDINGS = ['headquarters', 'storage', 'farm', 'timber_camp', 'clay_pit', 'iron_mine'];
public function __construct(private readonly VillageFactory $villages) {}
/**
* Barbarian villages around a new player's village, each with its first growth step.
*
* @param array<string, bool> $taken updated with the new villages
* @return list<Village>
*/
public function around(World $world, Village $village, array &$taken): array
{
$config = $world->gameConfig();
$frontier = new Frontier($config);
$maxLevel = $config->get('world.map.barbarians.max_level', 3);
$created = [];
for ($n = $frontier->barbariansPerJoin(VillageFactory::random(...)); $n > 0; $n--) {
$spot = $frontier->near($village->x, $village->y, $taken, VillageFactory::random(...));
if (! $spot) {
break;
}
$taken["{$spot[0]}|{$spot[1]}"] = false;
$levels = [];
foreach (self::BUILDINGS as $type) {
$levels[$type] = mt_rand(1, $maxLevel);
}
$barbarian = $this->villages->create($world, null, 'Barbarian village', $spot[0], $spot[1], $levels);
$this->scheduleFirstGrowth($world, $barbarian);
$created[] = $barbarian;
}
return $created;
}
/**
* 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
{
$waiting = GameEvent::where('type', GameEvent::BARBARIAN_GROWS)->whereNull('processed_at')->select('village_id');
$villages = $world->villages()->whereNull('player_id')->whereNotIn('id', $waiting)->get();
foreach ($villages as $village) {
$this->scheduleFirstGrowth($world, $village);
}
return $villages->count();
}
/** The first growth step lands 0.5–1.5 intervals out, so villages don't grow in step. */
private function scheduleFirstGrowth(World $world, Village $village): void
{
$interval = (new BarbarianGrowth($world->gameConfig()))->interval();
GameEvent::create([
'world_id' => $world->id,
'village_id' => $village->id,
'type' => GameEvent::BARBARIAN_GROWS,
'fire_at' => now()->toImmutable()->addSeconds((int) round($interval * (0.5 + VillageFactory::random()))),
]);
}
}