Prima parte della F6: il pannello «Mercato globale» dell'immagine di riferimento 06, con i dati calcolati dal server. - Lo storico dei prezzi globali passa da 360 a 720 giorni. I salvataggi con lo storico di un anno si migrano al caricamento allungando la finestra (RollingWindow.Extended), senza cambiare formato. - MarketOutlook (Core) è un'analisi in sola lettura del mondo: storico mensile, variazione a 30 giorni, offerta e domanda con la quota mondiale, scorte in mesi, indice materie prime, previsione a 4 mesi dalla componente mondiale con banda, destinazioni di vendita ordinate per prezzo con la linea che le collega, hub, evento in corso e avanzamento verso la compravendita in proprio. Parametri nuovi in balance.json (market.outlook); interpretazioni nell'ADR 0015. - Protocollo: DetailKind.Market (7) e MarketReport (129); il server risponde su richiesta, il client lo mostra in un pannello a tutto schermo e il pilota automatico ne fa la schermata 16_mercato. - Test: finestra allungata e migrazione, storico mensile, previsione deterministica ed entro i limiti, evento, analisi su Valdoria, round-trip del messaggio e quadro via WebSocket. La simulazione non cambia: l'analisi non scrive nel mondo e l'accettazione F4 dà gli stessi numeri di prima. Closes #29. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
117 lines
6.4 KiB
C#
117 lines
6.4 KiB
C#
using System.Diagnostics;
|
|
using System.Globalization;
|
|
using System.Text;
|
|
using RailEnterprise.Core.Data;
|
|
using RailEnterprise.Core.Economy;
|
|
using RailEnterprise.Core.Persistence;
|
|
using RailEnterprise.Core.Simulation;
|
|
using RailEnterprise.Core.Simulation.Systems;
|
|
|
|
namespace RailEnterprise.Tools.Commands;
|
|
|
|
/// <summary>
|
|
/// simulate: fa girare il mondo per N anni senza client e scrive i KPI annuali in CSV
|
|
/// (separatore «;», decimali con la virgola) con le colonne della guida (14.5).
|
|
/// </summary>
|
|
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]";
|
|
|
|
private static readonly CultureInfo It = CultureInfo.InvariantCulture;
|
|
|
|
public int Run(CommandLine args)
|
|
{
|
|
ulong seed = args.ULong("seed", 1);
|
|
int years = args.Int("years", 20);
|
|
int size = args.Int("size", 128);
|
|
string difficulty = args.String("difficulty", "imprenditore");
|
|
string? scenario = args.String("scenario");
|
|
string output = args.String("out", "kpi.csv");
|
|
string? savePath = args.String("save");
|
|
bool trace = args.Flag("trace-ai");
|
|
args.EnsureAllUsed();
|
|
if (trace) Core.Simulation.Ai.AiSystem.Trace = Console.WriteLine;
|
|
|
|
var data = GameData.LoadDefault();
|
|
var total = Stopwatch.StartNew();
|
|
World world;
|
|
if (scenario is not null)
|
|
world = Scenarios.ScenarioLoader.Load(data, scenario).World;
|
|
else
|
|
world = WorldFactory.Create(data, new NewGameSettings { Seed = seed, SizeKm = size, DifficultyId = difficulty });
|
|
long createMs = total.ElapsedMilliseconds;
|
|
|
|
var csv = new StringBuilder();
|
|
csv.AppendLine("anno;compagnia;bene;prezzo medio;produzione;consumo;popolazione;efficienza media;condizione media flotta;condizione media impianti;cassa;patrimonio;quota di mercato;nota");
|
|
var lastProduced = (long[])world.Goods.Produced.Clone();
|
|
var lastConsumed = (long[])world.Goods.Consumed.Clone();
|
|
|
|
var sim = Stopwatch.StartNew();
|
|
for (int y = 0; y < years; y++)
|
|
{
|
|
int year = world.Clock.Year;
|
|
world.RunYears(1);
|
|
WriteYear(world, year, csv, lastProduced, lastConsumed);
|
|
Array.Copy(world.Goods.Produced, lastProduced, lastProduced.Length);
|
|
Array.Copy(world.Goods.Consumed, lastConsumed, lastConsumed.Length);
|
|
world.Events.Drain();
|
|
}
|
|
long simMs = sim.ElapsedMilliseconds;
|
|
|
|
File.WriteAllText(output, csv.ToString(), new UTF8Encoding(encoderShouldEmitUTF8Identifier: true));
|
|
if (savePath is not null) SaveFile.SaveToFile(world, savePath, typeof(SimulateCommand).Assembly.GetName().Version?.ToString() ?? "?");
|
|
|
|
Console.WriteLine($"simulate: {years} anni su {world.Settings.SizeKm} km in {simMs / 1000.0:F1} s (creazione {createMs} ms)");
|
|
Console.WriteLine($" data finale {world.Clock.Date}, hash {world.LastStateHash:x16}");
|
|
Console.WriteLine($" popolazione {Core.Common.Money.GroupThousands((ulong)world.Towns.Sum(t => (long)t.Population))}, industrie aperte {world.Industries.Count(i => !i.Closed)} su {world.Industries.Count}");
|
|
Console.WriteLine($" invarianti: denaro {(world.MoneyBalanceSum() == 0 ? "ok" : "ROTTO")}, merci {(Enumerable.Range(0, data.GoodCount).All(g => world.TotalStock(g) == world.Goods.ExpectedStock(g)) ? "ok" : "ROTTO")}");
|
|
foreach (var c in world.Companies)
|
|
Console.WriteLine($" {c.Name}: patrimonio {c.NetWorth}, cassa {c.Cash}, livello {c.Tier}, rating {c.Rating}, azione {c.SharePrice / 100:0.00} lire{AiNote(world, c)}{(c.Defunct ? " (fuori gioco)" : "")}");
|
|
Console.WriteLine($" KPI in {output}");
|
|
return 0;
|
|
}
|
|
|
|
private static void WriteYear(World w, int year, StringBuilder csv, long[] lastProduced, long[] lastConsumed)
|
|
{
|
|
var data = w.Data;
|
|
long population = w.Towns.Sum(t => (long)t.Population);
|
|
var open = w.Industries.Where(i => !i.Closed).ToList();
|
|
double efficiency = open.Count == 0 ? 0 : open.Average(i => i.Efficiency);
|
|
double plant = open.Count == 0 ? 0 : open.Average(i => i.Condition);
|
|
for (int g = 0; g < data.GoodCount; g++)
|
|
{
|
|
var def = data.Goods[g];
|
|
double price = w.Market.PriceHistory[g].AverageOfLast(w.Calendar.DaysPerYear) / 100.0;
|
|
long produced = w.Goods.Produced[g] - lastProduced[g];
|
|
long consumed = w.Goods.Consumed[g] - lastConsumed[g];
|
|
string note = def.Era > year ? "non ancora disponibile" : "";
|
|
csv.AppendLine(string.Join(';', year.ToString(It), "", def.Id, Dec(price), produced.ToString(It), consumed.ToString(It),
|
|
population.ToString(It), Dec(efficiency), "", Dec(plant), "", "", "", note));
|
|
}
|
|
long totalCarrier = w.Companies.Sum(c => Company.Revenue(c.LastYearEntries));
|
|
foreach (var c in w.Companies)
|
|
{
|
|
long revenue = Company.Revenue(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)}";
|
|
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));
|
|
}
|
|
}
|
|
|
|
/// <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);
|
|
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);
|
|
return $", progetti {running}/{s.Projects.Count}, treni {trains}, città collegate {Tiers.ConnectedTowns(w, c.Id, 1000)} (≥1000) {Tiers.ConnectedTowns(w, c.Id, 2000)} (≥2000), comandi {s.Issued} (rifiutati {s.RejectedShare * 100:0.0} %)";
|
|
}
|
|
|
|
private static string Dec(double v) => v.ToString("0.###", It).Replace('.', ',');
|
|
}
|