- Sezione 11: usura e recupero degli impianti, fermi e incidenti, ricambi e macchinari come domanda esplicita (treno, trasporto locale, trasbordo nel bacino), revisione e ammodernamento, acquisto delle industrie dal livello 3, conguaglio mensile con il proprietario (ADR 0011). - Livelli della compagnia con soglie ritarate e ritaratura economica misurata con le IA. - Sezione 12.2–12.3: libro dei soci, prezzo con sentiment, quotazione, riacquisto, dividendi, controllo e fusione (comando 39), offerte pubbliche con difese, esiti per difficoltà, aste delle IA fallite, nuovi concorrenti, fine partita e Cronaca finale (ADR 0012). - Sezione 12.1: agenti IA con candidati, Dijkstra sulle celle, TrackPreview e ROI, tre personalità, linee dei ricambi, rimedio agli stalli, borsa (ADR 0013). - Salvataggio versione 3, protocollo (messaggi 126–128, blocchi di estensione), server, simulate --trace-ai; test di 14.5 su IA e borsa e accettazione F5 (120 test). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
117 lines
6.4 KiB
C#
117 lines
6.4 KiB
C#
using System.Diagnostics;
|
|
using System.Globalization;
|
|
using System.Text;
|
|
using ViaFerrea.Core.Data;
|
|
using ViaFerrea.Core.Economy;
|
|
using ViaFerrea.Core.Persistence;
|
|
using ViaFerrea.Core.Simulation;
|
|
using ViaFerrea.Core.Simulation.Systems;
|
|
|
|
namespace ViaFerrea.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].Average / 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('.', ',');
|
|
}
|