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
@@ -9,7 +9,7 @@ La specifica vincolante è `docs/GUIDA.md`; lo stato dei lavori è in `docs/STAT
|
||||
scripts/build.sh # check-nuget + build Release della soluzione
|
||||
scripts/test.sh [filtri] # build + validate-data + tutti i test (--skip-slow, --serial)
|
||||
dotnet run --project tests/RailEnterprise.Tests -- --list
|
||||
dotnet run --project src/RailEnterprise.Tools -- <comando> # validate-data, genmap, profile, simulate, bench, replay
|
||||
dotnet run --project src/RailEnterprise.Tools -- <comando> # validate-data, genmap, profile, simulate, balance, bench, replay
|
||||
```
|
||||
|
||||
## Regole non negoziabili
|
||||
|
||||
+18
-3
@@ -36,11 +36,12 @@
|
||||
"commuterCoverage": 0.6,
|
||||
"hubShare": 0.25,
|
||||
"noPartsFactor": 0.5,
|
||||
"townBonus": 1.8,
|
||||
"townRoiFactor": 0.5,
|
||||
"townBonus": 3.0,
|
||||
"townRoiFactor": 0.35,
|
||||
"repayCashMonths": 12,
|
||||
"planningDaySpacing": 7,
|
||||
"failedMemory": 64
|
||||
"failedMemory": 64,
|
||||
"partsDeferYears": 3.0
|
||||
},
|
||||
"market": {
|
||||
"founderAcceptPremium": 0.4,
|
||||
@@ -63,11 +64,25 @@
|
||||
"cashReserveMultiple": 2.0,
|
||||
"maxTrainsPerMonth": 1
|
||||
},
|
||||
"trading": {
|
||||
"enabled": true,
|
||||
"minMargin": 0.25,
|
||||
"priceSlack": 0.06,
|
||||
"minSellPriceShare": 0.9,
|
||||
"maxUnits": 150,
|
||||
"maxTradesPerMonth": 2,
|
||||
"cashShare": 0.15,
|
||||
"cashReserveMultiple": 2.0
|
||||
},
|
||||
"personalities": [
|
||||
{ "id": "expansive", "name_it": "Espansiva", "roiThreshold": 0.08, "loanShareOfCredit": 0.8, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "standard" },
|
||||
{ "id": "prudent", "name_it": "Prudente", "roiThreshold": 0.15, "loanShareOfCredit": 0.3, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "standard" },
|
||||
{ "id": "predatory", "name_it": "Predatoria", "roiThreshold": 0.10, "loanShareOfCredit": 0.6, "targetsPlayer": true, "buysShares": true, "maintenancePolicy": "standard" }
|
||||
],
|
||||
"bots": [
|
||||
{ "id": "bot_competent", "name_it": "Bot competente", "roiThreshold": 0.10, "loanShareOfCredit": 0.6, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "standard" },
|
||||
{ "id": "bot_prudent", "name_it": "Bot prudente", "roiThreshold": 0.18, "loanShareOfCredit": 0.25, "targetsPlayer": false, "buysShares": false, "maintenancePolicy": "thorough" }
|
||||
],
|
||||
"companyNames": [
|
||||
"Strade Ferrate del Nord", "Società Ferroviaria Adriatica", "Compagnia delle Valli", "Ferrovie Meridionali",
|
||||
"Società Anonima delle Strade Ferrate", "Ferrovia Alta Valle", "Compagnia Lombardo-Veneta", "Rete del Litorale"
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@
|
||||
"maxPriceFactor": 3.0,
|
||||
"ratioMin": 0.2,
|
||||
"ratioMax": 5.0,
|
||||
"world": { "amplitude": 0.12, "periodYears": 6, "volumeShare": 0.5, "baselinePerDay": 4.0, "elasticity": 1.0,
|
||||
"world": { "amplitude": 0.12, "periodYears": 6, "volumeShare": 1.0, "baselinePerDay": 4.0, "elasticity": 2.5,
|
||||
"shockChancePerYear": 0.25, "shockMin": 0.08, "shockMax": 0.30, "shockDecayDays": 150, "priceFloor": 0.05 },
|
||||
"historyDays": 720,
|
||||
"outlook": { "historyMonths": 24, "changeDays": 30, "forecastMonths": 4, "forecastBandPerMonth": 0.03, "sellPlaces": 3, "eventThreshold": 0.05 }
|
||||
|
||||
+105
-1
@@ -74,6 +74,57 @@
|
||||
},
|
||||
"minItems": 3
|
||||
},
|
||||
"bots": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"id": {
|
||||
"type": "string",
|
||||
"pattern": "^[a-z][a-z0-9_]*$"
|
||||
},
|
||||
"name_it": {
|
||||
"type": "string",
|
||||
"minLength": 1
|
||||
},
|
||||
"roiThreshold": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"loanShareOfCredit": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"targetsPlayer": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"buysShares": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"maintenancePolicy": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"economy",
|
||||
"standard",
|
||||
"thorough"
|
||||
]
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"id",
|
||||
"name_it",
|
||||
"roiThreshold",
|
||||
"loanShareOfCredit",
|
||||
"targetsPlayer",
|
||||
"buysShares",
|
||||
"maintenancePolicy"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"minItems": 1
|
||||
},
|
||||
"companyNames": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
@@ -119,6 +170,57 @@
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"trading": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"enabled": {
|
||||
"type": "boolean"
|
||||
},
|
||||
"minMargin": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 5
|
||||
},
|
||||
"priceSlack": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"minSellPriceShare": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 3
|
||||
},
|
||||
"maxUnits": {
|
||||
"type": "integer",
|
||||
"minimum": 1
|
||||
},
|
||||
"maxTradesPerMonth": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"cashShare": {
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 1
|
||||
},
|
||||
"cashReserveMultiple": {
|
||||
"type": "number",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"enabled",
|
||||
"minMargin",
|
||||
"priceSlack",
|
||||
"minSellPriceShare",
|
||||
"maxUnits",
|
||||
"maxTradesPerMonth",
|
||||
"cashShare",
|
||||
"cashReserveMultiple"
|
||||
],
|
||||
"additionalProperties": false
|
||||
},
|
||||
"market": {
|
||||
"type": "object",
|
||||
"additionalProperties": {
|
||||
@@ -137,7 +239,9 @@
|
||||
"companyNames",
|
||||
"colors",
|
||||
"market",
|
||||
"renewal"
|
||||
"renewal",
|
||||
"trading",
|
||||
"bots"
|
||||
],
|
||||
"additionalProperties": false
|
||||
}
|
||||
@@ -8,7 +8,7 @@ Questo documento descrive come è fatto il codice. Va aggiornato a ogni fase: le
|
||||
RailEnterprise.Core (net10.0; net8.0) simulazione deterministica, dati, mappa, economia, rete, salvataggi
|
||||
RailEnterprise.Protocol (net10.0; net8.0) frame binari, messaggi, SpanWriter/SpanReader → Core
|
||||
RailEnterprise.Server (net10.0, Web SDK) Kestrel, WebSocket, GameLoop, API HTTP, autosave → Core, Protocol
|
||||
RailEnterprise.Tools (net10.0) railenterprise-tools: validate-data, genmap, profile, simulate, bench, smoke, replay → Core, Protocol
|
||||
RailEnterprise.Tools (net10.0) railenterprise-tools: validate-data, genmap, profile, simulate, balance, bench, smoke, replay → Core, Protocol
|
||||
RailEnterprise.Tests (net10.0) harness interno, test di unità, scenari → Core, Protocol, Server
|
||||
client/RailEnterprise.Client (Godot .NET) rendering, input, UI; anteprime con Core → Core, Protocol
|
||||
```
|
||||
@@ -70,7 +70,7 @@ Sistemi implementati (F1–F5), nella loro posizione:
|
||||
- Ogni sistema implementa `ISimSystem.Step(WorldContext ctx)`; i sistemi giornalieri o mensili controllano `ctx.IsNewDay` / `ctx.IsNewMonth` e ritornano subito negli altri tick: nei 239 tick su 240 lavora solo `TrainSystem`.
|
||||
- `SystemPipeline.Profile` misura tempo e allocazioni per sistema (usato da `bench`).
|
||||
- `WorldContext` espone il mondo, i dati e il calendario; gli eventi in uscita (notifiche, notizie) vanno in `World.Events`, che il server svuota.
|
||||
- I comandi arrivano in una coda; il server la riempie dai socket e il sistema `Commands` la drena a inizio tick. Le IA eseguono i loro comandi direttamente con `CommandProcessor` dal sistema `AiAgents` (stesse validazioni, esito immediato, numeri di sequenza ≥ 0x80000000, non registrati per il replay: le IA si rigiocano da sole). Per il replay si registrano `(tick, comando)` in `World.CommandLog`.
|
||||
- I comandi arrivano in una coda; il server la riempie dai socket e il sistema `Commands` la drena a inizio tick. Le IA eseguono i loro comandi direttamente con `CommandProcessor` dal sistema `AiAgents` (stesse validazioni, esito immediato, numeri di sequenza ≥ 0x80000000, non registrati per il replay: le IA si rigiocano da sole). Il bot giocatore del banco di bilanciamento (`World.PlayerBot`, ADR 0025) usa lo stesso agente per la compagnia del giocatore, prima delle IA, e non è salvato. Per il replay si registrano `(tick, comando)` in `World.CommandLog`.
|
||||
- I flussi pseudo-casuali dei sottosistemi si ottengono con `World.Stream(nome)` (derivati dalla radice con `Rng.Fork`, salvati per nome).
|
||||
|
||||
## 4. Determinismo
|
||||
|
||||
+16
-5
@@ -194,11 +194,21 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- `ServerTests`: scheda via WebSocket attesa come risposta nuova, `ServerInfo` nel `Welcome`, elenco dei salvataggi dopo `Save`, `Load` rifiutato con l'avviso del server al giorno −1;
|
||||
- campioni del protocollo con i blocchi nuovi; `Welcome` senza blocco 1 (server F5) con stato del server assente nella copia locale.
|
||||
Con le ere e l'audio: 218 test (198 senza i lenti).
|
||||
- Restano della F6: tooltip «perché», tutorial, bilanciamento con i bot.
|
||||
- bilanciamento con i bot su `simulate` (issue #47, ADR 0025):
|
||||
- obiettivi O1–O14 scritti nell'ADR prima della taratura, ciascuno con il suo motivo nella guida;
|
||||
- `railenterprise-tools balance` (semi × difficoltà × bot × anni, in parallelo, rapporto deterministico): `rapporto.txt` con gli obiettivi e la sintesi (livelli per anno, patrimonio, rating, fallimenti, interessi, prezzi/base min/medio/max, margini dei trasformatori, coperture, ampliamenti, crescita delle città, veicoli superati), `anni.csv`, `mesi.csv`, `prezzi.csv`, `esecuzioni.csv`, `tempi.txt`; `simulate --bot <id>`;
|
||||
- bot giocatore (`PlayerBot`): l'agente delle IA con le personalità di `ai.json → bots` (`bot_competent`, `bot_prudent`) alla guida della compagnia del giocatore; pianifica per primo; non salvato e fuori dall'hash (il formato dei salvataggi non cambia);
|
||||
- le IA (e i bot) usano la compravendita in proprio (supera ADR 0016 §9): vendita delle scorte, arbitraggio nel bacino o verso le stazioni raggiungibili dalle linee merci, con margine minimo, tetti e prezzi limite in `ai.json → trading`;
|
||||
- agente corretto: un trasformatore è una fonte solo con gli input alimentati (prima i bot fallivano su linee che si svuotavano finite le scorte iniziali); la linea dei ricambi di una rete nuova esce dal budget iniziale se l'utile la ripaga entro `planning.partsDeferYears` (3 anni);
|
||||
- dati: `market.world.volumeShare` 0,5 → 1,0 ed `elasticity` 1,0 → 2,5; `planning.townBonus` 1,8 → 3,0 e `townRoiFactor` 0,5 → 0,35;
|
||||
- risultato sulla matrice predefinita (72 esecuzioni da 12 anni): obiettivi raggiunti da 5 a 9 su 14; livello 2 del bot competente in «Imprenditore» al 4° anno (mediana, prima 7°); nessun fallimento dei bot in «Apprendista» e «Imprenditore» (prima 2); prezzi medi tra 0,77 e 1,42 volte il base (prima 0,38–2,78); mesi-bene entro 0,7–1,6 dal 35 % al 91 %; restano aperti O7 (95 %), O8 (margini dei trasformatori, ora per logistica e non per prezzo), O9–O10 (servono linee pendolari), O11 (IA in «Ferro e sangue»);
|
||||
- test: `Balance/BalanceTests.cs`, 4: rapporto deterministico (stesso seme, stesse righe, 1 o 2 thread), bot che gioca con i comandi e non entra nel salvataggio, compravendita dell'agente nello scenario, banco ridotto lento (3 semi, «Imprenditore», 6 anni) sugli obiettivi principali; `EconomyTests.PriceRisesWhenDemandExceedsSupply` con soglia 1,25 (il mondo assorbe parte dello squilibrio).
|
||||
Con il bilanciamento: 222 test (201 senza i lenti), suite completa ~4 minuti.
|
||||
- Restano della F6: tooltip «perché», tutorial.
|
||||
|
||||
## Prossimo passo
|
||||
|
||||
- F6: tooltip «perché», tutorial, bilanciamento con i bot su `simulate`.
|
||||
- F6: tooltip «perché», tutorial.
|
||||
|
||||
## Limiti noti
|
||||
|
||||
@@ -212,14 +222,13 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- Mercato globale (ADR 0015): la previsione segue solo la componente mondiale (ciclo e shock), non domanda e offerta della mappa; «Dove conviene vendere» dà il prezzo alla destinazione, senza il costo del trasporto.
|
||||
- Scalata (ADR 0018): il livello non scende; lo storico del patrimonio ha un punto all'anno (più la fondazione e oggi); il capitale iniziale mostrato è quello della difficoltà; il valore contabile si aggiorna a inizio mese, mentre cassa, partecipazioni e debiti sono del giorno; i salvataggi delle versioni 1–5 ripartiscono il totale degli attivi in proporzione alle voci del giorno di caricamento fino al ricalcolo del mese; il pannello non è ancora stato provato in Godot (qui manca l'editor).
|
||||
- In F3 tutte le sessioni guidano la compagnia del giocatore (ADR 0009).
|
||||
- Il bilanciamento economico è provvisorio (F6): nello scenario l'acciaieria cresce di livello ogni due trimestri finché la linea operai non satura; il prezzo del minerale sale oltre 1,5 volte il base e il margine dei trasformatori diventa negativo quando la domanda supera l'offerta delle miniere.
|
||||
- Bilanciamento (ADR 0025): sulla matrice del banco i beni lavorati (acciaio, legname, materiali edili) restano a lungo sopra 1,6 volte il base nelle difficoltà alte (91 % dei mesi-bene nella fascia contro il 95 % dell'obiettivo); i trasformatori che vendono hanno margine medio negativo perché l'output si vende solo se qualcuno lo ritira; con le sole linee merci le industrie servite lavorano a circa 0,35 (copertura dei lavoratori 0,36) e le città calano dello 0,9 % l'anno; in «Magnate» e «Ferro e sangue» i bot non trovano una prima rete sopra la soglia del ROI e in «Ferro e sangue» poche IA partono entro il 3° anno; nello scenario l'acciaieria cresce ancora ogni due trimestri finché la linea operai non satura (sulla mappa generata 0,3 ampliamenti per industria servita all'anno).
|
||||
- La lunghezza dei marciapiedi non è modellata; i segnali sono solo a blocco fisso (niente segnali di percorso).
|
||||
- Comandi ancora `NotImplemented`: concessioni, contratti, ricerca, regioni (fasi F6–F7).
|
||||
- Manutenzione (ADR 0010): il viaggio verso l'officina si stima in linea d'aria; un treno rimorchiato completa il tratto in corso prima di dirigersi all'officina; con un solo treno su una linea di pendolari e un deposito senza personale la copertura cala durante gli interventi (servono riserve e personale); la mappa dei flussi dei pendolari (frecce blu, opzionale nella guida) non è ancora disegnata.
|
||||
- Una rete a binario semplice con pochi binari di stazione può ancora bloccarsi se tutti i binari alle due estremità sono occupati da treni che devono incrociarsi (stallo di capacità segnalato al giocatore come «possibile stallo»): la rete dell'accettazione F4 è dimensionata di conseguenza.
|
||||
- IA (ADR 0013): su mappe da 128 km in «Magnate» di solito una o due IA crescono (livello 2–3 in 15 anni) mentre le altre restano piccole o falliscono quando la regione non offre candidati con ROI sopra soglia; nel 1850 i grandi fiumi dividono la mappa in regioni fino ai ponti in ferro. Le IA non comprano ancora industrie se non dal livello 3 e non usano la compravendita in proprio (ADR 0016: da aggiungere ai candidati degli agenti con il bilanciamento della F6).
|
||||
- IA (ADR 0013): su mappe da 128 km in «Magnate» di solito una o due IA crescono (livello 2–3 in 15 anni) mentre le altre restano piccole o falliscono quando la regione non offre candidati con ROI sopra soglia; nel 1850 i grandi fiumi dividono la mappa in regioni fino ai ponti in ferro. Le IA non comprano ancora industrie se non dal livello 3; la compravendita in proprio (ADR 0025) guarda solo i venditori del bacino delle proprie stazioni e i compratori raggiungibili dalle linee merci, senza costruire linee apposta; costruiscono di rado linee pendolari.
|
||||
- Borsa (ADR 0012): per le compagnie piccole il prezzo per azione è di pochi centesimi e il premio di un'offerta ha la granularità di un centesimo; antitrust e finanziamenti statali arrivano in F7.
|
||||
- Prezzi, soglie dei livelli e taratura economica restano provvisori fino al bilanciamento della F6.
|
||||
|
||||
## Misure di prestazione
|
||||
|
||||
@@ -244,3 +253,5 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
| Pilota automatico del client con i pannelli F4 | ~90 s, 12 schermate | F4 |
|
||||
| Suite di test (120, parallela su 4 core, con i test lenti delle IA) | ~137 s (accettazione F5 70 s) | F5 |
|
||||
| `simulate --years 15` su 128 km «Magnate» con 3 IA | ~60 s | F5 |
|
||||
| `balance` matrice predefinita (72 esecuzioni da 12 anni su 128 km, 12 in parallelo) | 533 s; 176 s per esecuzione in media, 400 s la più lunga | F6 |
|
||||
| `balance --difficulties imprenditore --years 8` (6 esecuzioni) | ~85 s | F6 |
|
||||
@@ -95,7 +95,7 @@ invarianti.
|
||||
«Compravendita in proprio» del pannello, quando sbloccato, sceglie stazione, quantità e
|
||||
destinazione per la merce selezionata e manda i comandi con un tetto del 10 % sopra (o un minimo
|
||||
del 10 % sotto) il prezzo mostrato: è una scelta d'interfaccia, il server ricalcola tutto.
|
||||
9. **IA.** Le compagnie IA non commerciano ancora: i loro candidati restano linee e treni (ADR 0013).
|
||||
9. **IA.** Le compagnie IA non commerciano ancora: i loro candidati restano linee e treni (ADR 0013). *Superato dall'ADR 0025: le IA commerciano con una regola mensile deterministica (`ai.json → trading`).*
|
||||
|
||||
## Conseguenze
|
||||
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
# ADR 0025 — Bilanciamento con i bot su simulate (F6)
|
||||
|
||||
Stato: accettato (F6, issue #47).
|
||||
|
||||
## Contesto
|
||||
|
||||
La sezione 16 chiede per la F6 il «bilanciamento con bot su `simulate`». Fino a qui prezzi, soglie dei
|
||||
livelli e taratura economica erano provvisori (STATE, «Limiti noti»): il prezzo del minerale saliva oltre
|
||||
1,5 volte il base, il margine dei trasformatori diventava negativo quando la domanda superava l'offerta
|
||||
delle miniere, l'acciaieria dello scenario cresceva di livello ogni due trimestri, e in molte partite due
|
||||
IA su tre non costruivano nulla. Mancavano un banco di prova ripetibile, obiettivi scritti prima di
|
||||
toccare i numeri e la compravendita in proprio delle IA (ADR 0016 §9).
|
||||
|
||||
## Obiettivi (scritti prima della taratura)
|
||||
|
||||
Gli obiettivi si misurano sulla matrice predefinita del banco (semi 1, 2, 3; le quattro difficoltà; bot
|
||||
competente e prudente; 12 anni su 128 km). Ognuno ha un motivo nella guida.
|
||||
|
||||
| Id | Obiettivo | Perché |
|
||||
|---|---|---|
|
||||
| O1 | Bot competente in «Imprenditore»: livello 2 tra il 3° e il 6° anno (mediana dei semi) | La difficoltà predefinita (7) deve dare il primo sblocco (fido, squadre, compravendita) dopo le prime linee, non subito e non mai |
|
||||
| O2 | Bot competente in «Apprendista»: livello 2 entro il 5° anno | Capitale doppio, tariffe ×1,15, costi ×0,8: la scalata deve essere più facile |
|
||||
| O3 | Patrimonio finale mediano del bot competente non crescente da «Apprendista» a «Ferro e sangue» | La tabella della sezione 7 peggiora ogni parametro salendo: la difficoltà deve contare |
|
||||
| O4 | Nessun fallimento del bot prudente in «Apprendista» e «Imprenditore» | Un giocatore prudente non deve finire in bancarotta (12.3: in «Apprendista» non si perde mai) |
|
||||
| O5 | Nessun fallimento del bot competente in «Apprendista» e «Imprenditore» | Le stime dei tooltip (gli stessi `Estimators` delle IA) devono essere affidabili |
|
||||
| O6 | Media di ogni bene sulla partita entro 0,7–1,6 volte il prezzo base | 6.3: il prezzo segue il ciclo mondiale (A = 0,12) con gli squilibri della mappa; i limiti 0,3–3 sono di sicurezza, non lo stato normale |
|
||||
| O7 | Almeno il 95 % dei mesi-bene entro 0,7–1,6 volte il base | Come O6, mese per mese: gli shock (fino a 0,3 × volatilità) possono uscire per poco |
|
||||
| O8 | Margine medio dei trasformatori che vendono positivo in almeno l'80 % dei mesi | 6.3: `pf = clamp(1 + 0,5·margine)`: con margini negativi le industrie servite rendono meno proprio quando il trasporto funziona. Si escludono i trasformatori senza vendite, che hanno margine −1 per costruzione (nessuno ritira l'output) |
|
||||
| O9 | Efficienza media delle industrie servite almeno 0,6 nella seconda metà della partita | ADR 0004 §5: un'industria isolata parte da circa 0,3; servirla deve almeno raddoppiarla |
|
||||
| O10 | Popolazione in «Imprenditore» con il bot: crescita media annua almeno −0,5 % | ADR 0004: senza vettori il mondo perde circa l'1 % l'anno; con bot e IA il declino deve almeno dimezzarsi |
|
||||
| O11 | Almeno la metà delle IA con una linea in esercizio entro il 3° anno | 12.1: concorrenti che giocano davvero |
|
||||
| O12 | Bot competente in «Imprenditore»: interessi entro il 20 % dei ricavi dei trasporti | 6.3: il debito è uno strumento, non una rendita della banca |
|
||||
| O13 | Comandi rifiutati di bot e IA al massimo il 5 % | 14.5 |
|
||||
| O14 | Invarianti di denaro e merci in ogni esecuzione | 14.5 |
|
||||
|
||||
Restano vere le accettazioni: F2 (acciaieria di Valdoria da meno del 40 % a oltre l'80 % in 2 anni), F4
|
||||
(`MaintenanceAcceptanceTests`), F5 (un'IA al livello 3 in 15 anni in «Magnate», seme 7).
|
||||
|
||||
## Decisione
|
||||
|
||||
### Banco di prova
|
||||
|
||||
- `railenterprise-tools balance [--seeds 1,2,3] [--difficulties …] [--bots bot_competent,bot_prudent|nessuno]
|
||||
[--years 12] [--size 128] [--threads n] [--out bilanciamento]` fa giocare, per ogni combinazione seme ×
|
||||
difficoltà × bot, la compagnia del giocatore a un **bot giocatore** insieme alle IA, mese per mese, e scrive
|
||||
`rapporto.txt` (obiettivi O1–O14 e sintesi per difficoltà e bot), `anni.csv` (per compagnia e anno: livello,
|
||||
patrimonio, rating, cassa, debito, interessi, ricavi dei trasporti, utile operativo, treni, linee),
|
||||
`mesi.csv` (prezzi/base, margini dei trasformatori, coperture, efficienza delle servite, popolazione, quota
|
||||
di veicoli superati), `prezzi.csv`, `esecuzioni.csv` (anno di ogni livello, fallimenti, comandi rifiutati,
|
||||
hash finale) e `tempi.txt`. Le esecuzioni girano in parallelo ma il rapporto segue l'ordine della matrice e
|
||||
non contiene tempi: stesso seme, stesso rapporto (test). `simulate --bot <id>` fa lo stesso su una partita.
|
||||
- Il bot giocatore (`PlayerBot`) è l'agente delle IA (stessi comandi, stesse stime) con una personalità di
|
||||
`ai.json → bots` (`bot_competent`: ROI 10 %, fido al 60 %, manutenzione standard; `bot_prudent`: ROI 18 %,
|
||||
fido al 25 %, manutenzione accurata). Pianifica lo stesso giorno della prima IA ma prima di lei, come un
|
||||
giocatore che costruisce dal primo giorno. È uno strumento di prova: non entra nel salvataggio né nell'hash
|
||||
(ne entrano gli effetti, che passano tutti dai comandi), quindi il formato dei salvataggi non cambia.
|
||||
- Tempi della matrice predefinita (72 esecuzioni da 12 anni su 128 km, 12 in parallelo): 533 s in tutto,
|
||||
176 s per esecuzione in media, 400 s la più lunga (prima della taratura 638 / 195 / 506 s).
|
||||
|
||||
### Compravendita delle IA (supera ADR 0016 §9)
|
||||
|
||||
Ogni mese, dopo i progetti, l'agente (IA o bot) vende le scorte dei propri magazzini se il miglior acquirente
|
||||
del bacino paga almeno `minSellPriceShare` del prezzo globale; se il livello sblocca la compravendita, cerca
|
||||
per ogni stazione e bene il venditore più economico del bacino e il compratore migliore nello stesso bacino
|
||||
o in una stazione raggiungibile dalle sue linee merci (`LineGraph`); un affare vale se il margine
|
||||
(vendita − acquisto)/acquisto è almeno `minMargin`. Quantità: al più `maxUnits`, la merce disponibile, lo
|
||||
spazio del magazzino, quanto ricevono i compratori e la quota `cashShare` della cassa oltre
|
||||
`cashReserveMultiple` volte la riserva. Gli affari si ordinano per utile (poi stazione, bene, destinazione) e
|
||||
se ne fanno al più `maxTradesPerMonth`, uno per stazione e bene, con prezzo massimo e minimo a ±`priceSlack`
|
||||
dalla quotazione; nello stesso bacino si rivende subito (solo alle industrie se nel bacino c'è un hub, che compra e vende con la stessa capacità mensile, e ricontrollando lo spazio dei compratori, che due stazioni vicine possono condividere), altrimenti si spedisce. Parametri in
|
||||
`ai.json → trading`; il validatore chiede `minMargin > 2·priceSlack`.
|
||||
|
||||
### Regole dell'agente corrette con il banco
|
||||
|
||||
1. **Trasformatori senza input** (causa dei fallimenti dei bot): una linea che parte da un'industria di
|
||||
trasformazione ne stimava la produzione con l'efficienza del giorno, alta all'inizio per scorte e copertura
|
||||
iniziali; finite le scorte l'impianto si fermava e la linea non incassava più nulla. Ora un trasformatore è
|
||||
una fonte solo se ogni suo input è alimentato (una stazione in esercizio lo serve, o un produttore di quel
|
||||
bene è nel raggio del trasporto locale).
|
||||
2. **Linea dei ricambi rimandata**: una rete nuova lontana dai ricambi metteva subito nel budget anche la linea
|
||||
dei ricambi (spesso più cara della linea stessa) e in «Imprenditore» il bot non costruiva mai. Ora la linea
|
||||
dei ricambi entra sempre nel ROI ma esce dal budget iniziale se l'utile atteso la ripaga entro
|
||||
`planning.partsDeferYears` (3 anni, entro i quali la dotazione del deposito regge: accettazione F4); finché
|
||||
un deposito in esercizio aspetta la sua linea e la cassa non basta, l'agente non apre reti nuove.
|
||||
|
||||
### Taratura dei dati
|
||||
|
||||
| File | Valore | Prima | Dopo | Motivo |
|
||||
|---|---|---|---|---|
|
||||
| `balance.json` | `market.world.volumeShare` | 0,5 | 1,0 | il resto del mondo scambia quanto la mappa: gli squilibri locali spostano meno il prezzo (O6, O7) |
|
||||
| `balance.json` | `market.world.elasticity` | 1,0 | 2,5 | domanda e offerta del mondo reagiscono di più al prezzo e lo riportano verso il ciclo; con 3,0 la flotta senza ricambi dell'accettazione F4 restava a 41 (limite 40) |
|
||||
| `ai.json` | `planning.townBonus` | 1,8 | 3,0 | quando il livello successivo chiede città collegate, le linee verso le città passano davanti alle merci (O1) |
|
||||
| `ai.json` | `planning.townRoiFactor` | 0,5 | 0,35 | idem: soglia del ROI delle linee urbane al 35 % di quella della personalità |
|
||||
| `ai.json` | `planning.partsDeferYears` | — | 3,0 | nuovo, regola 2 |
|
||||
| `ai.json` | `trading`, `bots` | — | nuovi | compravendita e bot giocatore |
|
||||
|
||||
Restano com'erano i valori fissati dalla guida (capitale e fido iniziali, moltiplicatori di difficoltà, k, α,
|
||||
A, T, limiti 0,3–3, formula del costo dei binari) e le soglie dei livelli: con le regole corrette bastano.
|
||||
|
||||
### Prima e dopo (matrice predefinita: semi 1–3, quattro difficoltà, due bot, 12 anni, 128 km)
|
||||
|
||||
| Metrica | Prima | Dopo |
|
||||
|---|---|---|
|
||||
| O1 livello 2 del bot competente in «Imprenditore» (anni dei semi) | mai / 5 / 7, mediana 7 | 4 / 8 / 3, mediana 4 |
|
||||
| O2 livello 2 del bot competente in «Apprendista» | mediana 1 | mediana 2 (livello 3 mediano al 4° anno) |
|
||||
| O3 patrimonio finale mediano del bot competente (Appr. / Impr. / Magn. / Ferro) | ₤ 1.989.863 / 393.763 / 150.000 / 100.000 | ₤ 4.729.246 / 1.683.669 / 150.000 / 100.000 |
|
||||
| O4 fallimenti del bot prudente (Appr. e Impr.) | 1 su 6 | 0 su 6 |
|
||||
| O5 fallimenti del bot competente (Appr. e Impr.) | 1 su 6 | 0 su 6 |
|
||||
| O6 media dei prezzi / base, bene più basso e più alto | 0,38 (grano) – 2,78 (alimentari) | 0,77 (bestiame) – 1,42 (materiali edili) |
|
||||
| Minerale di ferro / base in «Imprenditore» (min / medio / max) | 0,30 / 0,68 / 1,69 | 0,55 / 0,83 / 1,20 |
|
||||
| Acciaio / base in «Imprenditore» (min / medio / max) | 1,05 / 2,31 / 3,00 | 1,03 / 1,39 / 1,82 |
|
||||
| O7 mesi-bene entro 0,7–1,6 | 34,8 % | 91,1 % |
|
||||
| O8 mesi con margine medio positivo dei trasformatori che vendono | 9,0 % (margine −0,62) | 5,6 % (margine −0,70) |
|
||||
| O9 efficienza delle industrie servite, seconda metà | 0,323 | 0,355 |
|
||||
| Coperture medie input / lavoratori / personale («Imprenditore») | 0,80 / 0,36 / 0,43 | 0,80 / 0,36 / 0,42 |
|
||||
| Ampliamenti per industria servita all'anno («Imprenditore») | non misurato | 0,32 |
|
||||
| O10 crescita annua delle città in «Imprenditore» | −0,9 % | −0,9 % |
|
||||
| O11 IA con una linea entro il 3° anno | 42,4 % (28 su 66) | 40,9 % (27 su 66) |
|
||||
| O12 interessi / ricavi dei trasporti del bot competente in «Imprenditore» | 5,3 % | 3,8 % |
|
||||
| O13 comandi rifiutati di bot e IA | 2,7 % (167 su 6.248) | 0,1 % (9 su 6.540) |
|
||||
| O14 invarianti di denaro e merci | rispettati | rispettati |
|
||||
| Veicoli superati alla fine dei 12 anni | 0 % | 0 % |
|
||||
| Obiettivi raggiunti | 5 su 14 | 9 su 14 |
|
||||
|
||||
### Obiettivi non raggiunti (restano aperti)
|
||||
|
||||
- **O7** (91 % contro 95 %): i beni lavorati (acciaio, legname, materiali edili) stanno a lungo sopra 1,6
|
||||
nelle difficoltà alte, dove pochi trasformatori sono serviti; un'elasticità più alta li rientrerebbe ma
|
||||
porta l'accettazione F4 oltre il limite.
|
||||
- **O8**: il problema noto dei prezzi è risolto (il minerale non supera più 1,2 volte il base e ai prezzi
|
||||
medi di dopo un'acciaieria a piena capacità ha margine circa +0,5), ma i trasformatori
|
||||
comprano gli input e vendono l'output solo se qualcuno lo ritira: con vendite parziali la media resta
|
||||
negativa. È logistica (output non trasportato), non prezzo.
|
||||
- **O9, O10**: con le sole linee merci l'efficienza resta limitata dai lavoratori (copertura 0,36): servono
|
||||
linee pendolari, che bot e IA costruiscono di rado; la crescita delle città resta quella senza vettori.
|
||||
- **O11** e i bot in «Magnate» e «Ferro e sangue»: con ₤ 150.000 e ₤ 100.000 e i costi ×1,25 e ×1,5 nessuna
|
||||
prima rete supera il ROI della personalità; le IA, con il capitale moltiplicato, partono, ma in «Ferro e
|
||||
sangue» solo 2 su 15 entro il 3° anno.
|
||||
- La crescita dell'acciaieria dello scenario «ogni due trimestri» non si ripete sulla mappa generata (0,32
|
||||
ampliamenti per industria servita all'anno); il punteggio di crescita della sezione 6 resta com'è.
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Il banco fa parte della verifica: il test lento `BalanceTests.BenchMeetsTheMainGoals` (3 semi,
|
||||
«Imprenditore», bot competente, 6 anni) controlla O1, O5, O6, O12, O13 e O14; un test veloce controlla il
|
||||
determinismo del rapporto.
|
||||
- `EconomyTests.PriceRisesWhenDemandExceedsSupply` chiedeva un aumento di 1,5 volte in 120 giorni senza
|
||||
offerta; con il mondo a volume pieno ed elasticità 2,5 l'aumento è circa 1,36: la soglia passa a 1,25 (resta
|
||||
la verifica che lo squilibrio alzi il prezzo).
|
||||
- Restano vere le accettazioni F2, F4 (flotta senza ricambi a 39) e F5 (un'IA al livello 3 nel 1861 in
|
||||
«Magnate», seme 7).
|
||||
@@ -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);
|
||||
|
||||
@@ -10,6 +10,7 @@ public static class ToolsProgram
|
||||
new ValidateDataCommand(),
|
||||
new GenMapCommand(),
|
||||
new SimulateCommand(),
|
||||
new BalanceCommand(),
|
||||
new ProfileCommand(),
|
||||
new BenchCommand(),
|
||||
new SmokeCommand(),
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Persistence;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Ai;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
using RailEnterprise.Tests.Harness;
|
||||
using RailEnterprise.Tools.Balance;
|
||||
using static RailEnterprise.Tests.Rail.RailFixture;
|
||||
|
||||
namespace RailEnterprise.Tests.Balance;
|
||||
|
||||
/// <summary>Banco di bilanciamento con i bot giocatore e compravendita delle IA (F6, issue #47, ADR 0025).</summary>
|
||||
public static class BalanceTests
|
||||
{
|
||||
[Test(Description = "Il banco è deterministico: stesso seme, stesso rapporto (testo, CSV e hash finale)")]
|
||||
public static void SameSeedGivesTheSameReport()
|
||||
{
|
||||
var o = new BalanceOptions { Seeds = [5], Difficulties = ["imprenditore"], Bots = ["bot_competent"], Years = 2, SizeKm = 64, Threads = 1 };
|
||||
var a = BalanceBench.Run(TestData.Data, o);
|
||||
var b = BalanceBench.Run(TestData.Data, o with { Threads = 2 });
|
||||
Assert.Equal(BalanceReport.Text(TestData.Data, o, a), BalanceReport.Text(TestData.Data, o, b));
|
||||
Assert.Equal(BalanceReport.YearsCsv(a), BalanceReport.YearsCsv(b));
|
||||
Assert.Equal(BalanceReport.MonthsCsv(TestData.Data, a), BalanceReport.MonthsCsv(TestData.Data, b));
|
||||
Assert.Equal(BalanceReport.RunsCsv(TestData.Data, a), BalanceReport.RunsCsv(TestData.Data, b));
|
||||
Assert.Equal(a[0].FinalHash, b[0].FinalHash);
|
||||
Assert.True(a[0].BotCommands > 0, "il bot ha giocato");
|
||||
Assert.True(a[0].InvariantsOk, "invarianti di denaro e merci");
|
||||
Assert.Equal(24, a[0].Months.Count);
|
||||
}
|
||||
|
||||
[Test(Slow = true, Description = "Banco ridotto (ADR 0025): in «Imprenditore» il bot competente arriva al livello 2 tra il 3° e il 6° anno senza fallire, prezzi medi nella fascia, pochi rifiuti, invarianti")]
|
||||
public static void BenchMeetsTheMainGoals()
|
||||
{
|
||||
var o = new BalanceOptions { Seeds = [1, 2, 3], Difficulties = ["imprenditore"], Bots = ["bot_competent"], Years = 6 };
|
||||
var runs = BalanceBench.Run(TestData.Data, o);
|
||||
var goals = BalanceReport.Goals(TestData.Data, runs);
|
||||
foreach (var g in goals) Console.WriteLine($" {(g.Met is null ? "—" : g.Met.Value ? "sì" : "NO")} {g.Id} {g.Text}: {g.Measured}");
|
||||
foreach (var id in new[] { "O1", "O5", "O6", "O12", "O13", "O14" })
|
||||
{
|
||||
var g = goals.Single(x => x.Id == id);
|
||||
Assert.True(g.Met == true, $"{g.Id} {g.Text}: {g.Measured}");
|
||||
}
|
||||
}
|
||||
|
||||
[Test(Description = "Il bot guida la compagnia del giocatore con i comandi, non entra nel salvataggio e il mondo resta deterministico")]
|
||||
public static void BotDrivesThePlayerAndIsNotSaved()
|
||||
{
|
||||
static World Make()
|
||||
{
|
||||
var w = TestWorlds.Small(11);
|
||||
w.PlayerBot = PlayerBot.Create(w, "bot_competent");
|
||||
return w;
|
||||
}
|
||||
var a = Make();
|
||||
var b = Make();
|
||||
a.RunYears(1);
|
||||
b.RunYears(1);
|
||||
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(b));
|
||||
Assert.True(a.PlayerBot!.State.Issued > 0, "il bot emette comandi");
|
||||
Assert.True(a.Network.Stations.Any(s => s.Owner == a.Player.Id), "stazioni del giocatore costruite dal bot");
|
||||
Assert.True(a.PlayerBot.State.RejectedShare <= a.Data.Ai.Planning.MaxRejectedShare, $"rifiutati {a.PlayerBot.State.Rejected} su {a.PlayerBot.State.Issued}");
|
||||
Assert.Equal(a.Companies.Count(c => !c.IsPlayer), a.AiStates.Count);
|
||||
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(a, "test"));
|
||||
Assert.True(loaded.PlayerBot is null, "il bot non è salvato");
|
||||
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(loaded));
|
||||
Assert.Throws<ArgumentException>(() => PlayerBot.Create(a, "expansive"));
|
||||
}
|
||||
|
||||
[Test(Description = "Compravendita delle IA (ADR 0016 §9): con il produttore pieno e il consumatore a secco nello stesso bacino l'agente compra e vende, senza comandi rifiutati")]
|
||||
public static void AgentTradesWhenTheMarginPays()
|
||||
{
|
||||
var f = Valdoria();
|
||||
var w = f.W;
|
||||
// stazione tra l'acciaieria e la fabbrica di attrezzi: produttore e consumatore dell'acciaio nello stesso bacino
|
||||
int hub = f.Ok(new BuildStationCommand(K(11.7, 3.7), 2, "Acciaierie"));
|
||||
var station = w.Network.Stations[hub];
|
||||
var mill = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
var tools = w.Industries.First(i => i.Def.Id == "tool_factory");
|
||||
Assert.True(station.Industries.Contains(mill.Id) && station.Industries.Contains(tools.Id), "bacino con acciaieria e fabbrica");
|
||||
w.Player.Tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.Trading).Level;
|
||||
int steel = w.Data.Goods.First(g => g.Id == "steel").Index;
|
||||
int cap = IndustryMath.OutputCapacity(mill, 0, w.Calendar.DaysPerMonth);
|
||||
w.Goods.Produced[steel] += cap - mill.OutputStock[0];
|
||||
mill.OutputStock[0] = cap;
|
||||
int input = tools.InputIndexOf(steel);
|
||||
w.Goods.Decayed[steel] += tools.InputStock[input];
|
||||
tools.InputStock[input] = 0;
|
||||
var q = TradingMath.Quote(w, station, steel);
|
||||
Assert.True((q.SellPrice - q.BuyPrice) / q.BuyPrice > w.Data.Ai.Trading.MinMargin, $"margine atteso: compra {q.BuyPrice:0}, vende {q.SellPrice:0}");
|
||||
|
||||
w.PlayerBot = PlayerBot.Create(w, "bot_competent");
|
||||
long millCash = mill.Cash.Cents, toolsCash = tools.Cash.Cents;
|
||||
w.RunDays(w.Calendar.DaysPerMonth + 1);
|
||||
long trading = w.Player.YearEntries[(int)LedgerEntry.Trading];
|
||||
Assert.True(mill.Cash.Cents > millCash, "l'acciaieria ha venduto acciaio alla compagnia");
|
||||
Assert.True(tools.Cash.Cents < toolsCash, "la fabbrica di attrezzi ha comprato l'acciaio");
|
||||
Assert.True(trading > 0, $"utile della compravendita: {trading} centesimi");
|
||||
Assert.Equal(0, station.StockOf(steel), "rivenduto subito alla fabbrica");
|
||||
Assert.Equal(0L, w.PlayerBot.State.Rejected, "nessun comando rifiutato");
|
||||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||||
for (int g = 0; g < w.Data.GoodCount; g++)
|
||||
Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id}");
|
||||
}
|
||||
}
|
||||
@@ -46,9 +46,10 @@ public static class EconomyTests
|
||||
var w = TestWorlds.Small(103);
|
||||
int food = w.Data.GoodIndex("food");
|
||||
double before = w.Market.GlobalPrice[food];
|
||||
// nessuna produzione di alimentari raggiunge il mercato: la domanda cittadina spinge il prezzo
|
||||
// nessuna produzione di alimentari raggiunge il mercato: la domanda cittadina spinge il prezzo; il resto
|
||||
// del mondo (volume pieno ed elasticità 2,5, ADR 0025) ne assorbe una parte, quindi la salita è più dolce
|
||||
w.RunDays(120);
|
||||
Assert.True(w.Market.GlobalPrice[food] > before * 1.5, $"prezzo alimentari {before} → {w.Market.GlobalPrice[food]}");
|
||||
Assert.True(w.Market.GlobalPrice[food] > before * 1.25, $"prezzo alimentari {before} → {w.Market.GlobalPrice[food]}");
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
<ProjectReference Include="..\..\src\RailEnterprise.Core\RailEnterprise.Core.csproj" />
|
||||
<ProjectReference Include="..\..\src\RailEnterprise.Protocol\RailEnterprise.Protocol.csproj" />
|
||||
<ProjectReference Include="..\..\src\RailEnterprise.Server\RailEnterprise.Server.csproj" />
|
||||
<ProjectReference Include="..\..\src\RailEnterprise.Tools\RailEnterprise.Tools.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
Reference in new issue
Block a user