game-village-politics-backend/app/Game/Buildings/BuildQueue.php

55 lines
1.6 KiB
PHP
Raw Normal View History

<?php
namespace App\Game\Buildings;
/**
* One queue shared by all builders. A free builder takes the first waiting order
* that no earlier order on the same building instance is still blocking.
*/
final class BuildQueue
{
/**
* @param list<array{id: int, building_id: int|null, builder: int|null}> $orders in queue order
* @return array<int, int> order id => builder slot (1-based) to start now
*/
public static function startable(array $orders, int $builders): array
{
$running = array_filter($orders, fn (array $o) => $o['builder'] !== null);
$busy = array_column($running, 'builder');
$blocked = array_flip(array_filter(array_column($running, 'building_id'), fn ($id) => $id !== null));
$start = [];
foreach ($orders as $o) {
if ($o['builder'] !== null) {
continue;
}
if ($o['building_id'] !== null) {
if (isset($blocked[$o['building_id']])) {
continue;
}
$blocked[$o['building_id']] = true;
}
$slot = self::freeSlot($busy, $builders);
if ($slot === null) {
break;
}
$busy[] = $slot;
$start[$o['id']] = $slot;
}
return $start;
}
/** @param list<int> $busy */
private static function freeSlot(array $busy, int $builders): ?int
{
for ($slot = 1; $slot <= $builders; $slot++) {
if (! in_array($slot, $busy, true)) {
return $slot;
}
}
return null;
}
}