F6: bilanciamento con i bot su simulate

Banco di prova ripetibile per tarare l'economia (ADR 0025, obiettivi O1–O14
scritti prima della taratura):

- railenterprise-tools balance: semi × difficoltà × bot × anni in parallelo,
  rapporto deterministico (rapporto.txt con gli obiettivi, anni/mesi/prezzi/
  esecuzioni.csv, tempi.txt); simulate --bot <id>.
- Bot giocatore (PlayerBot): l'agente delle IA con le personalità di
  ai.json → bots guida la compagnia del giocatore; pianifica per primo; non
  è salvato né nell'hash, il formato dei salvataggi non cambia.
- Le IA usano la compravendita in proprio (supera ADR 0016 §9) con una regola
  mensile deterministica e parametri in ai.json → trading.
- Agente corretto: un trasformatore è fonte solo con gli input alimentati
  (prima i bot fallivano su linee rimaste senza merce finite le scorte
  iniziali); la linea dei ricambi di una rete nuova esce dal budget iniziale
  se l'utile la ripaga entro planning.partsDeferYears.
- Dati: market.world volumeShare 0,5 → 1,0 ed elasticity 1,0 → 2,5;
  townBonus 1,8 → 3,0, townRoiFactor 0,5 → 0,35.

Matrice predefinita (72 esecuzioni da 12 anni, 533 s): obiettivi da 5 a 9
su 14; livello 2 del bot competente in «Imprenditore» al 4° anno (prima 7°),
nessun fallimento dei bot in «Apprendista» e «Imprenditore», prezzi medi tra
0,77 e 1,42 volte il base (prima 0,38–2,78). Restano aperti O7–O11.

EconomyTests.PriceRisesWhenDemandExceedsSupply: la soglia passa da 1,5 a
1,25 volte in 120 giorni perché il mondo a volume pieno ed elasticità 2,5
assorbe parte dello squilibrio (aumento misurato ~1,36). Accettazioni F2, F4
e F5 invariate e verdi; 222 test verdi.

Refs #47.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-08 16:30:31 +01:00
1 parent 2e781bbba2
commit 3d394c01d3
22 files changed
+1336 -28

No files matched your search

