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:
1 parent
2e781bbba2
commit
3d394c01d3
22 files changed
+1336
-28
No files matched your search
@@ -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);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user