game-village-politics-backend/app/Game/Economy/Production.php

72 lines
2.6 KiB
PHP
Raw Normal View History

<?php
namespace App\Game\Economy;
use App\Game\Buildings\BuildingRules;
use App\Game\Buildings\BuildingState;
use App\Game\Buildings\Specialisation;
use App\Game\WorldConfig;
/** Resource rates per hour from the base trickle, buildings and their staffing. */
final class Production
{
public const RESOURCES = ['wood', 'clay', 'iron', 'food'];
private BuildingRules $rules;
private Specialisation $specialisation;
public function __construct(private readonly WorldConfig $config)
{
$this->rules = new BuildingRules($config);
$this->specialisation = new Specialisation($config);
}
/** Output share at staffing ratio r: e^(k·(r−1)). Full is 1, empty about 0.1. */
public function staffingFactor(float $ratio): float
{
return exp($this->config->get('economy.staffing.k', 2.3) * (min(1.0, max(0.0, $ratio)) - 1));
}
/**
* @param float $bonus extra share from the village's role (0.2 = +20%)
* @param float $share the instance's share among its type (BuildingRules::instanceShares)
* @return array{resource: string, per_hour: float}|null
*/
public function output(BuildingState $building, Workforce $workforce, float $bonus = 0.0, float $share = 1.0): ?array
{
$output = $this->rules->output($building->type, $building->level);
if (! $output) {
return null;
}
$output['per_hour'] *= $this->staffingFactor($workforce->ratio($building->id)) * (1 + $bonus) * $share;
return $output;
}
/**
* Net change per hour, with the village role's bonus on its buildings and copies at
* their instance share. Food is farm output minus upkeep, so it can go negative.
*
* @param list<BuildingState> $buildings
* @return array{wood: float, clay: float, iron: float, food: float}
*/
public function rates(array $buildings, Workforce $workforce): array
{
$rates = array_fill_keys(self::RESOURCES, 0.0);
foreach ($this->config->get('economy.base_production', []) as $resource => $perHour) {
$rates[$resource] += $perHour * $this->config->speed();
}
$role = $this->specialisation->role(array_map(fn (BuildingState $b) => $b->type, $buildings));
$shares = $this->rules->instanceShares($buildings);
foreach ($buildings as $b) {
if ($output = $this->output($b, $workforce, $this->specialisation->productionBonus($role, $b->type), $shares[$b->id])) {
$rates[$output['resource']] += $output['per_hour'];
}
}
$rates['food'] -= $workforce->upkeep;
return $rates;
}
}