+37
View File
@@ -12,7 +12,14 @@ public sealed class AiFile
public required AiMarketParams Market { get; init; }
/// <summary>Rinnovo dei treni con veicoli superati (F6, ADR 0020).</summary>
public required AiRenewalParams Renewal { get; init; }
/// <summary>Compravendita in proprio delle IA (F6, ADR 0016 §9 e ADR 0025).</summary>
public required AiTradingParams Trading { get; init; }
public required List<AiPersonalityDef> Personalities { get; init; }
/// <summary>
/// Personalità dei «bot giocatore» del banco di bilanciamento (ADR 0025): guidano la compagnia del
/// giocatore con lo stesso agente delle IA; non si assegnano mai alle compagnie IA.
/// </summary>
public required List<AiPersonalityDef> Bots { get; init; }
public required List<string> CompanyNames { get; init; }
public required List<string> Colors { get; init; }
}
@@ -77,6 +84,12 @@ public sealed class AiPlanningParams
public required int PlanningDaySpacing { get; init; }
/// <summary>Candidati falliti ricordati per non riprovarli.</summary>
public required int FailedMemory { get; init; }
/// <summary>
/// Una rete nuova lontana dai ricambi parte senza la sua linea dei ricambi (che si costruisce dopo, con
/// i ricavi) solo se l'utile atteso la ripaga entro questi anni; altrimenti la linea entra subito nel
/// budget (ADR 0025). Zero: sempre subito.
/// </summary>
public required double PartsDeferYears { get; init; }
}
/// <summary>
@@ -94,6 +107,30 @@ public sealed class AiRenewalParams
public required int MaxTrainsPerMonth { get; init; }
}
/// <summary>
/// Compravendita in proprio delle IA (ADR 0016 §9, ADR 0025): una volta al mese, dal livello che la sblocca,
/// l'agente vende la merce dei propri magazzini ai compratori del bacino che pagano almeno
/// <see cref="MinSellPriceShare"/> del prezzo globale e cerca le occasioni migliori: comprare dai produttori
/// (o dagli hub) del bacino di una sua stazione e vendere nella stessa stazione o in una raggiungibile con le
/// sue linee, quando il margine atteso sulla prossima unità supera <see cref="MinMargin"/>. Al più
/// <see cref="MaxTradesPerMonth"/> operazioni da <see cref="MaxUnits"/> unità, con al più
/// <see cref="CashShare"/> della cassa libera oltre <see cref="CashReserveMultiple"/> volte la riserva.
/// </summary>
public sealed class AiTradingParams
{
public required bool Enabled { get; init; }
/// <summary>Margine minimo atteso (vendita − acquisto) / acquisto sulla prossima unità.</summary>
public required double MinMargin { get; init; }
/// <summary>Scarto ammesso sul prezzo della prossima unità: tetto d'acquisto e minimo di vendita.</summary>
public required double PriceSlack { get; init; }
/// <summary>Si vende la merce in magazzino solo a chi paga almeno questa quota del prezzo globale.</summary>
public required double MinSellPriceShare { get; init; }
public required int MaxUnits { get; init; }
public required int MaxTradesPerMonth { get; init; }
public required double CashShare { get; init; }
public required double CashReserveMultiple { get; init; }
}
/// <summary>Comportamento in borsa delle IA (12.1–12.2).</summary>
public sealed class AiMarketParams
{
@@ -273,7 +273,12 @@ public static class DataValidator
RequireKeys("maintenance.json", "depots.stallsBySize", m.Depots.StallsBySize.Keys, SizeKeys, errors);
// --- IA, contratti, regioni
Unique("ai.json", d.Ai.Personalities.Select(p => p.Id), errors);
// personalità delle IA e dei bot giocatore (ADR 0025) in un solo spazio di nomi
Unique("ai.json", d.Ai.Personalities.Select(p => p.Id).Concat(d.Ai.Bots.Select(p => p.Id)), errors);
if (d.Ai.Trading.MinMargin <= 2 * d.Ai.Trading.PriceSlack)
Err("ai.json", "trading.minMargin deve superare il doppio di trading.priceSlack (ogni unità scambiata resta in margine)");
if (d.Ai.Planning.PartsDeferYears < 0)
Err("ai.json", "planning.partsDeferYears non può essere negativo");
Unique("contracts.json", d.Contracts.Templates.Select(t => t.Id), errors);
foreach (var t in d.Contracts.Templates)
{
@@ -27,14 +27,16 @@ internal sealed class AiAgent
private readonly AiPlanningParams _plan;
private readonly AiMarketParams _mk;
private readonly GridPath _path;
// un deposito in esercizio aspetta la sua linea dei ricambi e la cassa non basta ancora: niente reti nuove
private bool _partsPending;
public AiAgent(World w, WorldContext ctx, AiState s, GridPath path)
public AiAgent(World w, WorldContext ctx, AiState s, GridPath path, AiPersonalityDef? personality = null)
{
_w = w;
_ctx = ctx;
_s = s;
_c = w.Company(s.Company);
_p = w.Data.Ai.Personalities.FirstOrDefault(p => p.Id == _c.AiPersonality) ?? w.Data.Ai.Personalities[0];
_p = personality ?? w.Data.Ai.Personalities.FirstOrDefault(p => p.Id == _c.AiPersonality) ?? w.Data.Ai.Personalities[0];
_plan = w.Data.Ai.Planning;
_mk = w.Data.Ai.Market;
_path = path;
@@ -269,7 +271,149 @@ internal sealed class AiAgent
RenewFleet();
StockMarket();
BuyIndustries();
if (!EnsurePartsSupply()) NewProject();
if (!EnsurePartsSupply() && !_partsPending) NewProject();
Trade();
}
// ================================================================== compravendita in proprio (ADR 0016, 0025)
/// <summary>Occasione di compravendita: comprare un bene in una stazione e venderlo lì o in un'altra raggiungibile.</summary>
private readonly record struct Deal(Station From, Station To, int Good, double BuyPrice, double SellPrice, int Units)
{
public double Profit => Units * (SellPrice - BuyPrice);
}
/// <summary>
/// Compravendita in proprio (ADR 0016 §9, ADR 0025), dopo i progetti: le linee hanno la precedenza sulla
/// cassa. Prima vende la merce dei propri magazzini a chi paga almeno trading.minSellPriceShare del prezzo
/// globale; poi, se il livello lo sblocca, valuta per ogni stazione propria e bene in vendita nel bacino la
/// destinazione migliore (la stazione stessa o una raggiungibile sulle proprie linee con i flag delle
/// fermate) e, se il margine della prossima unità supera trading.minMargin, compra con un tetto e vende
/// subito o spedisce. Regola deterministica: occasioni in ordine di utile atteso, poi stazione, bene e
/// destinazione; al più trading.maxTradesPerMonth al mese, una per stazione e bene.
/// </summary>
private void Trade()
{
var t = _w.Data.Ai.Trading;
if (!t.Enabled) return;
var stations = new List<Station>();
foreach (var st in _w.Network.Stations)
{
if (st.Owner == _c.Id && _w.Network.IsAlive(st)) stations.Add(st);
}
if (stations.Count == 0) return;
SellStock(t, stations);
if (t.MaxTradesPerMonth <= 0 || !Tiers.Unlocks(_w, _c).Trading) return;
double budget = Math.Max(0, FreeCash() - Reserve() * t.CashReserveMultiple) * t.CashShare;
if (budget <= 0) return;
var graph = _w.LineGraphs.For(_w, _c.Id);
int[] reserved = TradingMath.ReservedByStation(_w);
var deals = new List<Deal>();
foreach (var from in stations)
{
int freeFrom = TradingMath.FreeSpace(_w, from, reserved[from.Id.Value]);
if (freeFrom <= 0) continue;
for (int g = 0; g < _w.Data.GoodCount; g++)
{
if (_w.Data.Goods[g].Era > _ctx.Year) continue;
var sellers = TradingMath.Sellers(_w, from, g);
if (TradingMath.CheapestSeller(_w, sellers, g, out double buy) is null || buy <= 0) continue;
int available = 0;
foreach (var x in sellers) available += x.Limit;
int affordable = (int)Math.Min(int.MaxValue, budget / (buy * (1 + t.PriceSlack)));
int cap = Math.Min(Math.Min(t.MaxUnits, available), Math.Min(freeFrom, affordable));
if (cap <= 0) continue;
Consider(deals, t, from, from, g, buy, cap);
var reach = graph.From(from.Id, LineGraph.GoodCargo(g), stopFlags: true);
if (reach.Count == 0) continue;
var keys = new List<int>(reach.Keys);
keys.Sort();
foreach (int k in keys)
{
var to = _w.Network.Stations[k];
if (to.Id == from.Id || to.Owner != _c.Id || !_w.Network.IsAlive(to)) continue;
int freeTo = TradingMath.FreeSpace(_w, to, reserved[k]);
if (freeTo > 0) Consider(deals, t, from, to, g, buy, Math.Min(cap, freeTo));
}
}
}
if (deals.Count == 0) return;
deals.Sort((a, b) =>
a.Profit != b.Profit ? b.Profit.CompareTo(a.Profit)
: a.From.Id.Value != b.From.Id.Value ? a.From.Id.Value.CompareTo(b.From.Id.Value)
: a.Good != b.Good ? a.Good.CompareTo(b.Good)
: a.To.Id.Value.CompareTo(b.To.Id.Value));
int done = 0;
var used = new List<(int Station, int Good)>();
foreach (var d in deals)
{
if (done >= t.MaxTradesPerMonth) break;
if (used.Contains((d.From.Id.Value, d.Good))) continue;
used.Add((d.From.Id.Value, d.Good));
string good = _w.Data.Goods[d.Good].Id;
long maxPrice = (long)Math.Ceiling(d.BuyPrice * (1 + t.PriceSlack));
if (FreeCash() < maxPrice) break;
int units = d.Units;
if (d.To.Id == d.From.Id)
{
// un affare precedente può aver riempito un compratore comune a due stazioni vicine
int room = 0;
foreach (var b in TradingMath.Buyers(_w, d.From, d.Good))
{
if (b.Kind == TradePartyKind.Industry || d.From.Hubs.Count == 0) room += b.Limit;
}
units = Math.Min(units, room);
if (units <= 0) continue;
}
int before = d.From.StockOf(d.Good);
if (!Do(new BuyGoodsCommand(d.From.Id, good, units, new Money(maxPrice))).Ok) continue;
int bought = d.From.StockOf(d.Good) - before;
if (bought <= 0) continue;
done++;
if (d.To.Id == d.From.Id)
Do(new SellGoodsCommand(d.From.Id, good, bought, new Money((long)Math.Floor(d.SellPrice * (1 - t.PriceSlack)))));
else
Do(new ShipGoodsCommand(d.From.Id, d.To.Id, good, bought));
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: COMMERCIO {bought} {good} a {d.From.Name} ({d.BuyPrice / 100:0.00}) → {d.To.Name} ({d.SellPrice / 100:0.00})");
}
}
/// <summary>Aggiunge l'occasione se i compratori della destinazione pagano la prossima unità con il margine minimo.</summary>
private void Consider(List<Deal> deals, AiTradingParams t, Station from, Station to, int good, double buy, int cap)
{
var buyers = TradingMath.Buyers(_w, to, good);
// nello stesso bacino un hub che vende consuma la stessa capacità mensile con cui comprerebbe:
// si rivende solo alle industrie
if (to.Id == from.Id && from.Hubs.Count > 0) buyers = buyers.Where(b => b.Kind == TradePartyKind.Industry).ToList();
if (TradingMath.BestBuyer(_w, buyers, good, out double sell) is null) return;
if ((sell - buy) / buy < t.MinMargin) return;
int room = 0;
foreach (var b in buyers) room += b.Limit;
int units = Math.Min(cap, room);
if (units > 0) deals.Add(new Deal(from, to, good, buy, sell, units));
}
/// <summary>Vende la merce dei magazzini propri ai compratori del bacino che pagano almeno la quota minima del prezzo globale.</summary>
private void SellStock(AiTradingParams t, List<Station> stations)
{
foreach (var st in stations)
{
if (st.StockTotal <= 0) continue;
for (int g = 0; g < _w.Data.GoodCount; g++)
{
int stock = st.StockOf(g);
if (stock <= 0) continue;
double floor = _w.Market.GlobalPrice[g] * t.MinSellPriceShare;
var buyers = TradingMath.Buyers(_w, st, g);
if (TradingMath.BestBuyer(_w, buyers, g, out double price) is null || price < Math.Ceiling(floor)) continue;
// compratori con il magazzino pieno: si riprova il mese dopo invece di farsi rifiutare il comando
int room = 0;
foreach (var b in buyers) room += b.Limit;
if (room <= 0) continue;
Do(new SellGoodsCommand(st.Id, _w.Data.Goods[g].Id, Math.Min(stock, room), new Money((long)Math.Ceiling(floor))));
}
}
}
// ================================================================== ricambi (10.2)
@@ -334,7 +478,11 @@ internal sealed class AiAgent
continue;
}
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: linea dei ricambi per {depot.Name}: {km:0.0} km, capitale {new Money(proposal.Capital)} (budget {new Money(budget)})");
if (proposal.Capital > budget) return false;
if (proposal.Capital > budget)
{
_partsPending = true;
return false;
}
Execute(proposal, depot.Id);
return true;
}
@@ -632,6 +780,8 @@ internal sealed class AiAgent
public Vec2? DepotPos { get; init; }
public DepotId ExistingDepot { get; init; } = DepotId.None;
public required long Capital { get; init; }
/// <summary>Parte del capitale spesa dopo, con i ricavi della linea: la linea dei ricambi del deposito (ADR 0025).</summary>
public long DeferredCapital { get; init; }
public required double Revenue { get; init; }
public required double Costs { get; init; }
public required int Trains { get; init; }
@@ -671,7 +821,9 @@ internal sealed class AiAgent
continue;
}
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: candidato {cand.Kind} bene {cand.Good} {cand.StraightKm:0.0} km: capitale {new Money(proposal.Capital)}, ricavi {Money.FromCentsRounded(proposal.Revenue)}, costi {Money.FromCentsRounded(proposal.Costs)}, ROI {proposal.Roi * 100:0.0} % (soglia {_p.RoiThreshold * 100:0} %, budget {new Money(budget)})");
if (proposal.Capital > budget) continue;
// la linea dei ricambi entra nel ROI ma si costruisce dopo (EnsurePartsSupply): il deposito parte con la
// sua dotazione di ricambi e la linea si paga con i primi ricavi (ADR 0025)
if (proposal.Capital - proposal.DeferredCapital > budget) continue;
// ROI sul capitale investito, come nella guida (gli interessi sono una scelta di finanziamento)
double roi = proposal.Roi;
bool townProject = cand.SourceIsTown || cand.DestIsTown;
@@ -730,6 +882,8 @@ internal sealed class AiAgent
// impianto fermo per un incidente: non si giudica oggi, se ne riparla a evento finito
if (capacity <= 0) break;
eff = Math.Min(prod.Efficiency / capacity, eff);
// senza chi porta gli input l'impianto vive delle scorte iniziali e poi si ferma (ADR 0025)
if (!InputsFed(prod, servedBy)) eff = 0;
}
double supply = (double)prod.Def.Capacity(prod.Level) * outputs[o].PerCycle / outputs[0].PerCycle * months * eff;
if (supply <= 0) continue;
@@ -932,6 +1086,32 @@ internal sealed class AiAgent
+ Estimators.StationCost(_w, _c, _plan.HubPlatforms) + Estimators.DepotCost(_w, _c, "small") + train;
}
/// <summary>
/// Un'industria di trasformazione ha ogni input alimentato: da una stazione in esercizio che la
/// serve o, con il trasporto locale attivo, da un produttore di quel bene entro il suo raggio
/// (ADR 0025). Le scorte iniziali e la copertura iniziale piena non bastano a stimarne la resa.
/// </summary>
private bool InputsFed(Industry ind, CompanyId[] servedBy)
{
if (servedBy[ind.Id.Value].IsValid) return true;
var lt = _w.Data.Balance.LocalTransport;
foreach (var input in ind.Def.Recipe.Inputs)
{
bool fed = false;
if (lt.Enabled)
{
foreach (var other in _w.Industries)
{
if (other.Closed || other.Level <= 0 || other.Id == ind.Id) continue;
if (!other.Def.Recipe.Outputs.Any(o => o.GoodIndex == input.GoodIndex)) continue;
if (Vec2.Distance(other.Position, ind.Position) <= lt.RadiusKm * 1000) { fed = true; break; }
}
}
if (!fed) return false;
}
return true;
}
/// <summary>
/// Compagnia che serve (o sta per servire) ciascuna industria: una sua stazione ha l'industria nel
/// bacino, anche se la linea è ancora in costruzione (o None).
@@ -984,7 +1164,7 @@ internal sealed class AiAgent
Vec2? depotPos = null;
var existingDepot = supply is { } supplied ? supplied : existingA.IsValid ? ConnectedDepot(existingA) : DepotId.None;
if (!existingDepot.IsValid && existingB.IsValid) existingDepot = ConnectedDepot(existingB);
long capital = plan.TotalCost.Cents;
long capital = plan.TotalCost.Cents, deferred = 0;
bool depotAtB = false;
if (!existingDepot.IsValid)
{
@@ -999,6 +1179,8 @@ internal sealed class AiAgent
long partsCost = PartsLineCost(home, sources);
if (partsCost < 0) return Reject("nessuna linea di ricambi possibile per il deposito");
capital += partsCost;
deferred = partsCost;
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: linea dei ricambi in conto {new Money(partsCost)}");
}
var next = depotAtB ? (polyline.Count > 1 ? polyline[^2] : posA.Value) : (polyline.Count > 1 ? polyline[1] : posB.Value);
depotPos = DepotSite(home, next);
@@ -1012,6 +1194,7 @@ internal sealed class AiAgent
if (!existingB.IsValid) capital += Estimators.StationCost(_w, _c, depotPos is not null && depotAtB ? _plan.HubPlatforms : _plan.Platforms);
double km = plan.LengthM / 1000;
AiSystem.Trace?.Invoke($"{_ctx.Day} {_c.Name}: binari {km:0.0} km: opere {plan.WorksCost}, terreni {plan.LandCost}");
VehicleDef? car = cand.Kind == AiProjectKind.Freight ? Estimators.WagonFor(_w, cand.Good, _ctx.Year) : Estimators.CoachFor(_w, cand.Class, _ctx.Year);
if (car is null) return null;
int cars = supply is not null ? 1 : cand.Kind == AiProjectKind.Freight ? _plan.WagonsPerTrain : Math.Max(1, _plan.WagonsPerTrain / 2);
@@ -1043,11 +1226,13 @@ internal sealed class AiAgent
+ (existingB.IsValid ? 0 : _plan.Platforms * sp.UpkeepPerPlatformPerYear)
+ (existingDepot.IsValid ? 0 : sp.DepotUpkeepPerYear["small"])
+ km * _plan.TrackUpkeepPerKmPerYear;
// la linea dei ricambi si rimanda solo se l'utile della linea la ripaga presto (ADR 0025)
if (deferred > (revenue - costs) * _plan.PartsDeferYears) deferred = 0;
return new Proposal
{
Candidate = cand, PosA = posA.Value, PosB = posB.Value, ExistingA = existingA, ExistingB = existingB,
Polyline = polyline, DepotPos = depotPos, ExistingDepot = existingDepot,
Capital = capital, Revenue = revenue, Costs = costs, Trains = trains, Loco = loco, Car = car, Cars = cars,
Capital = capital, DeferredCapital = deferred, Revenue = revenue, Costs = costs, Trains = trains, Loco = loco, Car = car, Cars = cars,
DepotAtB = depotAtB,
};
}
@@ -1222,7 +1407,7 @@ internal sealed class AiAgent
/// <summary>Apre i cantieri del progetto: stazioni, deposito, binario e raccordo del deposito.</summary>
private void Execute(Proposal p, DepotId? supply = null)
{
long need = p.Capital + Reserve() - FreeCash();
long need = p.Capital - p.DeferredCapital + Reserve() - FreeCash();
if (need > 0 && !Borrow(need)) return;
var cand = p.Candidate;
var stationA = p.ExistingA;
@@ -20,6 +20,14 @@ public sealed class AiSystem : ISimSystem
if (w.AiPaused) return;
EnsureStates(w);
int dpm = w.Calendar.DaysPerMonth;
// il bot del giocatore (ADR 0025) prima delle IA, come un giocatore che costruisce dal primo giorno,
// finché la compagnia è in gioco
if (w.PlayerBot is { } bot && !w.Player.Defunct && w.GameOver is null)
{
var agent = new AiAgent(w, ctx, bot.State, _path, bot.Personality);
agent.Daily();
if (ctx.Day % dpm == bot.State.PlanDay) agent.Monthly();
}
foreach (var s in w.AiStates)
{
var c = w.Company(s.Company);
@@ -0,0 +1,37 @@
using RailEnterprise.Core.Data;
namespace RailEnterprise.Core.Simulation.Ai;
/// <summary>
/// «Bot giocatore» del banco di bilanciamento (ADR 0025): guida la compagnia del giocatore con lo stesso
/// agente delle IA (stessi comandi, stesse validazioni) e una personalità della sezione <c>bots</c> di
/// ai.json. Serve solo agli strumenti e ai test: non entra nel salvataggio né nell'hash di stato
/// (gli effetti dei suoi comandi sì, come quelli di un giocatore), e un mondo caricato non ha bot.
/// </summary>
public sealed class PlayerBot
{
private PlayerBot(AiPersonalityDef personality, AiState state)
{
Personality = personality;
State = state;
}
public AiPersonalityDef Personality { get; }
/// <summary>Stato dell'agente (progetti, comandi emessi e rifiutati), come per le IA.</summary>
public AiState State { get; }
/// <summary>Bot con la personalità indicata (id di ai.json → bots) per la compagnia del giocatore.</summary>
public static PlayerBot Create(World w, string personalityId)
{
var def = w.Data.Ai.Bots.FirstOrDefault(b => b.Id == personalityId)
?? throw new ArgumentException($"Bot sconosciuto: {personalityId} (ai.json → bots: {string.Join(", ", w.Data.Ai.Bots.Select(b => b.Id))})");
// pianifica lo stesso giorno della prima IA ma prima di lei (AiSystem): il giocatore sceglie per primo
var state = new AiState
{
Company = w.Player.Id,
PlanDay = 1 % w.Calendar.DaysPerMonth,
};
return new PlayerBot(def, state);
}
}
@@ -76,6 +76,12 @@ public sealed class World
/// <summary>Agenti IA sospesi (le compagnie IA esistono ma non agiscono): test e scenari didattici.</summary>
public bool AiPaused { get; set; }
/// <summary>
/// Bot che guida la compagnia del giocatore (banco di bilanciamento, ADR 0025), null di norma.
/// Non è salvato: un mondo caricato riparte senza bot.
/// </summary>
public Ai.PlayerBot? PlayerBot { get; set; }
/// <summary>Ultimo anno in cui è entrato un nuovo concorrente (12.1).</summary>
public int LastCompetitorYear { get; set; } = int.MinValue;
@@ -0,0 +1,250 @@
using System.Diagnostics;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Economy;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Core.Simulation.Ai;
using RailEnterprise.Core.Simulation.Systems;
namespace RailEnterprise.Tools.Balance;
/// <summary>Matrice del banco di bilanciamento: semi × difficoltà × bot, per un numero di anni (ADR 0025).</summary>
public sealed record BalanceOptions
{
public required IReadOnlyList<ulong> Seeds { get; init; }
public required IReadOnlyList<string> Difficulties { get; init; }
/// <summary>Id dei bot di ai.json → bots; «nessuno» lascia il giocatore passivo.</summary>
public required IReadOnlyList<string> Bots { get; init; }
public int Years { get; init; } = 12;
public int SizeKm { get; init; } = 128;
/// <summary>Esecuzioni in parallelo (ogni mondo è indipendente: il risultato non cambia).</summary>
public int Threads { get; init; } = Environment.ProcessorCount;
}
/// <summary>Una compagnia alla fine di un anno di gioco.</summary>
public sealed record CompanyYearRow(
int YearIndex, int Year, string Company, bool IsBot, string Personality, int Tier, long NetWorthCents, string Rating,
long CashCents, long DebtCents, long InterestCents, long TransportRevenueCents, long OperatingProfitCents,
int Trains, int RunningLines, bool Bankrupt, bool Defunct);
/// <summary>Un mese di gioco: prezzi, margini dei trasformatori, coperture, popolazione.</summary>
public sealed record MonthRow(
int MonthIndex, double[] PriceRatio, double TransformerMargin, double TransformerNegativeShare,
double SellingTransformerMargin, int SellingTransformers, double Efficiency, double CovInput, double CovWorkers, double CovStaff,
double ServedEfficiency, int ServedIndustries, long Population, double SupersededShare);
/// <summary>Esito di un'esecuzione della matrice.</summary>
public sealed class BalanceRun
{
public required ulong Seed { get; init; }
public required string Difficulty { get; init; }
public required string Bot { get; init; }
public required int Years { get; init; }
public required int StartYear { get; init; }
public List<CompanyYearRow> YearRows { get; } = [];
public List<MonthRow> Months { get; } = [];
/// <summary>Anno di gioco (1 = il primo) in cui il bot ha raggiunto ciascun livello, 0 se mai (indice = livello − 1).</summary>
public int[] BotTierYear { get; set; } = [];
public bool BotBankrupt { get; set; }
public bool GameOver { get; set; }
public int AiCompanies { get; set; }
public int AiBankrupt { get; set; }
/// <summary>IA con almeno una linea in esercizio alla fine del terzo anno.</summary>
public int AiActiveByYear3 { get; set; }
public int BestAiTier { get; set; }
/// <summary>Anno di gioco in cui la prima IA ha raggiunto il livello 2, 0 se mai.</summary>
public int AiTier2Year { get; set; }
/// <summary>Ampliamenti di livello delle industrie e mesi-industria serviti (ritmo di crescita, ADR 0025).</summary>
public int LevelUps { get; set; }
public int ServedIndustryMonths { get; set; }
/// <summary>Livello più alto raggiunto da un'industria.</summary>
public int MaxIndustryLevel { get; set; }
public long PopulationStart { get; set; }
public long PopulationEnd { get; set; }
public long BotCommands { get; set; }
public long BotRejected { get; set; }
public long AiCommands { get; set; }
public long AiRejected { get; set; }
public ulong FinalHash { get; set; }
public bool InvariantsOk { get; set; }
/// <summary>Durata in millisecondi (non entra nel rapporto deterministico).</summary>
public long ElapsedMs { get; set; }
}
/// <summary>
/// Banco di bilanciamento (ADR 0025): per ogni combinazione di seme, difficoltà e bot crea una partita,
/// affida la compagnia del giocatore al bot (lo stesso agente delle IA con una personalità di ai.json →
/// bots) e la fa girare mese per mese, misurando livelli, patrimonio, rating, fallimenti, prezzi rispetto
/// al base, margini dei trasformatori, coperture, città, treni superati e interessi. Le esecuzioni sono
/// indipendenti e si possono fare in parallelo: il rapporto è lo stesso.
/// </summary>
public static class BalanceBench
{
public const string NoBot = "nessuno";
public static List<BalanceRun> Run(GameData data, BalanceOptions o, Action<BalanceRun>? done = null)
{
foreach (string b in o.Bots)
{
if (b != NoBot && data.Ai.Bots.All(x => x.Id != b))
throw new ArgumentException($"Bot sconosciuto: {b} (ai.json → bots: {string.Join(", ", data.Ai.Bots.Select(x => x.Id))}, oppure {NoBot})");
}
foreach (string d in o.Difficulties) data.DifficultyPreset(d);
var plan = new List<(ulong Seed, string Difficulty, string Bot)>();
foreach (string d in o.Difficulties)
{
foreach (string b in o.Bots)
{
foreach (ulong s in o.Seeds) plan.Add((s, d, b));
}
}
var runs = new BalanceRun[plan.Count];
var lockDone = new object();
Parallel.For(0, plan.Count, new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, o.Threads) }, i =>
{
var (seed, difficulty, bot) = plan[i];
runs[i] = RunOne(data, seed, difficulty, bot, o.Years, o.SizeKm);
if (done is not null)
{
lock (lockDone) done(runs[i]);
}
});
return [.. runs];
}
/// <summary>Una partita: crea il mondo, mette il bot e la fa girare mese per mese.</summary>
public static BalanceRun RunOne(GameData data, ulong seed, string difficulty, string bot, int years, int sizeKm)
{
var clock = Stopwatch.StartNew();
var w = WorldFactory.Create(data, new NewGameSettings { Seed = seed, SizeKm = sizeKm, DifficultyId = difficulty });
if (bot != NoBot) w.PlayerBot = PlayerBot.Create(w, bot);
var run = new BalanceRun { Seed = seed, Difficulty = difficulty, Bot = bot, Years = years, StartYear = w.Clock.Year };
run.PopulationStart = w.Towns.Sum(t => (long)t.Population);
int months = w.Calendar.MonthsPerYear;
int dpm = w.Calendar.DaysPerMonth;
var levels = w.Industries.Select(i => i.Level).ToArray();
for (int y = 0; y < years; y++)
{
int year = w.Clock.Year;
for (int m = 0; m < months; m++)
{
w.RunDays(dpm);
var month = SampleMonth(w, y * months + m);
run.Months.Add(month);
run.ServedIndustryMonths += month.ServedIndustries;
for (int i = 0; i < w.Industries.Count; i++)
{
var ind = w.Industries[i];
if (i >= levels.Length) continue; // nate durante la partita: contano dal mese dopo
if (ind.Level > levels[i]) run.LevelUps += ind.Level - levels[i];
levels[i] = ind.Level;
run.MaxIndustryLevel = Math.Max(run.MaxIndustryLevel, ind.Level);
}
if (levels.Length < w.Industries.Count) levels = [.. levels, .. w.Industries.Skip(levels.Length).Select(i => i.Level)];
w.Events.Drain();
}
// il bilancio dell'anno si chiude al primo giorno del successivo: le voci dell'anno sono ancora in YearEntries
SampleYear(w, run, y + 1, year);
if (y + 1 == 3) run.AiActiveByYear3 = w.AiStates.Count(s => !w.Company(s.Company).Defunct && s.Projects.Any(p => p.Stage == AiProjectStage.Running));
}
var player = w.Player;
run.BotTierYear = new int[data.Tiers.Tiers.Count];
for (int t = 1; t < run.BotTierYear.Length; t++)
{
long day = player.TierReachedDay[t];
run.BotTierYear[t] = day < 0 ? 0 : (int)(day / w.Calendar.DaysPerYear) + 1;
}
run.BotTierYear[0] = 1;
run.BotBankrupt = player.Bankrupt;
run.GameOver = w.GameOver is not null;
var ais = w.Companies.Where(c => !c.IsPlayer).ToList();
run.AiCompanies = ais.Count;
run.AiBankrupt = ais.Count(c => c.Bankrupt);
run.BestAiTier = ais.Count == 0 ? 0 : ais.Max(c => c.Tier);
long firstAi2 = ais.Select(c => c.TierReachedDay[1]).Where(d => d >= 0).DefaultIfEmpty(-1).Min();
run.AiTier2Year = firstAi2 < 0 ? 0 : (int)(firstAi2 / w.Calendar.DaysPerYear) + 1;
run.PopulationEnd = w.Towns.Sum(t => (long)t.Population);
if (w.PlayerBot is { } pb)
{
run.BotCommands = pb.State.Issued;
run.BotRejected = pb.State.Rejected;
}
run.AiCommands = w.AiStates.Sum(s => s.Issued);
run.AiRejected = w.AiStates.Sum(s => s.Rejected);
run.FinalHash = w.LastStateHash;
run.InvariantsOk = w.MoneyBalanceSum() == 0 && Enumerable.Range(0, data.GoodCount).All(g => w.TotalStock(g) == w.Goods.ExpectedStock(g));
run.ElapsedMs = clock.ElapsedMilliseconds;
return run;
}
private static MonthRow SampleMonth(World w, int monthIndex)
{
var data = w.Data;
int year = w.Clock.Year;
int dpm = w.Calendar.DaysPerMonth;
var ratio = new double[data.GoodCount];
for (int g = 0; g < data.GoodCount; g++)
{
var def = data.Goods[g];
ratio[g] = def.Era > year ? double.NaN : w.Market.PriceHistory[g].AverageOfLast(dpm) / def.BasePrice;
}
long day = w.Clock.Day;
int window = data.Balance.Growth.QuarterDays;
double margin = 0, servedMargin = 0, eff = 0, ci = 0, cw = 0, cs = 0, servedEff = 0;
int transformers = 0, negative = 0, served = 0, open = 0, servedAll = 0;
foreach (var ind in w.Industries)
{
if (ind.Closed || ind.Level <= 0) continue;
open++;
eff += ind.Efficiency;
ci += ind.CovInput;
cw += ind.CovWorkers;
cs += ind.CovStaff;
bool isServed = ind.ServedWithin(day, window);
if (isServed)
{
servedAll++;
servedEff += ind.Efficiency;
}
if (ind.Def.Kind == IndustryKind.Primary) continue;
transformers++;
margin += ind.Margin;
if (ind.Margin < 0) negative++;
// trasformatori che vendono (ritiri dei vettori o trasporto locale): senza vendite il margine è −1
// per costruzione, qualunque siano i prezzi
if (ind.RevenueEma > 0)
{
served++;
servedMargin += ind.Margin;
}
}
int vehicles = 0, superseded = 0;
foreach (var v in w.Vehicles)
{
if (v.Sold) continue;
vehicles++;
if (Obsolescence.IsSuperseded(v.Def, year)) superseded++;
}
return new MonthRow(
monthIndex, ratio,
transformers == 0 ? 0 : margin / transformers, transformers == 0 ? 0 : (double)negative / transformers,
served == 0 ? double.NaN : servedMargin / served, served,
open == 0 ? 0 : eff / open, open == 0 ? 0 : ci / open, open == 0 ? 0 : cw / open, open == 0 ? 0 : cs / open,
servedAll == 0 ? double.NaN : servedEff / servedAll, servedAll,
w.Towns.Sum(t => (long)t.Population), vehicles == 0 ? 0 : (double)superseded / vehicles);
}
private static void SampleYear(World w, BalanceRun run, int yearIndex, int year)
{
foreach (var c in w.Companies)
{
var state = c.IsPlayer ? w.PlayerBot?.State : w.AiStates.FirstOrDefault(s => s.Company == c.Id);
int lines = state?.Projects.Count(p => p.Stage == AiProjectStage.Running) ?? 0;
int trains = w.Trains.Count(t => !t.Removed && t.Owner == c.Id);
string personality = c.IsPlayer ? w.PlayerBot?.Personality.Id ?? NoBot : c.AiPersonality ?? "";
run.YearRows.Add(new CompanyYearRow(
yearIndex, year, c.Name, c.IsPlayer, personality, c.Tier, c.NetWorth.Cents, c.Rating.ToString(),
c.Cash.Cents, c.Debt.Cents, -c.YearEntries[(int)LedgerEntry.Interest], Company.TransportRevenue(c.YearEntries),
Company.OperatingProfit(c.YearEntries), trains, lines, c.Bankrupt, c.Defunct));
}
}
}
@@ -0,0 +1,328 @@
using System.Globalization;
using System.Text;
using RailEnterprise.Core.Data;
namespace RailEnterprise.Tools.Balance;
/// <summary>Esito di un obiettivo dell'ADR 0025 sulla matrice eseguita.</summary>
public sealed record GoalResult(string Id, string Text, string Measured, bool? Met);
/// <summary>
/// Rapporto del banco di bilanciamento (ADR 0025): testo riassuntivo per difficoltà e bot, obiettivi
/// con l'esito e CSV di dettaglio (separatore «;», decimali con la virgola, come simulate). Il testo e i
/// CSV dipendono solo dalle esecuzioni (non dai tempi): stesso seme, stesso rapporto.
/// </summary>
public static class BalanceReport
{
private static readonly CultureInfo It = CultureInfo.InvariantCulture;
// Obiettivi dell'ADR 0025 (soglie del banco, non della simulazione).
public const string NormalDifficulty = "imprenditore";
public const string EasyDifficulty = "apprendista";
public const string CompetentBot = "bot_competent";
public const string PrudentBot = "bot_prudent";
public const int Tier2FromYear = 3, Tier2ToYear = 6;
public const int EasyTier2ByYear = 5;
public const double PriceLow = 0.7, PriceHigh = 1.6;
public const double PriceMonthsInBand = 0.95;
public const double TransformerPositiveMonths = 0.8;
public const double ServedEfficiencyMin = 0.6;
public const double PopulationGrowthMin = -0.005;
public const double AiActiveShareMin = 0.5;
public const double InterestShareMax = 0.2;
public const double RejectedShareMax = 0.05;
/// <summary>Mediana degli anni (0 = mai, contato come oltre la fine) come testo.</summary>
private static string MedianYear(IEnumerable<int> years, int horizon)
{
var list = years.Select(y => y == 0 ? horizon + 1 : y).OrderBy(y => y).ToList();
if (list.Count == 0) return "–";
int m = list[(list.Count - 1) / 2];
return m > horizon ? "mai" : m.ToString(It);
}
/// <summary>Mediana degli anni con «mai» oltre ogni soglia (un obiettivo mancato non passa per caso).</summary>
private static int MedianYearValue(IEnumerable<int> years, int horizon)
{
var list = years.Select(y => y == 0 ? int.MaxValue : y).OrderBy(y => y).ToList();
return list.Count == 0 ? int.MaxValue : list[(list.Count - 1) / 2];
}
private static long Median(IEnumerable<long> values)
{
var list = values.OrderBy(v => v).ToList();
return list.Count == 0 ? 0 : list[(list.Count - 1) / 2];
}
public static string Dec(double v, string format = "0.###") => double.IsNaN(v) ? "" : v.ToString(format, It).Replace('.', ',');
private static string Pct(double v) => double.IsNaN(v) ? "–" : (v * 100).ToString("0.0", It).Replace('.', ',') + " %";
private static string Lire(long cents) => Core.Common.Money.FromCentsRounded(cents).ToString();
/// <summary>Obiettivi dell'ADR 0025 misurati sulle esecuzioni (null = combinazione non eseguita).</summary>
public static List<GoalResult> Goals(GameData data, List<BalanceRun> runs)
{
var goals = new List<GoalResult>();
int horizon = runs.Count == 0 ? 0 : runs.Max(r => r.Years);
List<BalanceRun> Of(string difficulty, string bot) => runs.Where(r => r.Difficulty == difficulty && r.Bot == bot).ToList();
var normal = Of(NormalDifficulty, CompetentBot);
if (normal.Count > 0)
{
int m = MedianYearValue(normal.Select(r => r.BotTierYear[1]), horizon);
goals.Add(new GoalResult("O1", $"bot competente in «Imprenditore»: livello 2 tra il {Tier2FromYear}° e il {Tier2ToYear}° anno (mediana)",
$"mediana {MedianYear(normal.Select(r => r.BotTierYear[1]), horizon)} (anni: {string.Join(", ", normal.Select(r => r.BotTierYear[1] == 0 ? "mai" : r.BotTierYear[1].ToString(It)))})",
m >= Tier2FromYear && m <= Tier2ToYear));
}
else goals.Add(new GoalResult("O1", "bot competente in «Imprenditore»: livello 2 tra il 3° e il 6° anno", "non eseguito", null));
var easy = Of(EasyDifficulty, CompetentBot);
if (easy.Count > 0)
{
int m = MedianYearValue(easy.Select(r => r.BotTierYear[1]), horizon);
goals.Add(new GoalResult("O2", $"bot competente in «Apprendista»: livello 2 entro il {EasyTier2ByYear}° anno (mediana)",
$"mediana {MedianYear(easy.Select(r => r.BotTierYear[1]), horizon)}", m <= EasyTier2ByYear));
}
else goals.Add(new GoalResult("O2", "bot competente in «Apprendista»: livello 2 entro il 5° anno", "non eseguito", null));
// la difficoltà conta: patrimonio finale mediano del bot competente non crescente con la difficoltà
var order = data.Difficulty.Presets.Select(p => p.Id).Where(d => Of(d, CompetentBot).Count > 0).ToList();
if (order.Count >= 2)
{
var worth = order.Select(d => Median(Of(d, CompetentBot).Select(r => FinalBot(r)?.NetWorthCents ?? 0))).ToList();
bool ok = true;
for (int i = 1; i < worth.Count; i++) ok &= worth[i] <= worth[i - 1];
goals.Add(new GoalResult("O3", "bot competente: patrimonio finale mediano non crescente con la difficoltà",
string.Join(" ≥ ", order.Zip(worth, (d, v) => $"{d} {Lire(v)}")), ok));
}
else goals.Add(new GoalResult("O3", "patrimonio decrescente con la difficoltà", "servono almeno due difficoltà", null));
var prudent = runs.Where(r => r.Bot == PrudentBot && (r.Difficulty == EasyDifficulty || r.Difficulty == NormalDifficulty)).ToList();
goals.Add(prudent.Count == 0
? new GoalResult("O4", "nessun fallimento del bot prudente in «Apprendista» e «Imprenditore»", "non eseguito", null)
: new GoalResult("O4", "nessun fallimento del bot prudente in «Apprendista» e «Imprenditore»",
$"{prudent.Count(r => r.BotBankrupt || r.GameOver)} su {prudent.Count}", prudent.All(r => !r.BotBankrupt && !r.GameOver)));
var competentEasy = runs.Where(r => r.Bot == CompetentBot && (r.Difficulty == EasyDifficulty || r.Difficulty == NormalDifficulty)).ToList();
goals.Add(competentEasy.Count == 0
? new GoalResult("O5", "nessun fallimento del bot competente in «Apprendista» e «Imprenditore»", "non eseguito", null)
: new GoalResult("O5", "nessun fallimento del bot competente in «Apprendista» e «Imprenditore»",
$"{competentEasy.Count(r => r.BotBankrupt || r.GameOver)} su {competentEasy.Count}", competentEasy.All(r => !r.BotBankrupt && !r.GameOver)));
// prezzi
int goods = data.GoodCount;
int inBand = 0, total = 0;
double worstMeanLow = double.MaxValue, worstMeanHigh = double.MinValue;
string lowGood = "", highGood = "";
for (int g = 0; g < goods; g++)
{
var values = runs.SelectMany(r => r.Months).Select(m => m.PriceRatio[g]).Where(v => !double.IsNaN(v)).ToList();
if (values.Count == 0) continue;
total += values.Count;
inBand += values.Count(v => v >= PriceLow && v <= PriceHigh);
double mean = values.Average();
if (mean < worstMeanLow) (worstMeanLow, lowGood) = (mean, data.Goods[g].Id);
if (mean > worstMeanHigh) (worstMeanHigh, highGood) = (mean, data.Goods[g].Id);
}
if (total > 0)
{
goals.Add(new GoalResult("O6", $"media di ogni bene entro {Dec(PriceLow)}–{Dec(PriceHigh)} volte il base",
$"più bassa {lowGood} {Dec(worstMeanLow, "0.00")}, più alta {highGood} {Dec(worstMeanHigh, "0.00")}",
worstMeanLow >= PriceLow && worstMeanHigh <= PriceHigh));
double share = (double)inBand / total;
goals.Add(new GoalResult("O7", $"almeno il {Dec(PriceMonthsInBand * 100)} % dei mesi-bene entro {Dec(PriceLow)}–{Dec(PriceHigh)} volte il base",
Pct(share), share >= PriceMonthsInBand));
}
// margini dei trasformatori che vendono (quelli senza vendite hanno margine −1 per costruzione)
var served = runs.SelectMany(r => r.Months).Where(m => !double.IsNaN(m.SellingTransformerMargin)).ToList();
if (served.Count > 0)
{
double share = (double)served.Count(m => m.SellingTransformerMargin > 0) / served.Count;
goals.Add(new GoalResult("O8", $"margine medio dei trasformatori che vendono positivo in almeno il {Dec(TransformerPositiveMonths * 100)} % dei mesi",
$"{Pct(share)} (margine medio {Dec(served.Average(m => m.SellingTransformerMargin), "0.000")})", share >= TransformerPositiveMonths));
}
else goals.Add(new GoalResult("O8", "margine dei trasformatori che vendono positivo", "nessun trasformatore vende", null));
var servedEff = runs.SelectMany(r => r.Months.Skip(r.Months.Count / 2)).Where(m => !double.IsNaN(m.ServedEfficiency)).ToList();
if (servedEff.Count > 0)
{
double eff = servedEff.Average(m => m.ServedEfficiency);
goals.Add(new GoalResult("O9", $"efficienza media delle industrie servite almeno {Dec(ServedEfficiencyMin)} (seconda metà)", Dec(eff, "0.000"), eff >= ServedEfficiencyMin));
}
var normalAll = runs.Where(r => r.Difficulty == NormalDifficulty && r.Bot != BalanceBench.NoBot).ToList();
if (normalAll.Count > 0)
{
double growth = normalAll.Average(r => AnnualGrowth(r));
goals.Add(new GoalResult("O10", $"popolazione in «Imprenditore» (con bot): crescita media annua almeno {Pct(PopulationGrowthMin)}", Pct(growth), growth >= PopulationGrowthMin));
}
int ais = runs.Sum(r => r.AiCompanies), active = runs.Sum(r => r.AiActiveByYear3);
if (ais > 0)
{
double share = (double)active / ais;
goals.Add(new GoalResult("O11", $"almeno il {Dec(AiActiveShareMin * 100)} % delle IA con una linea in esercizio entro il 3° anno", $"{active} su {ais} ({Pct(share)})", share >= AiActiveShareMin));
}
if (normal.Count > 0)
{
long interest = normal.Sum(r => r.YearRows.Where(y => y.IsBot).Sum(y => y.InterestCents));
long revenue = normal.Sum(r => r.YearRows.Where(y => y.IsBot).Sum(y => y.TransportRevenueCents));
double share = revenue <= 0 ? double.PositiveInfinity : (double)interest / revenue;
goals.Add(new GoalResult("O12", $"bot competente in «Imprenditore»: interessi entro il {Dec(InterestShareMax * 100)} % dei ricavi dei trasporti",
$"{Lire(interest)} su {Lire(revenue)} ({(double.IsInfinity(share) ? "senza ricavi" : Pct(share))})", share <= InterestShareMax));
}
long cmds = runs.Sum(r => r.BotCommands + r.AiCommands), rej = runs.Sum(r => r.BotRejected + r.AiRejected);
if (cmds > 0)
{
double share = (double)rej / cmds;
goals.Add(new GoalResult("O13", $"comandi rifiutati di bot e IA al massimo il {Dec(RejectedShareMax * 100)} % (14.5)", $"{rej} su {cmds} ({Pct(share)})", share <= RejectedShareMax));
}
bool inv = runs.All(r => r.InvariantsOk);
goals.Add(new GoalResult("O14", "invarianti di denaro e merci in ogni esecuzione", inv ? "rispettati" : "ROTTI", inv));
return goals;
}
private static CompanyYearRow? FinalBot(BalanceRun r) => r.YearRows.LastOrDefault(y => y.IsBot);
/// <summary>Crescita media annua composta della popolazione complessiva.</summary>
public static double AnnualGrowth(BalanceRun r) =>
r.PopulationStart <= 0 || r.Years <= 0 ? 0 : Core.Common.DMath.Pow((double)r.PopulationEnd / r.PopulationStart, 1.0 / r.Years) - 1;
/// <summary>Testo del rapporto (deterministico: non contiene tempi).</summary>
public static string Text(GameData data, BalanceOptions o, List<BalanceRun> runs)
{
var sb = new StringBuilder();
sb.AppendLine("Banco di bilanciamento (ADR 0025)");
sb.AppendLine($"semi {string.Join(", ", o.Seeds)}; difficoltà {string.Join(", ", o.Difficulties)}; bot {string.Join(", ", o.Bots)}; {o.Years} anni su {o.SizeKm} km; {runs.Count} esecuzioni");
sb.AppendLine();
sb.AppendLine("Obiettivi");
var goals = Goals(data, runs);
foreach (var g in goals)
sb.AppendLine($" {(g.Met is null ? "–" : g.Met.Value ? "sì" : "NO")} {g.Id} {g.Text}: {g.Measured}");
sb.AppendLine($" raggiunti {goals.Count(g => g.Met == true)} su {goals.Count(g => g.Met is not null)}");
int horizon = o.Years;
foreach (string d in o.Difficulties)
{
foreach (string b in o.Bots)
{
var set = runs.Where(r => r.Difficulty == d && r.Bot == b).ToList();
if (set.Count == 0) continue;
sb.AppendLine();
sb.AppendLine($"[{d} / {b}] {set.Count} semi");
if (b != BalanceBench.NoBot)
{
for (int t = 2; t <= data.Tiers.Tiers.Count; t++)
{
var years = set.Select(r => r.BotTierYear[t - 1]).ToList();
if (years.All(y => y == 0)) continue;
sb.AppendLine($" bot livello {t}: anno mediano {MedianYear(years, horizon)} (semi: {string.Join(", ", years.Select(y => y == 0 ? "mai" : y.ToString(It)))})");
}
var finals = set.Select(FinalBot).Where(x => x is not null).Select(x => x!).ToList();
sb.AppendLine($" bot alla fine: livello {string.Join("/", finals.Select(f => f.Tier))}, patrimonio mediano {Lire(Median(finals.Select(f => f.NetWorthCents)))}, rating {string.Join("/", finals.Select(f => f.Rating))}, treni {string.Join("/", finals.Select(f => f.Trains))}");
sb.AppendLine($" bot fallito: {set.Count(r => r.BotBankrupt)}, fine partita: {set.Count(r => r.GameOver)}; interessi pagati (mediana del totale) {Lire(Median(set.Select(r => r.YearRows.Where(y => y.IsBot).Sum(y => y.InterestCents))))}");
sb.AppendLine($" livello per anno (prima esecuzione): {string.Join(" ", set[0].YearRows.Where(y => y.IsBot).Select(y => y.Tier))}");
}
sb.AppendLine($" IA: {set.Sum(r => r.AiCompanies)} compagnie, fallite {set.Sum(r => r.AiBankrupt)}, attive al 3° anno {set.Sum(r => r.AiActiveByYear3)}, livello massimo {string.Join("/", set.Select(r => r.BestAiTier))}, primo livello 2 di un'IA all'anno {MedianYear(set.Select(r => r.AiTier2Year), horizon)} (mediana)");
var months = set.SelectMany(r => r.Months).ToList();
var served = months.Where(m => !double.IsNaN(m.SellingTransformerMargin)).ToList();
sb.AppendLine($" trasformatori: margine medio {Dec(months.Average(m => m.TransformerMargin), "0.000")} (quota in perdita {Pct(months.Average(m => m.TransformerNegativeShare))}); che vendono {Dec(served.Count == 0 ? double.NaN : served.Average(m => m.SellingTransformerMargin), "0.000")}, mesi positivi {Pct(served.Count == 0 ? double.NaN : (double)served.Count(m => m.SellingTransformerMargin > 0) / served.Count)}");
var se = months.Where(m => !double.IsNaN(m.ServedEfficiency)).ToList();
sb.AppendLine($" coperture medie: input {Dec(months.Average(m => m.CovInput), "0.00")}, lavoratori {Dec(months.Average(m => m.CovWorkers), "0.00")}, personale {Dec(months.Average(m => m.CovStaff), "0.00")}; efficienza {Dec(months.Average(m => m.Efficiency), "0.00")}, servite {Dec(se.Count == 0 ? double.NaN : se.Average(m => m.ServedEfficiency), "0.00")}");
int servedMonths = set.Sum(r => r.ServedIndustryMonths);
sb.AppendLine($" industrie: ampliamenti {set.Sum(r => r.LevelUps)}, per industria servita all'anno {Dec(servedMonths == 0 ? double.NaN : set.Sum(r => r.LevelUps) * 12.0 / servedMonths, "0.00")}, livello massimo {string.Join("/", set.Select(r => r.MaxIndustryLevel))}");
sb.AppendLine($" città: crescita media annua {Pct(set.Average(AnnualGrowth))}; veicoli superati alla fine {Pct(set.Average(r => r.Months[^1].SupersededShare))}");
var prices = new List<string>();
for (int g = 0; g < data.GoodCount; g++)
{
var v = months.Select(m => m.PriceRatio[g]).Where(x => !double.IsNaN(x)).ToList();
if (v.Count == 0) continue;
prices.Add($"{data.Goods[g].Id} {Dec(v.Min(), "0.00")}/{Dec(v.Average(), "0.00")}/{Dec(v.Max(), "0.00")}");
}
sb.AppendLine($" prezzi / base (min/medio/max): {string.Join("; ", prices)}");
}
}
return sb.ToString();
}
/// <summary>Scrive rapporto.txt e i CSV nella cartella indicata.</summary>
public static void Write(string dir, GameData data, BalanceOptions o, List<BalanceRun> runs)
{
Directory.CreateDirectory(dir);
var utf8 = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true);
File.WriteAllText(Path.Combine(dir, "rapporto.txt"), Text(data, o, runs), utf8);
File.WriteAllText(Path.Combine(dir, "anni.csv"), YearsCsv(runs), utf8);
File.WriteAllText(Path.Combine(dir, "mesi.csv"), MonthsCsv(data, runs), utf8);
File.WriteAllText(Path.Combine(dir, "prezzi.csv"), PricesCsv(data, runs), utf8);
File.WriteAllText(Path.Combine(dir, "esecuzioni.csv"), RunsCsv(data, runs), utf8);
}
public static string YearsCsv(List<BalanceRun> runs)
{
var sb = new StringBuilder("seme;difficoltà;bot;anno di gioco;anno;compagnia;bot giocatore;personalità;livello;patrimonio;rating;cassa;debito;interessi;ricavi trasporti;utile operativo;treni;linee;fallita;fuori gioco\n");
foreach (var r in runs)
{
foreach (var y in r.YearRows)
{
sb.AppendLine(string.Join(';', r.Seed.ToString(It), r.Difficulty, r.Bot, y.YearIndex.ToString(It), y.Year.ToString(It), y.Company,
y.IsBot ? "sì" : "no", y.Personality, y.Tier.ToString(It), Dec(y.NetWorthCents / 100.0, "0.00"), y.Rating,
Dec(y.CashCents / 100.0, "0.00"), Dec(y.DebtCents / 100.0, "0.00"), Dec(y.InterestCents / 100.0, "0.00"),
Dec(y.TransportRevenueCents / 100.0, "0.00"), Dec(y.OperatingProfitCents / 100.0, "0.00"),
y.Trains.ToString(It), y.RunningLines.ToString(It), y.Bankrupt ? "sì" : "no", y.Defunct ? "sì" : "no"));
}
}
return sb.ToString();
}
public static string MonthsCsv(GameData data, List<BalanceRun> runs)
{
var sb = new StringBuilder("seme;difficoltà;bot;mese;margine trasformatori;quota in perdita;margine trasformatori che vendono;trasformatori che vendono;efficienza;copertura input;copertura lavoratori;copertura personale;efficienza servite;industrie servite;popolazione;quota superati;");
sb.AppendLine(string.Join(';', data.Goods.Select(g => "prezzo/base " + g.Id)));
foreach (var r in runs)
{
foreach (var m in r.Months)
{
sb.Append(string.Join(';', r.Seed.ToString(It), r.Difficulty, r.Bot, (m.MonthIndex + 1).ToString(It), Dec(m.TransformerMargin), Dec(m.TransformerNegativeShare),
Dec(m.SellingTransformerMargin), m.SellingTransformers.ToString(It), Dec(m.Efficiency), Dec(m.CovInput), Dec(m.CovWorkers), Dec(m.CovStaff),
Dec(m.ServedEfficiency), m.ServedIndustries.ToString(It), m.Population.ToString(It), Dec(m.SupersededShare)));
sb.Append(';');
sb.AppendLine(string.Join(';', m.PriceRatio.Select(v => Dec(v))));
}
}
return sb.ToString();
}
public static string PricesCsv(GameData data, List<BalanceRun> runs)
{
var sb = new StringBuilder("seme;difficoltà;bot;bene;minimo/base;medio/base;massimo/base;mesi fuori 0,7–1,6\n");
foreach (var r in runs)
{
for (int g = 0; g < data.GoodCount; g++)
{
var v = r.Months.Select(m => m.PriceRatio[g]).Where(x => !double.IsNaN(x)).ToList();
if (v.Count == 0) continue;
sb.AppendLine(string.Join(';', r.Seed.ToString(It), r.Difficulty, r.Bot, data.Goods[g].Id, Dec(v.Min()), Dec(v.Average()), Dec(v.Max()),
v.Count(x => x < PriceLow || x > PriceHigh).ToString(It)));
}
}
return sb.ToString();
}
public static string RunsCsv(GameData data, List<BalanceRun> runs)
{
var sb = new StringBuilder("seme;difficoltà;bot;anni;");
sb.Append(string.Join(';', Enumerable.Range(2, data.Tiers.Tiers.Count - 1).Select(t => $"anno livello {t}")));
sb.AppendLine(";bot fallito;fine partita;IA;IA fallite;IA attive al 3° anno;livello massimo IA;anno livello 2 IA;ampliamenti industrie;mesi-industria serviti;livello massimo industrie;popolazione iniziale;popolazione finale;comandi bot;rifiutati bot;comandi IA;rifiutati IA;invarianti;hash finale");
foreach (var r in runs)
{
sb.Append(string.Join(';', r.Seed.ToString(It), r.Difficulty, r.Bot, r.Years.ToString(It)));
sb.Append(';');
sb.Append(string.Join(';', r.BotTierYear.Skip(1).Select(y => y.ToString(It))));
sb.AppendLine(";" + string.Join(';', r.BotBankrupt ? "sì" : "no", r.GameOver ? "sì" : "no", r.AiCompanies.ToString(It), r.AiBankrupt.ToString(It),
r.AiActiveByYear3.ToString(It), r.BestAiTier.ToString(It), r.AiTier2Year.ToString(It), r.LevelUps.ToString(It), r.ServedIndustryMonths.ToString(It), r.MaxIndustryLevel.ToString(It), r.PopulationStart.ToString(It), r.PopulationEnd.ToString(It),
r.BotCommands.ToString(It), r.BotRejected.ToString(It), r.AiCommands.ToString(It), r.AiRejected.ToString(It), r.InvariantsOk ? "ok" : "ROTTI", r.FinalHash.ToString("x16", It)));
}
return sb.ToString();
}
}
@@ -0,0 +1,58 @@
using System.Diagnostics;
using System.Globalization;
using RailEnterprise.Core.Data;
using RailEnterprise.Tools.Balance;
namespace RailEnterprise.Tools.Commands;
/// <summary>
/// balance: banco di bilanciamento con i bot giocatore (ADR 0025). Fa giocare il bot e le IA su
/// semi × difficoltà × bot per N anni e scrive in una cartella il rapporto con gli obiettivi
/// (rapporto.txt) e i CSV di dettaglio (anni, mesi, prezzi, esecuzioni); i tempi vanno in tempi.txt.
/// </summary>
public sealed class BalanceCommand : IToolCommand
{
public string Name => "balance";
public string Usage => "balance [--seeds 1,2,3] [--difficulties apprendista,imprenditore,magnate,ferro_e_sangue] [--bots bot_competent,bot_prudent|nessuno] [--years 12] [--size 128] [--threads n] [--out bilanciamento]";
public int Run(CommandLine args)
{
Console.OutputEncoding = System.Text.Encoding.UTF8;
var data = GameData.LoadDefault();
var o = new BalanceOptions
{
Seeds = List(args.String("seeds", "1,2,3")).Select(s => ulong.Parse(s, CultureInfo.InvariantCulture)).ToList(),
Difficulties = List(args.String("difficulties", string.Join(',', data.Difficulty.Presets.Select(p => p.Id)))),
Bots = List(args.String("bots", "bot_competent,bot_prudent")),
Years = args.Int("years", 12),
SizeKm = args.Int("size", 128),
Threads = args.Int("threads", Environment.ProcessorCount),
};
string output = args.String("out", "bilanciamento");
args.EnsureAllUsed();
var clock = Stopwatch.StartNew();
int total = o.Seeds.Count * o.Difficulties.Count * o.Bots.Count, finished = 0;
Console.WriteLine($"balance: {total} esecuzioni da {o.Years} anni su {o.SizeKm} km, {o.Threads} in parallelo");
var runs = BalanceBench.Run(data, o, r =>
{
finished++;
Console.WriteLine($" [{finished}/{total}] seme {r.Seed} {r.Difficulty} {r.Bot}: {r.ElapsedMs / 1000.0:F1} s, livello 2 del bot all'anno {(r.BotTierYear.Length > 1 && r.BotTierYear[1] > 0 ? r.BotTierYear[1].ToString(CultureInfo.InvariantCulture) : "mai")}{(r.BotBankrupt ? ", FALLITO" : "")}");
});
long wall = clock.ElapsedMilliseconds;
BalanceReport.Write(output, data, o, runs);
long cpu = runs.Sum(r => r.ElapsedMs);
string times = $"tempo totale {wall / 1000.0:F1} s; somma delle esecuzioni {cpu / 1000.0:F1} s; per esecuzione media {cpu / 1000.0 / Math.Max(1, runs.Count):F1} s, massima {runs.Max(r => r.ElapsedMs) / 1000.0:F1} s; {o.Threads} in parallelo\n";
File.WriteAllText(Path.Combine(output, "tempi.txt"), times);
Console.WriteLine();
Console.Write(BalanceReport.Text(data, o, runs));
Console.WriteLine();
Console.Write(times);
Console.WriteLine($"rapporto e CSV in {output}");
return 0;
}
private static List<string> List(string value) =>
value.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToList();
}
@@ -17,7 +17,7 @@ public sealed class SimulateCommand : IToolCommand
{
public string Name => "simulate";
public string Usage => "simulate --seed <n> --years <n> [--size 128] [--difficulty imprenditore] [--scenario <file>] [--out kpi.csv] [--save <file>] [--trace-ai]";
public string Usage => "simulate --seed <n> --years <n> [--size 128] [--difficulty imprenditore] [--scenario <file>] [--out kpi.csv] [--save <file>] [--bot bot_competent] [--trace-ai]";
private static readonly CultureInfo It = CultureInfo.InvariantCulture;
@@ -31,6 +31,7 @@ public sealed class SimulateCommand : IToolCommand
string output = args.String("out", "kpi.csv");
string? savePath = args.String("save");
bool trace = args.Flag("trace-ai");
string? bot = args.String("bot");
args.EnsureAllUsed();
if (trace) Core.Simulation.Ai.AiSystem.Trace = Console.WriteLine;
@@ -41,6 +42,8 @@ public sealed class SimulateCommand : IToolCommand
world = Scenarios.ScenarioLoader.Load(data, scenario).World;
else
world = WorldFactory.Create(data, new NewGameSettings { Seed = seed, SizeKm = size, DifficultyId = difficulty });
// bot giocatore (ADR 0025): guida la compagnia del giocatore con una personalità di ai.json → bots
if (bot is not null) world.PlayerBot = Core.Simulation.Ai.PlayerBot.Create(world, bot);
long createMs = total.ElapsedMilliseconds;
var csv = new StringBuilder();
@@ -95,7 +98,7 @@ public sealed class SimulateCommand : IToolCommand
{
long revenue = Company.TransportRevenue(c.LastYearEntries);
double share = totalCarrier > 0 ? (double)revenue / totalCarrier : 0;
string note = $"{(c.IsPlayer ? "giocatore" : c.AiPersonality)}, rating {c.Rating}, livello {c.Tier}{(c.Bankrupt ? ", bancarotta" : "")}{(c.Merged ? ", fusa" : "")}{AiNote(w, c)}";
string note = $"{(c.IsPlayer ? w.PlayerBot is { } pb ? "giocatore, " + pb.Personality.Id : "giocatore" : c.AiPersonality)}, rating {c.Rating}, livello {c.Tier}{(c.Bankrupt ? ", bancarotta" : "")}{(c.Merged ? ", fusa" : "")}{AiNote(w, c)}";
bool fleet = w.Trains.Any(t => !t.Removed && t.Owner == c.Id && t.Vehicles.Count > 0);
csv.AppendLine(string.Join(';', year.ToString(It), c.Name, "", "", "", "", population.ToString(It), "",
fleet ? Dec(Fleet.FleetCondition(w, c.Id)) : "", "", Dec(c.Cash.Lire), Dec(c.NetWorth.Lire), Dec(share), note));
@@ -105,7 +108,7 @@ public sealed class SimulateCommand : IToolCommand
/// <summary>Diagnostica dell'agente IA: progetti, treni, comandi rifiutati.</summary>
private static string AiNote(World w, Company c)
{
var s = w.AiStates.FirstOrDefault(a => a.Company == c.Id);
var s = c.IsPlayer ? w.PlayerBot?.State : w.AiStates.FirstOrDefault(a => a.Company == c.Id);
if (s is null) return "";
int running = s.Projects.Count(p => p.Stage == Core.Simulation.Ai.AiProjectStage.Running);
int trains = w.Trains.Count(t => !t.Removed && t.Owner == c.Id);
+1
View File
@@ -10,6 +10,7 @@ public static class ToolsProgram
new ValidateDataCommand(),
new GenMapCommand(),
new SimulateCommand(),
new BalanceCommand(),
new ProfileCommand(),
new BenchCommand(),
new SmokeCommand(),