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

70 lines
2.4 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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%)
* @return array{resource: string, per_hour: float}|null
*/
public function output(BuildingState $building, Workforce $workforce, float $bonus = 0.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);
return $output;
}
/**
* Net change per hour, with the village role's bonus on its buildings. 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));
foreach ($buildings as $b) {
if ($output = $this->output($b, $workforce, $this->specialisation->productionBonus($role, $b->type))) {
$rates[$output['resource']] += $output['per_hour'];
}
}
$rates['food'] -= $workforce->upkeep;
return $rates;
}
}