Merge remote-tracking branch 'origin/main' into claude/f6-bilanciamento
Tooltip «perché» (PR #52) e tutorial (PR #51) entrano nel ramo; in STATE.md restano le due sezioni di main e quella del bilanciamento, con i passi rimasti della F6. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
67a3dd05f9
49 files changed
+4116
-86
No files matched your search
@@ -0,0 +1,346 @@
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
using RailEnterprise.Client.Tutorial;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using RailEnterprise.Tests.Harness;
|
||||
|
||||
namespace RailEnterprise.Tests.Client;
|
||||
|
||||
/// <summary>Tutorial guidato del client (F6, issue #45, ADR 0023): copione, condizioni, macchina a stati, avanzamento salvato.</summary>
|
||||
public static class TutorialTests
|
||||
{
|
||||
private static string ClientDir()
|
||||
{
|
||||
var dir = new DirectoryInfo(AppContext.BaseDirectory);
|
||||
while (dir is not null)
|
||||
{
|
||||
string candidate = Path.Combine(dir.FullName, "client", "RailEnterprise.Client");
|
||||
if (File.Exists(Path.Combine(candidate, "project.godot"))) return candidate;
|
||||
dir = dir.Parent;
|
||||
}
|
||||
throw new DirectoryNotFoundException("Cartella del client non trovata");
|
||||
}
|
||||
|
||||
private static TutorialScript RealScript() =>
|
||||
TutorialScript.Parse(File.ReadAllText(Path.Combine(ClientDir(), "assets", "tutorial", "tutorial.json")));
|
||||
|
||||
private static TutorialStep Step(string id, TutorialCondition? done = null, string? highlight = null) =>
|
||||
new() { Id = id, Title = "Titolo " + id, Text = "Testo " + id, Done = done, Highlight = highlight };
|
||||
|
||||
private static TutorialFacts Facts(string panel = TutorialFacts.NoPanel, params (string Counter, double Value)[] counters)
|
||||
{
|
||||
var f = new TutorialFacts { Panel = panel };
|
||||
foreach (var (c, v) in counters) f.Set(c, v);
|
||||
return f;
|
||||
}
|
||||
|
||||
[Test(Description = "Il copione reale è valido e copre la sequenza minima della prima partita")]
|
||||
public static void RealScriptIsValidAndComplete()
|
||||
{
|
||||
var script = RealScript();
|
||||
var errors = script.Validate();
|
||||
Assert.True(errors.Count == 0, string.Join("; ", errors));
|
||||
string[] required =
|
||||
[
|
||||
"welcome", "map", "time", "stations", "depot", "track-tool", "track-profile", "track-build", "construction",
|
||||
"locomotive", "cars", "compose", "line", "assign", "market", "finance", "climb", "tips",
|
||||
];
|
||||
int last = -1;
|
||||
foreach (string id in required)
|
||||
{
|
||||
int i = script.IndexOf(id);
|
||||
Assert.True(i > last, $"passo «{id}» mancante o fuori ordine");
|
||||
last = i;
|
||||
}
|
||||
Assert.True(script.Steps[0].IsInformative, "si apre con un passo informativo");
|
||||
Assert.True(script.Steps[^1].IsInformative, "si chiude con i consigli (informativo)");
|
||||
// il profilo si guarda prima di costruire, e i pannelli finali si aprono davvero
|
||||
Assert.Equal("track", script.Steps[script.IndexOf("track-tool")].Done!.Panel);
|
||||
foreach (string panel in new[] { "market", "finance", "climb" })
|
||||
Assert.Equal(panel, script.Steps[script.IndexOf(panel)].Done!.Panel);
|
||||
}
|
||||
|
||||
[Test(Description = "Titoli, testi e scritte del tutorial hanno la riga in strings.csv con l'inglese")]
|
||||
public static void TextsAreTranslated()
|
||||
{
|
||||
var rows = ReadCsv(Path.Combine(ClientDir(), "assets", "i18n", "strings.csv"));
|
||||
var keys = new List<string>();
|
||||
foreach (var s in RealScript().Steps) keys.AddRange([s.Title, s.Text]);
|
||||
keys.AddRange(["Avanti", "Salta passo", "Chiudi tutorial", "Tutorial", "Passo {0} di {1}", "Fine", "Fatto", "Mostra il tutorial",
|
||||
"Tutorial non disponibile: {0}", "Nuova partita locale di prova con il tutorial dal primo passo: la tua partita locale resta com'è"]);
|
||||
foreach (string key in keys)
|
||||
{
|
||||
Assert.True(rows.TryGetValue(key, out var row), $"manca in strings.csv: «{key}»");
|
||||
Assert.True(row!.Length >= 3 && row[1].Length == 0 && row[2].Trim().Length > 0, $"riga senza inglese o con l'italiano non vuoto: «{key}»");
|
||||
}
|
||||
}
|
||||
|
||||
[Test(Description = "I pannelli noti al tutorial sono gli strumenti della barra (enum Tool del client)")]
|
||||
public static void PanelsMatchToolbar()
|
||||
{
|
||||
string toolbar = File.ReadAllText(Path.Combine(ClientDir(), "scripts", "Hud", "Toolbar.cs"));
|
||||
var m = Regex.Match(toolbar, @"public enum Tool\s*\{([^}]*)\}");
|
||||
Assert.True(m.Success, "enum Tool non trovato");
|
||||
var tools = m.Groups[1].Value.Split(',').Select(t => t.Trim().ToLowerInvariant()).Where(t => t.Length > 0).ToList();
|
||||
Assert.SequenceEqual(tools, TutorialFacts.KnownPanels);
|
||||
// e GameScreen risolve ogni elemento che non sia un pulsante della barra
|
||||
string screen = File.ReadAllText(Path.Combine(ClientDir(), "scripts", "Screens", "GameScreen.cs"));
|
||||
foreach (string target in TutorialScript.KnownTargets.Where(t => !t.StartsWith("toolbar:", StringComparison.Ordinal)))
|
||||
Assert.True(screen.Contains($"\"{target}\" =>"), $"GameScreen.TutorialTarget non risolve «{target}»");
|
||||
}
|
||||
|
||||
[Test(Description = "Contatori assoluti, aumenti dall'inizio del passo, pannello aperto, tutte e almeno una")]
|
||||
public static void ConditionsUseFactsAndBaseline()
|
||||
{
|
||||
var empty = Facts();
|
||||
var atLeast = new TutorialCondition { Counter = "stations", AtLeast = 2 };
|
||||
Assert.False(atLeast.IsMet(Facts(counters: ("stations", 1)), empty));
|
||||
Assert.True(atLeast.IsMet(Facts(counters: ("stations", 2)), empty));
|
||||
|
||||
var atMost = new TutorialCondition { Counter = "edgesBuilding", AtMost = 0 };
|
||||
Assert.True(atMost.IsMet(empty, empty), "un contatore mai visto vale zero");
|
||||
Assert.False(atMost.IsMet(Facts(counters: ("edgesBuilding", 1)), empty));
|
||||
|
||||
var increase = new TutorialCondition { Counter = "cmd:BuildTrack", Increase = 1 };
|
||||
var baseline = Facts(counters: ("cmd:BuildTrack", 3));
|
||||
Assert.False(increase.IsMet(Facts(counters: ("cmd:BuildTrack", 3)), baseline), "i binari costruiti prima del passo non contano");
|
||||
Assert.True(increase.IsMet(Facts(counters: ("cmd:BuildTrack", 4)), baseline));
|
||||
|
||||
var panel = new TutorialCondition { Panel = "market" };
|
||||
Assert.True(panel.IsMet(Facts("market"), empty));
|
||||
Assert.False(panel.IsMet(Facts("finance"), empty));
|
||||
|
||||
var all = new TutorialCondition { All = [atLeast, panel] };
|
||||
var any = new TutorialCondition { Any = [atLeast, panel] };
|
||||
Assert.False(all.IsMet(Facts("market"), empty));
|
||||
Assert.True(any.IsMet(Facts("market"), empty));
|
||||
Assert.True(all.IsMet(Facts("market", ("stations", 2)), empty));
|
||||
}
|
||||
|
||||
[Test(Description = "La macchina avanza sulle condizioni, Avanti sui passi informativi, Salta e Chiudi")]
|
||||
public static void MachineAdvancesSkipsAndCloses()
|
||||
{
|
||||
var script = new TutorialScript
|
||||
{
|
||||
Steps =
|
||||
[
|
||||
Step("intro"),
|
||||
Step("pan", new TutorialCondition { Counter = "mapPan", Increase = 0.5 }),
|
||||
Step("stations", new TutorialCondition { Counter = "stations", AtLeast = 2 }),
|
||||
Step("end"),
|
||||
],
|
||||
};
|
||||
var m = new TutorialMachine(script);
|
||||
Assert.Equal("intro", m.Current!.Id);
|
||||
Assert.False(m.Update(Facts()), "un passo informativo non si completa da solo");
|
||||
m.Next();
|
||||
Assert.Equal("pan", m.Current!.Id);
|
||||
|
||||
// la base del passo è il primo aggiornamento: lo spostamento già fatto non conta
|
||||
Assert.False(m.Update(Facts(counters: ("mapPan", 2))));
|
||||
Assert.False(m.Update(Facts(counters: ("mapPan", 2.3))));
|
||||
Assert.True(m.Update(Facts(counters: ("mapPan", 2.6))));
|
||||
Assert.Equal("stations", m.Current!.Id);
|
||||
Assert.Equal(new TutorialProgress("stations", TutorialStatus.Active), m.Progress);
|
||||
|
||||
m.Skip();
|
||||
Assert.Equal("end", m.Current!.Id);
|
||||
Assert.True(m.IsLast);
|
||||
m.Next();
|
||||
Assert.Equal(TutorialStatus.Completed, m.Status);
|
||||
Assert.Equal(null, m.Current);
|
||||
Assert.False(m.Update(Facts()));
|
||||
|
||||
m.Restart();
|
||||
Assert.Equal("intro", m.Current!.Id);
|
||||
m.Close();
|
||||
Assert.Equal(TutorialStatus.Closed, m.Status);
|
||||
Assert.Equal("closed", m.Progress.Encode());
|
||||
m.Next();
|
||||
Assert.Equal(TutorialStatus.Closed, m.Status, "chiuso, Avanti non fa nulla");
|
||||
}
|
||||
|
||||
[Test(Description = "Avanzamento salvato: codifica, ripresa, passo sparito, piano di apertura")]
|
||||
public static void ProgressRoundTripAndLaunchPlan()
|
||||
{
|
||||
foreach (var p in new[] { new TutorialProgress("depot", TutorialStatus.Active), new TutorialProgress(null, TutorialStatus.Completed), new TutorialProgress(null, TutorialStatus.Closed) })
|
||||
Assert.Equal(p, TutorialProgress.Decode(p.Encode()));
|
||||
Assert.Equal(null, TutorialProgress.Decode(""));
|
||||
Assert.Equal(null, TutorialProgress.Decode("boh"));
|
||||
|
||||
var script = RealScript();
|
||||
var m = new TutorialMachine(script);
|
||||
m.Restore(new TutorialProgress("line", TutorialStatus.Active));
|
||||
Assert.Equal("line", m.Current!.Id);
|
||||
m.Restore(new TutorialProgress("passo-che-non-esiste-piu", TutorialStatus.Active));
|
||||
Assert.Equal(script.Steps[0].Id, m.Current!.Id);
|
||||
m.Restore(new TutorialProgress(null, TutorialStatus.Completed));
|
||||
Assert.Equal(TutorialStatus.Completed, m.Status);
|
||||
|
||||
var active = new TutorialProgress("depot", TutorialStatus.Active);
|
||||
var closed = new TutorialProgress(null, TutorialStatus.Closed);
|
||||
Assert.Equal(TutorialLaunch.StartFresh, TutorialMachine.Plan(requested: true, restart: false, saved: null));
|
||||
Assert.Equal(TutorialLaunch.Hidden, TutorialMachine.Plan(requested: false, restart: false, saved: null));
|
||||
Assert.Equal(TutorialLaunch.Resume, TutorialMachine.Plan(requested: false, restart: false, saved: active));
|
||||
var completed = new TutorialProgress(null, TutorialStatus.Completed);
|
||||
Assert.Equal(TutorialLaunch.Hidden, TutorialMachine.Plan(requested: false, restart: false, saved: closed), "chiuso e non richiesto: nascosto");
|
||||
Assert.Equal(TutorialLaunch.Hidden, TutorialMachine.Plan(requested: false, restart: false, saved: completed));
|
||||
// la casella spuntata è una richiesta esplicita: vale anche su una voce chiusa (partita nuova con lo stesso seme)
|
||||
Assert.Equal(TutorialLaunch.StartFresh, TutorialMachine.Plan(requested: true, restart: false, saved: closed));
|
||||
Assert.Equal(TutorialLaunch.StartFresh, TutorialMachine.Plan(requested: true, restart: false, saved: completed));
|
||||
Assert.Equal(TutorialLaunch.Resume, TutorialMachine.Plan(requested: true, restart: false, saved: active), "in corso: si riprende");
|
||||
Assert.Equal(TutorialLaunch.StartFresh, TutorialMachine.Plan(requested: false, restart: true, saved: closed));
|
||||
Assert.Equal(TutorialLaunch.StartFresh, TutorialMachine.Plan(requested: false, restart: true, saved: active));
|
||||
}
|
||||
|
||||
[Test(Description = "La chiave della partita non cambia giocando (impronta del terreno, data) e separa le origini")]
|
||||
public static void GameKeyIsStableDuringTheGame()
|
||||
{
|
||||
var start = new WorldSummary { Seed = 1, SizeKm = 128, StartYear = 1850, RegionId = "pianura-padana", CompanyId = 0, TerrainHash = 0x1111, Tick = 0, Date = "1850-01-01" };
|
||||
// un anno dopo: le città si sono allargate (impronta del terreno nuova) e la data è avanzata
|
||||
var later = new WorldSummary { Seed = 1, SizeKm = 128, StartYear = 1850, RegionId = "pianura-padana", CompanyId = 0, TerrainHash = 0x2222, Tick = 2_000_000, Date = "1851-03-01" };
|
||||
string key = TutorialProgress.GameKey("local", start);
|
||||
Assert.Equal(key, TutorialProgress.GameKey("local", later), "stessa partita dopo un anno di gioco: stessa voce");
|
||||
Assert.True(key.All(c => char.IsAsciiLetterOrDigit(c) || c == '_'), $"chiave adatta a ConfigFile: {key}");
|
||||
Assert.Equal(key, key.ToLowerInvariant());
|
||||
|
||||
Assert.NotEqual(key, TutorialProgress.GameKey("tutorial", start), "la partita di prova del tutorial ha la sua voce");
|
||||
Assert.NotEqual(key, TutorialProgress.GameKey("remote_192.168.1.5_7400", start), "un server remoto ha la sua voce");
|
||||
Assert.NotEqual(key, TutorialProgress.GameKey("local", new WorldSummary { Seed = 2, SizeKm = 128, StartYear = 1850, RegionId = "pianura-padana" }));
|
||||
Assert.NotEqual(key, TutorialProgress.GameKey("local", new WorldSummary { Seed = 1, SizeKm = 128, StartYear = 1850, RegionId = "pianura-padana", CompanyId = 2 }));
|
||||
string remote = TutorialProgress.GameKey("remote_192.168.1.5_7400", start);
|
||||
Assert.True(remote.All(c => char.IsAsciiLetterOrDigit(c) || c == '_'), $"chiave adatta a ConfigFile: {remote}");
|
||||
}
|
||||
|
||||
[Test(Description = "Un comando riuscito subito dopo il completamento di un passo conta per il passo nuovo")]
|
||||
public static void BaselineIsTakenWhenThePreviousStepCompletes()
|
||||
{
|
||||
var build = new TutorialCondition { Counter = "cmd:BuildTrack", Increase = 1 };
|
||||
var script = new TutorialScript
|
||||
{
|
||||
Steps =
|
||||
[
|
||||
Step("profile", new TutorialCondition { Counter = "trackPreviews", Increase = 1 }),
|
||||
Step("build", build),
|
||||
Step("link", build),
|
||||
Step("end"),
|
||||
],
|
||||
};
|
||||
var m = new TutorialMachine(script);
|
||||
Assert.False(m.Update(Facts(counters: ("trackPreviews", 0))));
|
||||
Assert.True(m.Update(Facts(counters: ("trackPreviews", 1))));
|
||||
Assert.Equal("build", m.Current!.Id);
|
||||
// il binario costruito arriva prima del prossimo aggiornamento: conta per «build»
|
||||
Assert.True(m.Update(Facts(counters: [("trackPreviews", 1), ("cmd:BuildTrack", 1)])), "il primo binario completa «build»");
|
||||
Assert.Equal("link", m.Current!.Id);
|
||||
// gli stessi fatti non completano anche «link»
|
||||
Assert.False(m.Update(Facts(counters: [("trackPreviews", 1), ("cmd:BuildTrack", 1)])));
|
||||
Assert.True(m.Update(Facts(counters: [("trackPreviews", 1), ("cmd:BuildTrack", 2)])), "il secondo binario completa «link»");
|
||||
Assert.Equal("end", m.Current!.Id);
|
||||
|
||||
// dopo Salta passo la base resta il primo aggiornamento del passo
|
||||
m.Restart();
|
||||
m.Skip();
|
||||
Assert.False(m.Update(Facts(counters: ("cmd:BuildTrack", 5))));
|
||||
Assert.True(m.Update(Facts(counters: ("cmd:BuildTrack", 6))));
|
||||
}
|
||||
|
||||
[Test(Description = "La validazione rifiuta copioni sbagliati e il parser i campi sconosciuti")]
|
||||
public static void ValidationRejectsBadScripts()
|
||||
{
|
||||
static List<string> Errors(params TutorialStep[] steps) => new TutorialScript { Steps = [.. steps] }.Validate();
|
||||
|
||||
Assert.True(Errors(Step("a"), Step("a")).Exists(e => e.Contains("ripetuto")));
|
||||
Assert.True(Errors(Step("a", new TutorialCondition { Counter = "binari", AtLeast = 1 })).Exists(e => e.Contains("contatore sconosciuto")));
|
||||
Assert.True(Errors(Step("a", new TutorialCondition { Counter = "cmd:Teletrasporto", Increase = 1 })).Exists(e => e.Contains("contatore sconosciuto")));
|
||||
Assert.True(Errors(Step("a", new TutorialCondition { Counter = "cmd:5", Increase = 1 })).Exists(e => e.Contains("contatore sconosciuto")));
|
||||
Assert.True(Errors(Step("a", new TutorialCondition { Counter = "stations" })).Exists(e => e.Contains("senza atLeast")));
|
||||
Assert.True(Errors(Step("a", new TutorialCondition { Panel = "cucina" })).Exists(e => e.Contains("pannello sconosciuto")));
|
||||
Assert.True(Errors(Step("a", new TutorialCondition { Panel = "market", Counter = "stations", AtLeast = 1 })).Exists(e => e.Contains("una sola forma")));
|
||||
Assert.True(Errors(Step("a", new TutorialCondition { All = [] })).Exists(e => e.Contains("vuoto")));
|
||||
Assert.True(Errors(Step("a", highlight: "toolbar:cucina")).Exists(e => e.Contains("evidenziare sconosciuto")));
|
||||
Assert.True(Errors().Exists(e => e.Contains("nessun passo")));
|
||||
// valori null ammessi dal JSON: errori chiari, nessuna eccezione
|
||||
Assert.True(TutorialScript.Parse("""{ "steps": null }""").Validate().Exists(e => e.Contains("elenco dei passi mancante")));
|
||||
Assert.True(TutorialScript.Parse("""{ "steps": [ null ] }""").Validate().Exists(e => e.Contains("passo n. 1 nullo")));
|
||||
Assert.True(TutorialScript.Parse("""{ "steps": [ { "id": "a", "title": "t", "text": "x", "done": { "all": [ null ] } } ] }""").Validate().Exists(e => e.Contains("condizione nulla")));
|
||||
Assert.True(TutorialScript.Parse("""{ "steps": [ { "id": "a", "title": "t", "text": "x", "done": { "any": [ null ] } } ] }""").Validate().Exists(e => e.Contains("condizione nulla")));
|
||||
Assert.Equal(0, Errors(Step("a", new TutorialCondition { Counter = TutorialFacts.CommandCounter(CommandType.BuildStation), Increase = 1 }, "toolbar:station")).Count);
|
||||
|
||||
Assert.Throws<System.Text.Json.JsonException>(() => TutorialScript.Parse("""{ "steps": [ { "id": "a", "title": "t", "text": "x", "colore": "rosso" } ] }"""));
|
||||
Assert.Throws<System.Text.Json.JsonException>(() => TutorialScript.Parse("""{ "steps": [ { "id": "a", "text": "x" } ] }"""));
|
||||
}
|
||||
|
||||
[Test(Description = "Una prima partita simulata con fatti plausibili percorre tutto il copione reale")]
|
||||
public static void FirstGameWalksTheWholeScript()
|
||||
{
|
||||
var script = RealScript();
|
||||
var m = new TutorialMachine(script);
|
||||
var f = new TutorialFacts();
|
||||
int guard = 0;
|
||||
void Tick() => m.Update(f);
|
||||
|
||||
while (m.Status == TutorialStatus.Active && guard++ < 200)
|
||||
{
|
||||
var step = m.Current!;
|
||||
Tick();
|
||||
if (step.IsInformative)
|
||||
{
|
||||
m.Next();
|
||||
continue;
|
||||
}
|
||||
// il giocatore fa ciò che il passo chiede; il client osserva soltanto gli effetti
|
||||
switch (step.Id)
|
||||
{
|
||||
case "map": f.Add("mapPan", 0.8); f.Add("mapZoom", 0.6); break;
|
||||
case "time": f.Add("speedChanges", 1); break;
|
||||
case "stations": f.Add(TutorialFacts.CommandCounter(CommandType.BuildStation), 2); f.Set("stations", 2); break;
|
||||
case "depot": f.Set("depots", 1); break;
|
||||
case "track-tool": f.Panel = "track"; break;
|
||||
case "track-profile": f.Add("trackPreviews", 12); break;
|
||||
case "track-build" or "depot-link": f.Add(TutorialFacts.CommandCounter(CommandType.BuildTrack), 1); f.Add("edges", 1); f.Add("edgesBuilding", 1); break;
|
||||
case "construction": f.Set("edgesBuilding", 0); f.Set("edgesActive", f.Get("edges")); break;
|
||||
case "locomotive": f.Panel = "trains"; f.Set("locomotives", 1); break;
|
||||
case "cars": f.Set("cars", 3); break;
|
||||
case "compose": f.Set("trains", 1); break;
|
||||
case "line": f.Panel = "lines"; f.Set("lines", 1); break;
|
||||
case "assign": f.Panel = "trains"; f.Set("trainsOnLine", 1); break;
|
||||
default: f.Panel = step.Done!.Panel ?? f.Panel; break;
|
||||
}
|
||||
int before = m.Index;
|
||||
Tick();
|
||||
Assert.True(m.Index == before + 1 || m.Status != TutorialStatus.Active, $"il passo «{step.Id}» non si è completato");
|
||||
}
|
||||
Assert.Equal(TutorialStatus.Completed, m.Status);
|
||||
}
|
||||
|
||||
/// <summary>CSV minimo (virgolette doppie, virgole tra virgolette), come lo legge Godot.</summary>
|
||||
private static Dictionary<string, string[]> ReadCsv(string path)
|
||||
{
|
||||
var rows = new Dictionary<string, string[]>(StringComparer.Ordinal);
|
||||
foreach (string line in File.ReadAllLines(path, Encoding.UTF8).Skip(1))
|
||||
{
|
||||
if (line.Length == 0) continue;
|
||||
var fields = new List<string>();
|
||||
var sb = new StringBuilder();
|
||||
bool quoted = false;
|
||||
for (int i = 0; i < line.Length; i++)
|
||||
{
|
||||
char c = line[i];
|
||||
if (quoted)
|
||||
{
|
||||
if (c == '"' && i + 1 < line.Length && line[i + 1] == '"') { sb.Append('"'); i++; }
|
||||
else if (c == '"') quoted = false;
|
||||
else sb.Append(c);
|
||||
}
|
||||
else if (c == '"') quoted = true;
|
||||
else if (c == ',') { fields.Add(sb.ToString()); sb.Clear(); }
|
||||
else sb.Append(c);
|
||||
}
|
||||
fields.Add(sb.ToString());
|
||||
rows[fields[0]] = [.. fields];
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,456 @@
|
||||
using System.Text.Json.Nodes;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Persistence;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Scenarios;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
using RailEnterprise.Protocol;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using RailEnterprise.Server;
|
||||
using RailEnterprise.Tests.Harness;
|
||||
using RailEnterprise.Tests.Rail;
|
||||
using RailEnterprise.Tests.Scenarios;
|
||||
using RailEnterprise.Tests.Server;
|
||||
|
||||
namespace RailEnterprise.Tests.Economy;
|
||||
|
||||
/// <summary>
|
||||
/// Tooltip «perché» (F6, issue #44, ADR 0024): ogni spiegazione dà lo stesso numero del motore e i suoi
|
||||
/// termini lo ricompongono con la formula dichiarata; le spiegazioni non cambiano il mondo, viaggiano nel
|
||||
/// protocollo e il server le manda su richiesta.
|
||||
/// </summary>
|
||||
public static class ExplanationTests
|
||||
{
|
||||
private static int GoodIndex(World w, string id) => w.Data.Goods.First(g => g.Id == id).Index;
|
||||
|
||||
/// <summary>Valdoria con la linea merci miniera → acciaieria, un treno e 40 giorni di servizio.</summary>
|
||||
private static (RailFixture F, int Line, int Train) ServedValdoria(int days = 40)
|
||||
{
|
||||
var f = RailFixture.Valdoria();
|
||||
var (mine, mill, depot) = f.BuildFreightNetwork();
|
||||
int train = f.Train(depot, "Merci 1", ("loco_steam_1850", 1), ("wagon_hopper", 4));
|
||||
int line = f.Ok(new CreateLineCommand("Linea 1", "#e0a526", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) }));
|
||||
f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
|
||||
f.W.RunDays(days);
|
||||
return (f, line, train);
|
||||
}
|
||||
|
||||
private static double V(Explanation e, string symbol)
|
||||
{
|
||||
var t = e.Term(symbol);
|
||||
Assert.True(t is not null, $"{e.Title}: manca il termine {symbol}");
|
||||
return t!.Value;
|
||||
}
|
||||
|
||||
private static void Available(Explanation e)
|
||||
{
|
||||
Assert.True(e.Available, $"{e.Title} disponibile");
|
||||
Assert.True(e.Title.Length > 0 && e.Formula.Length > 0, $"{e.Title}: titolo e formula");
|
||||
}
|
||||
|
||||
[Test(Description = "Prezzo globale: valore uguale al motore per ogni bene e termini che ricompongono il passo α·Pg′ + (1 − α)·Pg₋₁; anche dopo un caricamento")]
|
||||
public static void GlobalPriceMatchesTheMarketStep()
|
||||
{
|
||||
var (f, _, _) = ServedValdoria();
|
||||
var w = f.W;
|
||||
void Check(World world, string when)
|
||||
{
|
||||
int stepped = 0;
|
||||
for (int g = 0; g < world.Data.GoodCount; g++)
|
||||
{
|
||||
var e = Explanations.GlobalPrice(world, new ExplainTarget(ExplainSubject.GlobalPrice, g));
|
||||
Available(e);
|
||||
Assert.Equal(world.Market.GlobalPrice[g], e.Value, $"{when}: prezzo di {world.Data.Goods[g].Id}");
|
||||
if (e.Term("Pg′") is null) continue;
|
||||
stepped++;
|
||||
double prev = V(e, "Pg₋₁"), target = V(e, "Pg′"), alpha = V(e, "α");
|
||||
Assert.Equal(e.Value, alpha * target + (1 - alpha) * prev, $"{when}: passo del prezzo di {world.Data.Goods[g].Id}");
|
||||
Assert.Equal(target, DMath.Clamp(prev * (1 + V(e, "k") * (V(e, "D/S") - 1)), V(e, "Pmin"), V(e, "Pmax")), $"{when}: prezzo obiettivo");
|
||||
Assert.True(V(e, "D") >= 0 && V(e, "S") >= 0 && V(e, "V") > 0, $"{when}: domanda, offerta e volume mondiale");
|
||||
// il rapporto viene da D, S e dagli scambi con il mondo: Dtot = D + V·(Pw/Pg₋₁)^η, Stot = S + V·(Pg₋₁/Pw)^η
|
||||
double pw = V(e, "Pw"), v = V(e, "V"), eta = V(e, "η");
|
||||
Assert.Equal(V(e, "D") + v * DMath.Pow(pw / prev, eta), V(e, "Dtot"), $"{when}: domanda con il mondo");
|
||||
Assert.Equal(V(e, "S") + v * DMath.Pow(prev / pw, eta), V(e, "Stot"), $"{when}: offerta con il mondo");
|
||||
Assert.Equal(DMath.Clamp(V(e, "Dtot") / Math.Max(1e-9, V(e, "Stot")), V(e, "rmin"), V(e, "rmax")), V(e, "D/S"), $"{when}: rapporto limitato");
|
||||
}
|
||||
Assert.True(stepped > 0, $"{when}: almeno un bene in commercio");
|
||||
}
|
||||
Check(w, "dopo 40 giorni");
|
||||
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
||||
Check(loaded, "dopo il caricamento");
|
||||
loaded.RunTicks(7);
|
||||
Check(loaded, "a metà giornata");
|
||||
|
||||
// prima del primo passo il prezzo è quello base
|
||||
var fresh = RailFixture.Valdoria().W;
|
||||
var e0 = Explanations.GlobalPrice(fresh, new ExplainTarget(ExplainSubject.GlobalPrice, 0));
|
||||
Assert.Equal((double)fresh.Data.Goods[0].BasePrice, e0.Value);
|
||||
Assert.Equal((double)fresh.Data.Goods[0].BasePrice, V(e0, "Pb"));
|
||||
}
|
||||
|
||||
[Test(Description = "Prezzo locale: al consumatore e al produttore lo stesso numero di TradingMath e della vendita, con Pl = Pg·clamp(1 + λ·squilibrio)")]
|
||||
public static void LocalPriceMatchesTradingMath()
|
||||
{
|
||||
var (f, _, _) = ServedValdoria();
|
||||
var w = f.W;
|
||||
var lp = w.Data.Balance.LocalPrice;
|
||||
int ore = GoodIndex(w, "iron_ore");
|
||||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
var mine = w.Industries.First(i => i.Def.Id == "iron_mine");
|
||||
var buyer = Explanations.LocalPrice(w, new ExplainTarget(ExplainSubject.LocalPrice, ore, steel.Id.Value));
|
||||
Available(buyer);
|
||||
int input = steel.InputIndexOf(ore);
|
||||
Assert.Equal(TradingMath.ConsumerPrice(w, steel, input, steel.InputStock[input]), buyer.Value);
|
||||
var seller = Explanations.LocalPrice(w, new ExplainTarget(ExplainSubject.LocalPrice, ore, mine.Id.Value));
|
||||
int output = mine.OutputIndexOf(ore);
|
||||
Assert.Equal(TradingMath.ProducerPrice(w, mine, output, mine.OutputStock[output]), seller.Value);
|
||||
foreach (var e in new[] { buyer, seller })
|
||||
{
|
||||
double dl = V(e, "Dl"), sl = V(e, "Sl");
|
||||
double imbalance = (dl - sl) / (dl + sl + V(e, "ε"));
|
||||
Assert.Equal(imbalance, V(e, "(Dl − Sl)/(Dl + Sl + ε)"));
|
||||
double factor = Math.Clamp(1 + V(e, "λ") * imbalance, 1 - V(e, "δ"), 1 + V(e, "δ"));
|
||||
Assert.Equal(factor, V(e, "f"));
|
||||
Assert.Equal(e.Value, V(e, "Pg") * factor);
|
||||
Assert.Equal(w.Market.GlobalPrice[ore], V(e, "Pg"));
|
||||
}
|
||||
Assert.Equal(lp.Lambda, V(buyer, "λ"));
|
||||
// nessun prezzo locale per un bene che l'industria non tratta
|
||||
var none = Explanations.LocalPrice(w, new ExplainTarget(ExplainSubject.LocalPrice, GoodIndex(w, "grain"), mine.Id.Value));
|
||||
Assert.False(none.Available);
|
||||
}
|
||||
|
||||
[Test(Description = "Tariffe di una linea: merci e passeggeri uguali a Tariffs del motore, termini che le ricompongono e tf a due volte il tempo atteso")]
|
||||
public static void TariffsMatchTheEngine()
|
||||
{
|
||||
var (f, lineId, trainId) = ServedValdoria();
|
||||
var w = f.W;
|
||||
var t = w.Data.Balance.Tariffs;
|
||||
int ore = GoodIndex(w, "iron_ore");
|
||||
var line = w.Lines[lineId];
|
||||
var stretch = Explanations.Stretch(w, line)!.Value;
|
||||
double km = Vec2.Distance(stretch.From.Position, stretch.To.Position) / 1000;
|
||||
var freight = Explanations.FreightTariff(w, new ExplainTarget(ExplainSubject.FreightTariff, lineId, ore), f.Me);
|
||||
Available(freight);
|
||||
double expected = V(freight, "giorni");
|
||||
Assert.True(expected > 0, "la linea porta il minerale: tempo atteso noto");
|
||||
Assert.Equal(km, V(freight, "km"));
|
||||
var def = w.Data.Goods[ore];
|
||||
Assert.Equal((double)Tariffs.Freight(1, km, w.Market.GlobalPrice[ore], def.BasePrice, expected, expected, t, w.Difficulty.TariffMultiplier).Cents, freight.Value);
|
||||
double priceFactor = V(freight, "a") + V(freight, "b") * V(freight, "Pg") / V(freight, "Pb");
|
||||
Assert.Equal(priceFactor, V(freight, "a + b·Pg/Pb"));
|
||||
Assert.Equal(DMath.Pow(km, V(freight, "e")), V(freight, "km^e"));
|
||||
Assert.Equal(1.0, V(freight, "tf"));
|
||||
double cents = V(freight, "u") * V(freight, "Tb") * priceFactor * V(freight, "km^e") * V(freight, "tf") * V(freight, "d");
|
||||
Assert.Equal((double)Money.FromCentsRounded(cents).Cents, freight.Value);
|
||||
Assert.Equal(Tariffs.LatenessFactor(2 * expected, expected, t), V(freight, "tf 2×"));
|
||||
Assert.True(V(freight, "tariffa 2×") < freight.Value, "in ritardo la tariffa scende");
|
||||
|
||||
var pax = Explanations.PassengerTariff(w, new ExplainTarget(ExplainSubject.PassengerTariff, lineId, 0), f.Me);
|
||||
Available(pax);
|
||||
double comfort = Fleet.Comfort(w, w.Trains[trainId], PaxClass.Worker);
|
||||
Assert.Equal(comfort, V(pax, "comfort"));
|
||||
double paxDays = V(pax, "giorni");
|
||||
var engine = Tariffs.Passenger(1, km, PaxClass.Worker, paxDays, paxDays, t, w.Difficulty.TariffMultiplier) * comfort;
|
||||
Assert.Equal((double)engine.Cents, pax.Value);
|
||||
double paxCents = V(pax, "p") * V(pax, "Tp") * V(pax, "km^e") * V(pax, "classe") * V(pax, "tf") * V(pax, "d");
|
||||
Assert.Equal((double)Money.FromCentsRounded(paxCents).Cents, V(pax, "senza comfort"));
|
||||
Assert.Equal(pax.Value, (double)(new Money((long)V(pax, "senza comfort")) * V(pax, "comfort")).Cents);
|
||||
var staff = Explanations.PassengerTariff(w, new ExplainTarget(ExplainSubject.PassengerTariff, lineId, 1), f.Me);
|
||||
Assert.Equal(t.ClassMultipliers["staff"], V(staff, "classe"));
|
||||
Assert.False(Explanations.FreightTariff(w, new ExplainTarget(ExplainSubject.FreightTariff, 999, ore), f.Me).Available, "linea inesistente");
|
||||
// la linea di un'altra compagnia non si spiega (tempi attesi e comfort sono della sua rete)
|
||||
var rival = new CompanyId(f.Me.Value + 1);
|
||||
Assert.False(Explanations.Build(w, rival, new ExplainTarget(ExplainSubject.FreightTariff, lineId, ore)).Available, "tariffa merci di una linea altrui");
|
||||
Assert.False(Explanations.Build(w, rival, new ExplainTarget(ExplainSubject.PassengerTariff, lineId, 0)).Available, "tariffa passeggeri di una linea altrui");
|
||||
Assert.False(Explanations.Build(w, CompanyId.None, new ExplainTarget(ExplainSubject.FreightTariff, lineId, ore)).Available, "spettatore");
|
||||
}
|
||||
|
||||
[Test(Description = "Efficienza dell'industria: i termini dell'ultima produzione ricompongono ind.Efficiency; dopo un caricamento arrivano con il giorno dopo")]
|
||||
public static void IndustryEfficiencyMatchesProduction()
|
||||
{
|
||||
var (f, _, _) = ServedValdoria();
|
||||
var w = f.W;
|
||||
foreach (var ind in w.Industries.Where(i => !i.Closed))
|
||||
{
|
||||
var e = Explanations.IndustryEfficiency(w, new ExplainTarget(ExplainSubject.IndustryEfficiency, ind.Id.Value));
|
||||
Available(e);
|
||||
Assert.Equal(ind.Efficiency, e.Value, ind.Name);
|
||||
// ritmo del lavoro: min(cL, cP) × pf × mc, zero solo se l'industria era ferma
|
||||
double labour = Math.Min(V(e, "cL"), V(e, "cP")) * V(e, "pf") * V(e, "mc");
|
||||
if (V(e, "lavoro") != 0 || labour == 0) Assert.Equal(labour, V(e, "lavoro"), $"{ind.Name}: ritmo del lavoro");
|
||||
else Assert.True(e.Notes.Count > 0, $"{ind.Name}: ferma, lo dice la nota");
|
||||
Assert.Equal(e.Value, V(e, "lavoro") * V(e, "cI") * V(e, "g") * V(e, "ev"), $"{ind.Name}: prodotto dei fattori");
|
||||
// la condizione mostrata è quella da cui viene mc, non quella dopo la manutenzione dello stesso tick
|
||||
Assert.Equal(IndustryMath.ConditionMultiplier(V(e, "condizione"), w.Data.Balance.IndustryMaintenance), V(e, "mc"), $"{ind.Name}: mc dalla condizione");
|
||||
}
|
||||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
Assert.Equal(IndustryOutlook.Build(w, steel, f.Me).Efficiency, Explanations.IndustryEfficiency(w, new ExplainTarget(ExplainSubject.IndustryEfficiency, steel.Id.Value)).Value,
|
||||
"lo stesso numero della scheda");
|
||||
|
||||
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
||||
var after = Explanations.IndustryEfficiency(loaded, new ExplainTarget(ExplainSubject.IndustryEfficiency, steel.Id.Value));
|
||||
Assert.Equal(steel.Efficiency, after.Value, "valore salvato");
|
||||
Assert.Equal(0, after.Terms.Count);
|
||||
Assert.Equal(1, after.Notes.Count);
|
||||
loaded.RunDays(1);
|
||||
var next = Explanations.IndustryEfficiency(loaded, new ExplainTarget(ExplainSubject.IndustryEfficiency, steel.Id.Value));
|
||||
Assert.True(next.Terms.Count > 0, "termini della produzione del giorno dopo");
|
||||
Assert.Equal(loaded.Industries[steel.Id.Value].Efficiency, next.Value);
|
||||
}
|
||||
|
||||
[Test(Description = "Punteggio di crescita e crescita delle città: le stesse funzioni del motore e i pesi che ricompongono il valore")]
|
||||
public static void GrowthMatchesTheEngine()
|
||||
{
|
||||
var (f, _, _) = ServedValdoria();
|
||||
var w = f.W;
|
||||
var g = w.Data.Balance.Growth;
|
||||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
var e = Explanations.IndustryGrowth(w, new ExplainTarget(ExplainSubject.IndustryGrowth, steel.Id.Value));
|
||||
Available(e);
|
||||
Assert.Equal(IndustryMath.GrowthScore(steel, g).Score, e.Value);
|
||||
Assert.Equal(IndustryOutlook.Build(w, steel, f.Me).Growth.Current.Score, e.Value, "lo stesso numero della scheda");
|
||||
Assert.Equal(e.Value, V(e, "ws") * V(e, "quota") + V(e, "wc") * V(e, "copertura") + V(e, "wr") * V(e, "redditività"));
|
||||
Assert.Equal(Math.Clamp((steel.Margin + 1) / 2, 0, 1), V(e, "redditività"));
|
||||
|
||||
var tb = w.Data.Balance.Town;
|
||||
foreach (var town in w.Towns)
|
||||
{
|
||||
var t = Explanations.TownGrowth(w, new ExplainTarget(ExplainSubject.TownGrowth, town.Id.Value));
|
||||
Available(t);
|
||||
Assert.Equal(TownSystem.GrowthOf(town, tb).Growth, t.Value, town.Name);
|
||||
double raw = V(t, "g₀") + V(t, "ws") * (V(t, "s") - V(t, "s₀")) + V(t, "wo") * (V(t, "o") - V(t, "o₀"));
|
||||
Assert.Equal(raw, V(t, "g grezza"), $"{town.Name}: crescita grezza");
|
||||
Assert.Equal(t.Value, Math.Clamp(raw, -V(t, "gmax"), V(t, "gmax")), $"{town.Name}: limite");
|
||||
Assert.Equal(town.LastGrowth, V(t, "ultimo mese"));
|
||||
}
|
||||
}
|
||||
|
||||
[Test(Description = "Condizione del treno: il componente più debole, il rischio di guasto del controllo giornaliero con 1/h e la stima del pianificatore")]
|
||||
public static void TrainConditionMatchesTheFleet()
|
||||
{
|
||||
var (f, _, trainId) = ServedValdoria(120);
|
||||
var w = f.W;
|
||||
var train = w.Trains[trainId];
|
||||
var e = Explanations.TrainCondition(w, new ExplainTarget(ExplainSubject.TrainCondition, trainId), f.Me);
|
||||
Available(e);
|
||||
Assert.Equal(Fleet.TrainCondition(w, train), e.Value);
|
||||
Assert.Equal(e.Value, V(e, "c"));
|
||||
var fp = w.Data.Maintenance.Failure;
|
||||
double c = V(e, "c rischio");
|
||||
double h = c < V(e, "c₀") ? V(e, "h₀") * DMath.Exp(V(e, "k") * (V(e, "c₀") - c) / V(e, "σ")) : V(e, "h₀") / V(e, "div");
|
||||
Assert.Equal(Fleet.Hazard(c, fp), h);
|
||||
Assert.Equal(h * V(e, "ispezione"), V(e, "h"));
|
||||
Assert.Equal(Fleet.DailyHazard(w, train, w.Clock.Day).Hazard, V(e, "h"));
|
||||
Assert.Equal(1 / V(e, "h"), V(e, "1/h"));
|
||||
Assert.Equal(Fleet.Dues(w, train).Condition, V(e, "stima"), "stima del pianificatore");
|
||||
Stima(e);
|
||||
|
||||
// la stima viene dal componente con meno giorni all'obiettivo, non dal più debole: freni a 60 che calano
|
||||
// di 2 al giorno contro il motore a 55 che cala di 0,1
|
||||
var loco = w.Vehicles[train.Vehicles[0].Value];
|
||||
var comps = Fleet.ComponentsOf(w.Data, loco.Def);
|
||||
int brakes = Fleet.ComponentIndex(comps, Fleet.Brakes), engine = Fleet.ComponentIndex(comps, Fleet.Engine);
|
||||
Assert.True(brakes >= 0 && engine >= 0, "la locomotiva ha freni e motore");
|
||||
foreach (var id in train.Vehicles)
|
||||
{
|
||||
var v = w.Vehicles[id.Value];
|
||||
for (int j = 0; j < v.Components.Length; j++)
|
||||
{
|
||||
v.Components[j] = 90;
|
||||
if (j < v.WearEma.Length) v.WearEma[j] = 0.01;
|
||||
}
|
||||
}
|
||||
loco.Components[brakes] = 60;
|
||||
loco.WearEma[brakes] = 2;
|
||||
loco.Components[engine] = 55;
|
||||
loco.WearEma[engine] = 0.1;
|
||||
var split = Explanations.TrainCondition(w, new ExplainTarget(ExplainSubject.TrainCondition, trainId), f.Me);
|
||||
Assert.Equal(55.0, V(split, "c"), "il più debole è il motore");
|
||||
Assert.Equal(Fleet.Engine, split.Term("c")!.Text);
|
||||
Assert.Equal(60.0, V(split, "cs"), "la stima viene dai freni");
|
||||
Assert.Equal(Fleet.Brakes, split.Term("cs")!.Text);
|
||||
Assert.Equal(2.0, V(split, "usura"));
|
||||
Assert.Equal(Fleet.Dues(w, train).Condition, V(split, "stima"));
|
||||
Stima(split);
|
||||
|
||||
// un treno di un'altra compagnia non si spiega
|
||||
var other = Explanations.Build(w, new CompanyId(f.Me.Value + 1), new ExplainTarget(ExplainSubject.TrainCondition, trainId));
|
||||
Assert.False(other.Available);
|
||||
}
|
||||
|
||||
/// <summary>La stima del pianificatore ricomposta dai termini: (cs − obiettivo)/usura − margine, −margine all'obiettivo.</summary>
|
||||
private static void Stima(Explanation e)
|
||||
{
|
||||
if (e.Term("stima") is null) return;
|
||||
double cs = V(e, "cs"), target = V(e, "obiettivo"), margin = V(e, "margine");
|
||||
double expected = cs <= target ? -margin : (cs - target) / V(e, "usura") - margin;
|
||||
Assert.Equal(expected, V(e, "stima"), "stima ricomposta dai termini");
|
||||
}
|
||||
|
||||
[Test(Description = "Valore del veicolo: valore di libro e rivendita di Obsolescence, con la curva del residuo nuovo e superato")]
|
||||
public static void VehicleValueMatchesObsolescence()
|
||||
{
|
||||
var json = JsonNode.Parse(File.ReadAllText(ScenarioHelper.PathOf("valdoria")))!;
|
||||
json["startYear"] = 1878;
|
||||
var s = ScenarioLoader.Load(TestData.Data, json.ToJsonString());
|
||||
var f = new RailFixture(s.World, s);
|
||||
var w = f.W;
|
||||
int depot = f.Ok(new BuildDepotCommand(RailFixture.K(2.6, 4.4), "small", "Deposito di prova"));
|
||||
int old = f.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1)).Created[0];
|
||||
int fresh = f.Do(new BuyVehicleCommand("loco_steam_1878", new DepotId(depot), 1)).Created[0];
|
||||
w.RunDays(400);
|
||||
var floor = w.Data.Balance.Finance.BookValueFloor;
|
||||
foreach (int id in new[] { old, fresh })
|
||||
{
|
||||
var v = w.Vehicles[id];
|
||||
var e = Explanations.VehicleValue(w, new ExplainTarget(ExplainSubject.VehicleValue, id), f.Me);
|
||||
Available(e);
|
||||
Assert.Equal((double)Obsolescence.BookValueCents(w, v), e.Value, v.Def.Id);
|
||||
Assert.Equal((double)Obsolescence.ResaleValue(w, v).Cents, V(e, "rivendita"));
|
||||
double r = e.Term("perdita") is null
|
||||
? Math.Max(floor, 1 - V(e, "età") / V(e, "vita"))
|
||||
: Math.Max(floor, (1 - V(e, "perdita")) * (1 - (V(e, "età") + (V(e, "velocità") - 1) * V(e, "anni superato")) / V(e, "vita")));
|
||||
Assert.Equal(V(e, "r"), r, $"{v.Def.Id}: residuo");
|
||||
Assert.Equal(e.Value, (double)(long)(V(e, "prezzo") * r), $"{v.Def.Id}: valore di libro");
|
||||
Assert.Equal(V(e, "rivendita"), (double)(new Money((long)V(e, "prezzo")) * (r * V(e, "condizione"))).Cents, $"{v.Def.Id}: rivendita");
|
||||
}
|
||||
var superseded = Explanations.VehicleValue(w, new ExplainTarget(ExplainSubject.VehicleValue, old), f.Me);
|
||||
Assert.True(superseded.Term("perdita") is not null, "il modello del 1850 è superato");
|
||||
Assert.Equal("loco_steam_1878", w.Data.Vehicles.First(d => d.NameIt == superseded.Term("successore")!.Text).Id);
|
||||
Assert.True(Explanations.VehicleValue(w, new ExplainTarget(ExplainSubject.VehicleValue, fresh), f.Me).Term("perdita") is null, "il modello del 1878 non è superato");
|
||||
}
|
||||
|
||||
[Test(Description = "Rating, avanzamento del livello e cassa: gli stessi numeri di FinanceOutlook, ClimbOutlook e della compagnia, ricomposti dai termini")]
|
||||
public static void CompanyValuesMatchTheOutlooks()
|
||||
{
|
||||
var (f, _, _) = ServedValdoria(75);
|
||||
var w = f.W;
|
||||
var c = w.Company(f.Me);
|
||||
var rating = Explanations.Build(w, f.Me, new ExplainTarget(ExplainSubject.Rating));
|
||||
Available(rating);
|
||||
var explain = FinanceOutlook.Explain(w, c);
|
||||
Assert.Equal(explain.Score, rating.Value);
|
||||
Assert.Equal(c.Rating.ToString(), rating.ValueText);
|
||||
Assert.Equal(FinanceSystem.MarginComponent(V(rating, "margine")), V(rating, "cm"));
|
||||
Assert.Equal(FinanceSystem.LeverageComponent(V(rating, "leva")), V(rating, "cl"));
|
||||
Assert.Equal(rating.Value, V(rating, "pm") * V(rating, "cm") + V(rating, "pl") * V(rating, "cl"));
|
||||
|
||||
var tier = Explanations.Build(w, f.Me, new ExplainTarget(ExplainSubject.TierProgress));
|
||||
Available(tier);
|
||||
var req = ClimbOutlook.Requirements(w, c, w.Data.Tiers.Tiers[c.Tier]);
|
||||
Assert.Equal(req.Progress, tier.Value);
|
||||
Assert.Equal(DMath.Clamp(V(tier, "patrimonio") / V(tier, "soglia"), 0, 1), V(tier, "fP"));
|
||||
Assert.Equal(DMath.Clamp(V(tier, "città") / V(tier, "richieste"), 0, 1), V(tier, "fC"));
|
||||
double progress = (V(tier, "fP") + V(tier, "fC") + V(tier, "fR")) / 3;
|
||||
if (!(req.NetWorthMet && req.TownsMet && req.RatingMet)) progress = Math.Min(progress, V(tier, "tetto"));
|
||||
Assert.Equal(tier.Value, progress);
|
||||
|
||||
var cash = Explanations.Build(w, f.Me, new ExplainTarget(ExplainSubject.Cash));
|
||||
Available(cash);
|
||||
Assert.Equal((double)c.Cash.Cents, cash.Value);
|
||||
Assert.Equal(V(cash, "flusso"), V(cash, "ricavi") + V(cash, "costi") + V(cash, "capitale"));
|
||||
Assert.Equal(cash.Value, V(cash, "inizio") + V(cash, "flusso"));
|
||||
Assert.True(V(cash, "ricavi") > 0, "la linea incassa noli nel mese");
|
||||
}
|
||||
|
||||
[Test(Description = "Le spiegazioni non cambiano il mondo e si proiettano nel protocollo (ExplanationReport) senza perdere nulla; RequestDetail porta il bersaglio nel blocco 1")]
|
||||
public static void ExplanationsAreReadOnlyAndRoundTrip()
|
||||
{
|
||||
var (f, line, train) = ServedValdoria();
|
||||
var w = f.W;
|
||||
int ore = GoodIndex(w, "iron_ore");
|
||||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
int vehicle = w.Trains[train].Vehicles[0].Value;
|
||||
var targets = new[]
|
||||
{
|
||||
new ExplainTarget(ExplainSubject.GlobalPrice, ore), new ExplainTarget(ExplainSubject.LocalPrice, ore, steel.Id.Value),
|
||||
new ExplainTarget(ExplainSubject.FreightTariff, line, ore), new ExplainTarget(ExplainSubject.PassengerTariff, line, 1),
|
||||
new ExplainTarget(ExplainSubject.IndustryEfficiency, steel.Id.Value), new ExplainTarget(ExplainSubject.IndustryGrowth, steel.Id.Value),
|
||||
new ExplainTarget(ExplainSubject.TownGrowth, 0), new ExplainTarget(ExplainSubject.TrainCondition, train),
|
||||
new ExplainTarget(ExplainSubject.Rating), new ExplainTarget(ExplainSubject.TierProgress),
|
||||
new ExplainTarget(ExplainSubject.VehicleValue, vehicle), new ExplainTarget(ExplainSubject.Cash),
|
||||
};
|
||||
Assert.Equal(Enum.GetValues<ExplainSubject>().Length - 1, targets.Length, "un bersaglio per ogni soggetto");
|
||||
ulong hash = StateHasher.Compute(w);
|
||||
foreach (var target in targets)
|
||||
{
|
||||
var e = Explanations.Build(w, f.Me, target);
|
||||
Available(e);
|
||||
Assert.True(e.Terms.Count > 0 || e.Notes.Count > 0, $"{target.Subject}: termini o note");
|
||||
var report = Projection.Explanation(w, f.Me, (byte)target.Subject, target.A, target.B);
|
||||
var back = (ExplanationReport)Frame.Decode(Frame.Encode(report));
|
||||
Assert.Equal((byte)target.Subject, back.Subject);
|
||||
Assert.Equal(target.A, back.Target);
|
||||
Assert.Equal(target.B, back.Arg);
|
||||
Assert.Equal(e.Value, back.Value, $"{target.Subject}: valore");
|
||||
Assert.Equal(e.Title, back.Title);
|
||||
Assert.Equal(e.Formula, back.Formula);
|
||||
Assert.Equal(e.ValueText, back.ValueText);
|
||||
Assert.Equal((byte)e.Unit, back.Unit);
|
||||
Assert.Equal(e.Terms.Count, back.Terms.Count);
|
||||
for (int i = 0; i < e.Terms.Count; i++)
|
||||
{
|
||||
Assert.Equal(e.Terms[i].Symbol, back.Terms[i].Symbol);
|
||||
Assert.Equal(e.Terms[i].Label, back.Terms[i].Label);
|
||||
Assert.Equal(e.Terms[i].Value, back.Terms[i].Value);
|
||||
Assert.Equal((byte)e.Terms[i].Unit, back.Terms[i].Unit);
|
||||
Assert.Equal(e.Terms[i].Text, back.Terms[i].Text);
|
||||
}
|
||||
Assert.SequenceEqual(e.Notes, back.Notes);
|
||||
}
|
||||
Assert.Equal(hash, StateHasher.Compute(w), "le spiegazioni non cambiano il mondo");
|
||||
var missing = Projection.Explanation(w, f.Me, (byte)ExplainSubject.IndustryEfficiency, 9999, -1);
|
||||
Assert.False(missing.Available);
|
||||
|
||||
// richiesta: il bersaglio viaggia nel blocco 1; una richiesta senza blocco si legge con soggetto 0
|
||||
var request = (RequestDetail)Frame.Decode(Frame.Encode(new RequestDetail { Kind = DetailKind.Explain, Target = 4, Subject = (byte)ExplainSubject.LocalPrice, Arg = 9 }));
|
||||
Assert.Equal(DetailKind.Explain, request.Kind);
|
||||
Assert.Equal(4, request.Target);
|
||||
Assert.Equal((byte)ExplainSubject.LocalPrice, request.Subject);
|
||||
Assert.Equal(9, request.Arg);
|
||||
var plain = (RequestDetail)Frame.Decode(Frame.Encode(new RequestDetail { Kind = DetailKind.Market, Target = 0 }));
|
||||
Assert.Equal((byte)0, plain.Subject);
|
||||
Assert.Equal(-1, plain.Arg);
|
||||
}
|
||||
|
||||
[Test(Description = "F6 in rete: la spiegazione arriva su richiesta (si aspetta la risposta, non una vecchia), con il prezzo del motore; un bersaglio inesistente risponde «non disponibile»")]
|
||||
public static void ExplanationOnRequest() => RunOnRequest().GetAwaiter().GetResult();
|
||||
|
||||
private static async Task RunOnRequest()
|
||||
{
|
||||
var scenario = ScenarioHelper.Load("valdoria");
|
||||
int coal = scenario.World.Data.Goods.First(g => g.Id == "coal").Index;
|
||||
await using var server = ServerFixture.Start(scenario.World);
|
||||
await using var client = await TestClient.ConnectAsync(server);
|
||||
var w = client.World;
|
||||
await client.WaitUntil(() => w.LastDigest is { Day: >= 2 }, "due giorni di partita");
|
||||
|
||||
var key = ((byte)ExplainSubject.GlobalPrice, coal, -1);
|
||||
Assert.False(w.Explanations.ContainsKey(key), "il server non manda spiegazioni da solo");
|
||||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Explain, Target = coal, Subject = (byte)ExplainSubject.GlobalPrice, Arg = -1 });
|
||||
var first = await client.WaitFor(() => w.Explanations.GetValueOrDefault(key), "spiegazione del prezzo");
|
||||
Assert.True(first.Available, "disponibile");
|
||||
Assert.Equal("Prezzo globale", first.Title);
|
||||
Assert.True(first.Day >= 2, $"giorno {first.Day}");
|
||||
Assert.True(first.Terms.Count > 0 && first.Formula.Length > 0, "formula e termini");
|
||||
Assert.True(first.Value > 0, "prezzo positivo");
|
||||
|
||||
// una seconda richiesta: si aspetta la risposta nuova, non quella già in cache
|
||||
await client.WaitUntil(() => w.LastDigest!.Day > first.Day, "un giorno dopo");
|
||||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Explain, Target = coal, Subject = (byte)ExplainSubject.GlobalPrice, Arg = -1 });
|
||||
var second = await client.WaitFor(() => w.Explanations.TryGetValue(key, out var e) && !ReferenceEquals(e, first) ? e : null, "spiegazione nuova");
|
||||
Assert.True(second.Day > first.Day, "spiegazione di un giorno dopo");
|
||||
if (w.LastDigest!.Day == second.Day)
|
||||
Assert.Equal(w.LastDigest.Prices[coal].Cents, Money.FromCentsRounded(second.Value).Cents, "lo stesso prezzo del resoconto del giorno");
|
||||
|
||||
var missingKey = ((byte)ExplainSubject.TrainCondition, 999, -1);
|
||||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Explain, Target = 999, Subject = (byte)ExplainSubject.TrainCondition, Arg = -1 });
|
||||
var missing = await client.WaitFor(() => w.Explanations.GetValueOrDefault(missingKey), "spiegazione non disponibile");
|
||||
Assert.False(missing.Available, "treno inesistente");
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,15 @@ public static class ProtocolTests
|
||||
yield return new CommandMessage { Seq = 99, Command = new BuildStationCommand(P, 3, "Stazione Nord") };
|
||||
yield return new SetSpeed { Speed = 4 };
|
||||
yield return new RequestDetail { Kind = DetailKind.Workshop, Target = 3 };
|
||||
yield return new RequestDetail { Kind = DetailKind.Explain, Target = 2, Subject = (byte)ExplainSubject.LocalPrice, Arg = 7 };
|
||||
yield return new ExplanationReport
|
||||
{
|
||||
Day = 412, Subject = (byte)ExplainSubject.GlobalPrice, Target = 2, Arg = -1, Available = true, Title = "Prezzo globale", Name = "Carbone",
|
||||
Value = 1234.5678, Unit = (byte)ExplainUnit.Price, ValueText = "", Formula = "Pg = α·Pg′ + (1 − α)·Pg₋₁",
|
||||
Terms = [new ExplanationTermInfo { Symbol = "Pg′", Label = "Prezzo obiettivo", Value = 1250.25, Unit = (byte)ExplainUnit.Price },
|
||||
new ExplanationTermInfo { Symbol = "gradino", Label = "Gradino sopra", Value = 0, Unit = (byte)ExplainUnit.Text, Text = "AA" }],
|
||||
Notes = ["D e S comprendono gli scambi con il resto del mondo."],
|
||||
};
|
||||
yield return new ListSaves();
|
||||
yield return new Save { Name = "partita è bella" };
|
||||
yield return new Load { SaveId = "auto-0003" };
|
||||
|
||||
@@ -14,6 +14,11 @@
|
||||
<ProjectReference Include="..\..\src\RailEnterprise.Tools\RailEnterprise.Tools.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<!-- Logica pura del tutorial del client (senza Godot, ADR 0023): compilata anche qui per provarla. -->
|
||||
<ItemGroup>
|
||||
<Compile Include="..\..\client\RailEnterprise.Client\scripts\Tutorial\Logic\*.cs" LinkBase="ClientTutorial" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Include="..\..\data\**\*.json" LinkBase="data" CopyToOutputDirectory="PreserveNewest" />
|
||||
<Content Include="scenarios\**\*.json" CopyToOutputDirectory="PreserveNewest" />
|
||||
|
||||
Reference in new issue
Block a user