F6: tutorial, correzioni della revisione
Unisce origin/main (audio, ere e obsolescenza, scheda dell'industria e schermata di connessione) e corregge i rilievi della revisione del tutorial (ADR 0023 aggiornato). - Chiave dell'avanzamento senza l'impronta del terreno, che il server ricalcola e che cambia giocando (città, industrie): origine della partita, seme, lato, anno d'inizio, regione e compagnia. Un tutorial ripreso dopo un anno di gioco ritrova la sua voce. - «Tutorial» apre una partita locale di prova sempre nuova in user://tutorial-server invece di riprendere l'autosalvataggio del giocatore e rifare il tutorial lì dentro; con salvataggi locali già presenti la casella «Mostra il tutorial» parte spenta. Casella e pulsante passano nella nuova ConnectScreen (MenuScreen non c'è più). - La casella spuntata vale anche su una voce chiusa o completata (stesso seme di una partita vecchia). - Contorno ritagliato dai contenitori a scorrimento, con l'elemento portato in vista; del tutto nascosto si usa il ripiego. - Pulsanti del riquadro senza fuoco: Invio e spazio restano alla partita (Costruisci, pausa) e non saltano il passo. - La base di «increase» è presa al completamento del passo precedente e gli esiti dei comandi si valutano subito: un binario costruito appena dopo conta per il passo nuovo. - Velocità contata solo dalle richieste di questo client. - Copione mancante o non valido segnalato nella partita; validazione dei null ammessi dal JSON. - Test: chiave stabile con impronta diversa, base al completamento, piano con la casella, null nel copione. 228 test (208 senza i lenti). Refs #45. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
64209afd5f
75 files changed
+7612
-571
No files matched your search
@@ -2,6 +2,7 @@ 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;
|
||||
@@ -66,7 +67,8 @@ public static class TutorialTests
|
||||
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"]);
|
||||
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}»");
|
||||
@@ -181,12 +183,67 @@ public static class TutorialTests
|
||||
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));
|
||||
Assert.Equal(TutorialLaunch.Hidden, TutorialMachine.Plan(requested: true, restart: false, saved: closed));
|
||||
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));
|
||||
}
|
||||
|
||||
string key = TutorialProgress.GameKey(3, 0xABCDEFUL, 1);
|
||||
Assert.Equal("g_0000000000000003_0000000000abcdef_1", key);
|
||||
Assert.True(key.All(c => char.IsAsciiLetterOrDigit(c) || c == '_'), "chiave adatta a ConfigFile");
|
||||
[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")]
|
||||
@@ -204,6 +261,11 @@ public static class TutorialTests
|
||||
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" } ] }"""));
|
||||
|
||||
@@ -0,0 +1,511 @@
|
||||
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.Ai;
|
||||
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;
|
||||
|
||||
namespace RailEnterprise.Tests.Economy;
|
||||
|
||||
/// <summary>Ere, novità tecnologiche, obsolescenza e rinnovo della flotta (F6, ADR 0020).</summary>
|
||||
public static class ErasTests
|
||||
{
|
||||
private static readonly Vec2 DepotPos = RailFixture.K(2.6, 4.4);
|
||||
|
||||
/// <summary>Valdoria che comincia nell'anno indicato, con un deposito e l'id del deposito.</summary>
|
||||
private static (RailFixture F, int Depot) ValdoriaIn(int year, GameData? data = null)
|
||||
{
|
||||
var json = JsonNode.Parse(File.ReadAllText(ScenarioHelper.PathOf("valdoria")))!;
|
||||
json["startYear"] = year;
|
||||
var s = ScenarioLoader.Load(data ?? TestData.Data, json.ToJsonString());
|
||||
var f = new RailFixture(s.World, s);
|
||||
int depot = f.Ok(new BuildDepotCommand(DepotPos, "small", "Deposito di prova"));
|
||||
return (f, depot);
|
||||
}
|
||||
|
||||
private static int CountTechnology(IEnumerable<GameEvent> events) => events.Count(e => e.Kind == EventKind.Technology);
|
||||
|
||||
private static void AssertInvariants(World w, string when)
|
||||
{
|
||||
Assert.Equal(0L, w.MoneyBalanceSum(), $"denaro {when}");
|
||||
for (int g = 0; g < w.Data.GoodCount; g++)
|
||||
Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id} {when}");
|
||||
}
|
||||
|
||||
[Test(Description = "Sblocchi per anno letti dai dati: era in corso, novità, fuori produzione, superati e testo della notizia")]
|
||||
public static void UnlocksFollowTheYear()
|
||||
{
|
||||
var d = TestData.Data;
|
||||
Assert.Equal("steam", EraSystem.CurrentEra(d, 1924).Id);
|
||||
Assert.Equal("diesel", EraSystem.CurrentEra(d, 1925).Id);
|
||||
Assert.Equal("electric", EraSystem.NextEra(d, 1925)!.Id);
|
||||
Assert.True(EraSystem.NextEra(d, 1990) is null, "dopo l'ultima era non ce n'è un'altra");
|
||||
|
||||
var u1878 = EraSystem.Unlocks(d, 1878);
|
||||
Assert.True(u1878.Any(u => u.Kind == TechKind.Vehicle && u.Id == "loco_steam_1878"), "1878: Vittoria 2-8-0");
|
||||
Assert.Equal("loco_steam_1850", EraSystem.NewlySuperseded(d, 1878).Single().Id);
|
||||
var u1925 = EraSystem.Unlocks(d, 1925);
|
||||
Assert.True(u1925.Any(u => u.Kind == TechKind.Traction && u.Id == "diesel"), "1925: trazione diesel");
|
||||
Assert.True(u1925.Any(u => u.Kind == TechKind.Vehicle && u.Id == "loco_diesel_1925"), "1925: Aquila D1");
|
||||
var u1950 = EraSystem.Unlocks(d, 1950);
|
||||
Assert.True(u1950.Any(u => u.Kind == TechKind.Electrification), "1950: elettrificazione");
|
||||
Assert.True(u1950.Any(u => u.Kind == TechKind.BridgeType && u.Id == "concrete"), "1950: ponti in cemento armato");
|
||||
Assert.True(u1950.Any(u => u.Kind == TechKind.TunnelLimit), "1950: gallerie più lunghe");
|
||||
Assert.Equal("loco_steam_1850", EraSystem.Retired(d, 1906).Single().Id);
|
||||
|
||||
string text = EraSystem.NewsText(d, 1925)!;
|
||||
Assert.True(text.StartsWith("Inizia l'Era diesel (1925)", StringComparison.Ordinal), text);
|
||||
Assert.True(text.Contains("Aquila D1", StringComparison.Ordinal) && text.Contains("Freccia 4-6-2 (successore Aquila D1)", StringComparison.Ordinal), text);
|
||||
Assert.True(EraSystem.NewsText(d, 1878)!.StartsWith("Novità del 1878", StringComparison.Ordinal));
|
||||
Assert.True(EraSystem.NewsText(d, 1906)!.Contains("fuori produzione: Ardita 2-6-0", StringComparison.Ordinal));
|
||||
Assert.True(EraSystem.NewsText(d, 1851) is null, "un anno senza novità non dà notizie");
|
||||
|
||||
// nessun elenco scritto a mano: un modello aggiunto ai dati entra nella notizia del suo anno
|
||||
var files = MemoryDataSource.Snapshot(TestData.Source);
|
||||
var vehicles = JsonNode.Parse(files["vehicles.json"])!;
|
||||
var copy = JsonNode.Parse(vehicles["vehicles"]![0]!.ToJsonString())!;
|
||||
copy["id"] = "loco_steam_1851";
|
||||
copy["name_it"] = "Prova 1851";
|
||||
copy["eraFrom"] = 1851;
|
||||
copy.AsObject().Remove("successor");
|
||||
vehicles["vehicles"]!.AsArray().Add(copy);
|
||||
files["vehicles.json"] = vehicles.ToJsonString();
|
||||
var altered = GameData.Load(new MemoryDataSource(files));
|
||||
Assert.True(EraSystem.NewsText(altered, 1851)!.Contains("locomotiva Prova 1851", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Test(Description = "Il validatore rifiuta successori sconosciuti, di un'altra categoria o introdotti prima")]
|
||||
public static void SuccessorValidation()
|
||||
{
|
||||
static string? Error(Action<JsonNode> change)
|
||||
{
|
||||
var files = MemoryDataSource.Snapshot(TestData.Source);
|
||||
var vehicles = JsonNode.Parse(files["vehicles.json"])!;
|
||||
change(vehicles["vehicles"]!);
|
||||
files["vehicles.json"] = vehicles.ToJsonString();
|
||||
try
|
||||
{
|
||||
GameData.Load(new MemoryDataSource(files));
|
||||
return null;
|
||||
}
|
||||
catch (DataValidationException ex)
|
||||
{
|
||||
return ex.Message;
|
||||
}
|
||||
}
|
||||
JsonNode Find(JsonNode list, string id) => list.AsArray().First(v => (string)v!["id"]! == id)!;
|
||||
Assert.True(Error(l => Find(l, "loco_steam_1850")["successor"] = "loco_inesistente") is { } e1 && e1.Contains("sconosciuto", StringComparison.Ordinal));
|
||||
Assert.True(Error(l => Find(l, "loco_steam_1850")["successor"] = "wagon_hopper") is { } e2 && e2.Contains("categoria", StringComparison.Ordinal));
|
||||
Assert.True(Error(l => Find(l, "loco_steam_1878")["successor"] = "loco_steam_1850") is { } e3 && e3.Contains("dopo", StringComparison.Ordinal));
|
||||
Assert.True(Error(l => Find(l, "loco_diesel_1925")["successor"] = "loco_electric_1950") is { } e4 && e4.Contains("elettrificata", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
[Test(Description = "La notizia del passaggio d'anno esce una volta sola, anche salvando prima o dopo, e la Cronaca la registra")]
|
||||
public static void EraNewsOnceAcrossSaves()
|
||||
{
|
||||
var (f, _) = ValdoriaIn(1877);
|
||||
var w = f.W;
|
||||
int dpy = w.Calendar.DaysPerYear;
|
||||
w.RunTicks((long)dpy * w.Calendar.TicksPerDay - 1 - w.Clock.Tick);
|
||||
Assert.Equal(1877, w.Clock.Year);
|
||||
Assert.Equal(0, CountTechnology(w.Events.Drain()), "nessuna notizia nel 1877");
|
||||
var before = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
||||
w.RunDays(2);
|
||||
before.RunDays(2);
|
||||
var news = w.Events.Drain().Where(e => e.Kind == EventKind.Technology).ToList();
|
||||
Assert.Equal(1, news.Count, "una notizia nel tick del 1° gennaio");
|
||||
Assert.Equal(1, CountTechnology(before.Events.Drain()), "anche dal salvataggio fatto il 31 dicembre");
|
||||
Assert.True(news[0].Text.Contains("Vittoria 2-8-0", StringComparison.Ordinal), news[0].Text);
|
||||
Assert.False(news[0].Company.IsValid, "la notizia è per tutte le compagnie");
|
||||
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(before), "stesso stato passando dal salvataggio");
|
||||
|
||||
var after = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
||||
after.RunDays(60);
|
||||
Assert.Equal(0, CountTechnology(after.Events.Drain()), "dopo il caricamento la notizia non si ripete");
|
||||
Assert.Equal(1, after.Player.Milestones.Count(m => m.Text.StartsWith("novità del 1878", StringComparison.Ordinal)), "fatto saliente nella Cronaca");
|
||||
Assert.True(ChronicleReport.Build(after).Highlights.Any(h => h.Contains("Vittoria 2-8-0", StringComparison.Ordinal)), "nella Cronaca");
|
||||
}
|
||||
|
||||
[Test(Description = "Un modello fuori produzione non si compra né compare nel catalogo; i superati sono segnati con il successore")]
|
||||
public static void OutOfProductionIsNotBuyable()
|
||||
{
|
||||
var (f, depot) = ValdoriaIn(1906);
|
||||
var r = f.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
|
||||
Assert.Equal(CommandError.EraLocked, r.Error, r.Message);
|
||||
Assert.True(f.Do(new BuyVehicleCommand("loco_steam_1878", new DepotId(depot), 1)).Ok, "il modello del 1878 è ancora in produzione");
|
||||
var report = FleetOutlook.Build(f.W, f.Me);
|
||||
Assert.False(report.Models.Any(m => m.Def.Id == "loco_steam_1850"), "il catalogo nasconde i fuori produzione");
|
||||
var m1878 = report.Models.Single(m => m.Def.Id == "loco_steam_1878");
|
||||
Assert.True(m1878.Superseded, "superato dalla Freccia del 1902");
|
||||
Assert.Equal("loco_steam_1902", m1878.Successor!.Id);
|
||||
Assert.False(report.Models.Single(m => m.Def.Id == "wagon_hopper").Superseded, "un carro senza successore non è superato");
|
||||
Assert.Equal("loco_steam_1902", Obsolescence.Recommended(f.W.Data.Vehicle("loco_steam_1850"), 1906)!.Id,
|
||||
"il successore consigliato salta i modelli fuori produzione della catena");
|
||||
}
|
||||
|
||||
[Test(Description = "Curva del valore: gradino all'arrivo del successore, poi ammortamento più rapido; rivendita = libro × condizione")]
|
||||
public static void ValueCurveOfSupersededModels()
|
||||
{
|
||||
var d = TestData.Data;
|
||||
var (f, depot) = ValdoriaIn(1876);
|
||||
var w = f.W;
|
||||
var cal = w.Calendar;
|
||||
var o = d.Obsolescence;
|
||||
double floor = d.Balance.Finance.BookValueFloor;
|
||||
var loco = d.Vehicle("loco_steam_1850");
|
||||
var wagon = d.Vehicle("wagon_hopper");
|
||||
long obsolete = Obsolescence.SupersededDay(cal, loco);
|
||||
Assert.Equal((long)(1878 - 1876) * cal.DaysPerYear, obsolete);
|
||||
|
||||
double before = Obsolescence.Residual(d, cal, loco, 0, obsolete - 1);
|
||||
double at = Obsolescence.Residual(d, cal, loco, 0, obsolete);
|
||||
Assert.Approx(1 - (obsolete - 1) / (double)cal.DaysPerYear / loco.LifeYears, before, 1e-12, "prima: lineare sulla vita");
|
||||
Assert.Approx((1 - o.ImmediateValueLoss) * (1 - 2.0 / loco.LifeYears), at, 1e-12, "gradino di immediateValueLoss");
|
||||
double oneYear = Obsolescence.Residual(d, cal, loco, 0, obsolete + cal.DaysPerYear);
|
||||
Assert.Approx((1 - o.ImmediateValueLoss) * (1 - (3 + (o.DepreciationSpeed - 1)) / loco.LifeYears), oneYear, 1e-12, "ammortamento più rapido");
|
||||
// pendenza da superato = depreciationSpeed volte quella normale (scalata dal gradino)
|
||||
double normalSlope = 1.0 / loco.LifeYears;
|
||||
Assert.Approx((1 - o.ImmediateValueLoss) * o.DepreciationSpeed * normalSlope, at - oneYear, 1e-12);
|
||||
// un carro senza successore segue la curva di sempre
|
||||
Assert.Approx(1 - 3.0 / wagon.LifeYears, Obsolescence.Residual(d, cal, wagon, 0, obsolete + cal.DaysPerYear), 1e-12);
|
||||
// monotona e mai sotto il minimo, anche per un veicolo comprato dopo l'arrivo del successore
|
||||
foreach (long bought in new[] { 0L, obsolete + 100 })
|
||||
{
|
||||
double last = double.MaxValue;
|
||||
for (long day = bought; day < bought + 40L * cal.DaysPerYear; day += 7)
|
||||
{
|
||||
double r = Obsolescence.Residual(d, cal, loco, bought, day);
|
||||
Assert.True(r <= last + 1e-12 && r >= floor - 1e-12, $"residuo {r} al giorno {day}");
|
||||
last = r;
|
||||
}
|
||||
}
|
||||
Assert.Approx(1 - o.ImmediateValueLoss, Obsolescence.Residual(d, cal, loco, obsolete + 100, obsolete + 100), 1e-12, "nuovo ma già superato");
|
||||
|
||||
// valore di libro, rivendita e SellVehicle sullo stesso residuo
|
||||
int id = f.Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1)).Created[0];
|
||||
w.RunDays((int)(obsolete - w.Clock.Day) + 30);
|
||||
var v = w.Vehicles[id];
|
||||
v.Components[0] = 50;
|
||||
double residual = Obsolescence.Residual(w, v);
|
||||
Assert.Equal((long)(loco.Price * residual), Obsolescence.BookValueCents(w, v));
|
||||
var resale = Obsolescence.ResaleValue(w, v);
|
||||
Assert.Equal(new Money(loco.Price) * (residual * Obsolescence.AverageCondition(v)), resale);
|
||||
var cash = w.Player.Cash;
|
||||
Assert.True(f.Do(new SellVehicleCommand(new VehicleId(id))).Ok);
|
||||
Assert.Equal(cash + resale, w.Player.Cash, "SellVehicle incassa la rivendita");
|
||||
AssertInvariants(w, "dopo la vendita");
|
||||
}
|
||||
|
||||
[Test(Description = "La manutenzione di un modello superato costa maintenanceCostFactor volte; gli altri veicoli non cambiano")]
|
||||
public static void SupersededMaintenanceCostsMore()
|
||||
{
|
||||
Money ServiceCost(int year)
|
||||
{
|
||||
var (f, depot) = ValdoriaIn(year);
|
||||
int train = f.Train(depot, "Prova", ("loco_steam_1850", 1), ("wagon_hopper", 3));
|
||||
var w = f.W;
|
||||
var t = w.Trains[train];
|
||||
var def = w.Data.Maintenance.Interventions[w.Data.Maintenance.InterventionIndex("service")];
|
||||
return Fleet.CostOf(w, t, def, Fleet.PolicyOf(w, t));
|
||||
}
|
||||
var d = TestData.Data;
|
||||
var service = d.Maintenance.Interventions[d.Maintenance.InterventionIndex("service")];
|
||||
long loco = d.Vehicle("loco_steam_1850").Price, wagon = d.Vehicle("wagon_hopper").Price;
|
||||
Assert.Equal(Money.FromCentsRounded((loco + 3.0 * wagon) * service.CostShare), ServiceCost(1877), "prima del successore");
|
||||
Assert.Equal(Money.FromCentsRounded((loco * d.Obsolescence.MaintenanceCostFactor + 3.0 * wagon) * service.CostShare), ServiceCost(1878),
|
||||
"superato: solo la locomotiva costa di più");
|
||||
}
|
||||
|
||||
[Test(Description = "Valore di libro dei veicoli: una sola fonte per patrimonio, quadro della flotta e stato patrimoniale")]
|
||||
public static void BookValueMatchesNetWorth()
|
||||
{
|
||||
var (f, depot) = ValdoriaIn(1877);
|
||||
var w = f.W;
|
||||
f.Train(depot, "Prova", ("loco_steam_1850", 2), ("coach_worker", 2));
|
||||
w.RunDays(w.Calendar.DaysPerYear + w.Calendar.DaysPerMonth - (int)(w.Clock.Day % w.Calendar.DaysPerMonth));
|
||||
Assert.Equal(1878, w.Clock.Year);
|
||||
Assert.Equal(0L, w.Clock.Day % w.Calendar.DaysPerMonth, "inizio del mese: valori appena aggiornati");
|
||||
long expected = w.Vehicles.Where(v => !v.Sold && v.Owner == f.Me).Sum(v => Obsolescence.BookValueCents(w, v));
|
||||
Assert.Equal(expected, FinanceSystem.BookValues(w)[f.Me.Value][(int)AssetCategory.Vehicles], "FinanceSystem.BookValues");
|
||||
Assert.Equal(expected, w.Player.BookValues[(int)AssetCategory.Vehicles], "voce salvata dal mese");
|
||||
Assert.Equal(new Money(expected), FleetOutlook.Build(w, f.Me).BookValueTotal, "quadro della flotta");
|
||||
var balance = ClimbOutlook.Balance(w.Player);
|
||||
Assert.Equal(new Money(expected), balance.Assets.Single(a => a.Category == AssetCategory.Vehicles).Value, "stato patrimoniale");
|
||||
Assert.Equal(w.Player.NetWorth, w.Player.Cash + w.Player.AssetBookValue + w.Player.PortfolioValue - w.Player.Debt);
|
||||
}
|
||||
|
||||
[Test(Description = "Rinnovo in officina: i veicoli superati si vendono e i successori prendono il loro posto, con denaro e merci in equilibrio")]
|
||||
public static void RenewalReplacesSupersededVehicles()
|
||||
{
|
||||
var (f, depot) = ValdoriaIn(1878);
|
||||
var w = f.W;
|
||||
int fresh = f.Train(depot, "Nuovo", ("loco_steam_1878", 1), ("wagon_hopper", 2));
|
||||
var refused = f.Do(new ScheduleServiceCommand(new TrainId(fresh), "renewal"));
|
||||
Assert.Equal(CommandError.NotAllowed, refused.Error, "niente da rinnovare");
|
||||
|
||||
int train = f.Train(depot, "Vecchio", ("loco_steam_1850", 1), ("wagon_hopper", 2));
|
||||
var t = w.Trains[train];
|
||||
var oldLoco = t.Vehicles[0];
|
||||
var wagons = t.Vehicles.Skip(1).ToList();
|
||||
var plan = Obsolescence.RenewalPlan(w, t);
|
||||
Assert.Equal(1, plan.Count, "solo la locomotiva è superata");
|
||||
Assert.Equal("loco_steam_1878", plan[0].Successor.Id);
|
||||
var renewal = w.Data.Maintenance.Interventions[w.Data.Maintenance.InterventionIndex("renewal")];
|
||||
var outlook = FleetOutlook.Build(w, f.Me).Trains.Single(x => x.Train.Value == train);
|
||||
Assert.Equal(Obsolescence.NetCost(plan) + Fleet.CostOf(w, t, renewal, Fleet.PolicyOf(w, t)), outlook.NetCost);
|
||||
|
||||
var cash = w.Player.Cash;
|
||||
Assert.True(f.Do(new ScheduleServiceCommand(new TrainId(train), "renewal")).Ok);
|
||||
Assert.True(t.InWorkshop, "il treno è già nel deposito: entra subito in officina");
|
||||
Assert.True(f.RunUntil(() => !t.InWorkshop, 30), "rinnovo completato");
|
||||
Assert.True(w.Vehicles[oldLoco.Value].Sold, "la vecchia locomotiva è venduta");
|
||||
var loco = w.Vehicles[t.Vehicles[0].Value];
|
||||
Assert.Equal("loco_steam_1878", loco.Def.Id);
|
||||
Assert.Equal(t.Id, loco.Train);
|
||||
Assert.SequenceEqual(wagons, t.Vehicles.Skip(1), "i carri restano al loro posto");
|
||||
Assert.Approx(loco.Def.PowerKw, t.PowerKw, 1e-9, "caratteristiche del treno ricalcolate");
|
||||
Assert.True(w.Player.Cash < cash, "il rinnovo costa");
|
||||
Assert.Equal(0, Obsolescence.RenewalPlan(w, t).Count, "niente più da rinnovare");
|
||||
Assert.True(t.History.Any(h => h.Intervention == w.Data.Maintenance.InterventionIndex("renewal")), "nello storico della manutenzione");
|
||||
AssertInvariants(w, "dopo il rinnovo");
|
||||
}
|
||||
|
||||
[Test(Description = "Rinnovo deterministico e salvataggio a metà officina: stesso hash e stesso esito, senza nuovo stato (corpo versione 7)")]
|
||||
public static void RenewalIsDeterministicAcrossSaves()
|
||||
{
|
||||
Assert.Equal(7, WorldSerializer.BodyVersion, "ere e obsolescenza non aggiungono stato al salvataggio");
|
||||
(World W, int Train) Start()
|
||||
{
|
||||
var (f, depot) = ValdoriaIn(1878);
|
||||
int train = f.Train(depot, "Vecchio", ("loco_steam_1850", 1), ("coach_worker", 2));
|
||||
Assert.True(f.Do(new ScheduleServiceCommand(new TrainId(train), "renewal")).Ok);
|
||||
f.W.RunDays(1);
|
||||
return (f.W, train);
|
||||
}
|
||||
var (a, train) = Start();
|
||||
var (b, _) = Start();
|
||||
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(b, "test"));
|
||||
Assert.True(loaded.Trains[train].InWorkshop, "salvato a metà officina");
|
||||
a.RunDays(40);
|
||||
loaded.RunDays(40);
|
||||
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(loaded));
|
||||
Assert.Equal("loco_steam_1878", loaded.Vehicles[loaded.Trains[train].Vehicles[0].Value].Def.Id);
|
||||
Assert.Equal(0L, loaded.MoneyBalanceSum());
|
||||
}
|
||||
|
||||
[Test(Description = "Il quadro della flotta si proietta nel protocollo e sopravvive al round-trip")]
|
||||
public static void FleetReportRoundTrip()
|
||||
{
|
||||
var (f, depot) = ValdoriaIn(1878);
|
||||
var w = f.W;
|
||||
int train = f.Train(depot, "Vecchio", ("loco_steam_1850", 1), ("wagon_hopper", 1));
|
||||
ulong hash = StateHasher.Compute(w);
|
||||
var report = Projection.FleetRenewal(w, f.Me);
|
||||
Assert.Equal(hash, StateHasher.Compute(w), "il quadro non cambia il mondo");
|
||||
var decoded = (FleetReport)Frame.Decode(Frame.Encode(report));
|
||||
Assert.Equal("steam", decoded.Era);
|
||||
Assert.Equal("diesel", decoded.NextEra);
|
||||
Assert.Equal(1925, decoded.NextEraYear);
|
||||
Assert.Equal("renewal", decoded.RenewalIntervention);
|
||||
Assert.Equal(2, decoded.Vehicles.Count);
|
||||
var loco = decoded.Vehicles.Single(v => v.Type == "loco_steam_1850");
|
||||
Assert.True(loco.Superseded && loco.InProduction);
|
||||
Assert.Equal(1878, loco.SupersededYear);
|
||||
Assert.Equal("loco_steam_1878", loco.Successor);
|
||||
Assert.Equal(train, loco.Train);
|
||||
Assert.Approx(w.Data.Obsolescence.MaintenanceCostFactor, loco.MaintenanceFactor, 1e-6);
|
||||
var v = w.Vehicles[loco.Vehicle];
|
||||
Assert.Equal(Obsolescence.ResaleValue(w, v), loco.Resale);
|
||||
Assert.Equal(new Money(Obsolescence.BookValueCents(w, v)), loco.BookValue);
|
||||
Assert.Equal(decoded.Vehicles.Sum(x => x.BookValue.Cents), decoded.BookValueTotal.Cents);
|
||||
Assert.Equal(train, decoded.Trains.Single().Train);
|
||||
Assert.True(decoded.Models.Single(m => m.Type == "loco_steam_1850").Superseded);
|
||||
Assert.False(decoded.Models.Any(m => m.Type == "loco_diesel_1925"), "non ancora introdotto");
|
||||
}
|
||||
|
||||
private static void SetCash(World w, Company c, Money target)
|
||||
{
|
||||
var delta = target - c.Cash;
|
||||
if (delta.IsPositive) w.Money.Transfer(Account.External, Account.Of(c.Id), delta, LedgerEntry.Other);
|
||||
else if (delta.IsNegative) w.Money.Transfer(Account.Of(c.Id), Account.External, -delta, LedgerEntry.Other);
|
||||
}
|
||||
|
||||
[Test(Description = "Rinnovo: la cassa spesa tra prenotazione e avvio annulla il lavoro senza scoperto; due prenotazioni non impegnano la stessa cassa")]
|
||||
public static void RenewalCashIsCheckedAtStartAndCommitted()
|
||||
{
|
||||
var (f, depot) = ValdoriaIn(1878);
|
||||
var w = f.W;
|
||||
int a = f.Train(depot, "Primo", ("loco_steam_1850", 1), ("wagon_hopper", 1));
|
||||
int b = f.Train(depot, "Secondo", ("loco_steam_1850", 1), ("wagon_hopper", 1));
|
||||
var ta = w.Trains[a];
|
||||
var tb = w.Trains[b];
|
||||
// all'inizio di un giorno: l'officina avvia i lavori solo al giorno dopo
|
||||
w.RunTicks(w.Calendar.TicksPerDay - w.Clock.Tick % w.Calendar.TicksPerDay + 1);
|
||||
var cost = Obsolescence.RenewalCost(w, ta, Obsolescence.RenewalPlan(w, ta));
|
||||
Assert.True(cost.IsPositive, "il rinnovo costa");
|
||||
// cassa per un rinnovo solo: il secondo trova la cassa già impegnata dal primo
|
||||
SetCash(w, w.Player, cost + cost * 0.5);
|
||||
Assert.True(f.Do(new ScheduleServiceCommand(new TrainId(a), "renewal")).Ok);
|
||||
Assert.Equal(cost, Obsolescence.Committed(w, f.Me), "spesa impegnata dal rinnovo prenotato");
|
||||
var outlook = FleetOutlook.Build(w, f.Me);
|
||||
Assert.True(outlook.Trains.Single(x => x.Train.Value == a).Booked, "il primo è prenotato");
|
||||
var second = outlook.Trains.Single(x => x.Train.Value == b);
|
||||
Assert.False(second.Booked, "il secondo no");
|
||||
Assert.False(second.Affordable, "il secondo non è pagabile con la cassa già impegnata");
|
||||
var refused = f.Do(new ScheduleServiceCommand(new TrainId(b), "renewal"));
|
||||
Assert.Equal(CommandError.InsufficientFunds, refused.Error, refused.Message);
|
||||
Assert.True(refused.Message.Contains("impegnati", StringComparison.Ordinal), refused.Message);
|
||||
|
||||
// la cassa si spende altrove prima dell'avvio: il rinnovo si annulla, niente scoperto
|
||||
SetCash(w, w.Player, cost - new Money(1));
|
||||
var oldLoco = ta.Vehicles[0];
|
||||
w.Events.Drain();
|
||||
w.RunDays(2);
|
||||
Assert.False(ta.InWorkshop, "il treno esce dall'officina");
|
||||
Assert.Equal(-1, ta.PlannedIntervention);
|
||||
Assert.Equal(oldLoco, ta.Vehicles[0], "nessun veicolo sostituito");
|
||||
Assert.False(w.Vehicles[oldLoco.Value].Sold);
|
||||
Assert.False(w.Player.Cash.IsNegative, "la cassa non va in scoperto");
|
||||
Assert.Equal(0L, ta.MaintenanceThisYear, "nemmeno il lavoro è pagato");
|
||||
Assert.True(w.Events.Drain().Any(e => e.Severity == EventSeverity.Warning && e.Text.Contains("rinnovo annullato", StringComparison.Ordinal)),
|
||||
"notizia di avviso");
|
||||
Assert.Equal(Money.Zero, Obsolescence.Committed(w, f.Me), "niente più impegnato");
|
||||
|
||||
// con la cassa, il rinnovo si paga all'avvio e poi non impegna più nulla
|
||||
SetCash(w, w.Player, cost * 3);
|
||||
Assert.True(f.Do(new ScheduleServiceCommand(new TrainId(a), "renewal")).Ok);
|
||||
w.RunDays(2);
|
||||
Assert.True(ta.InWorkshop, "lavori in corso");
|
||||
Assert.Equal("loco_steam_1878", w.Vehicles[ta.Vehicles[0].Value].Def.Id, "veicoli sostituiti all'avvio");
|
||||
Assert.Equal(Money.Zero, Obsolescence.Committed(w, f.Me), "spesa già pagata");
|
||||
Assert.True(f.RunUntil(() => !ta.InWorkshop, 30), "rinnovo completato");
|
||||
Assert.True(tb.Vehicles.All(id => !w.Vehicles[id.Value].Sold));
|
||||
AssertInvariants(w, "dopo i rinnovi");
|
||||
}
|
||||
|
||||
[Test(Description = "Un rinnovo che all'avvio non ha più nulla da sostituire si annulla senza far pagare il lavoro")]
|
||||
public static void RenewalWithEmptyPlanAtStartIsCancelled()
|
||||
{
|
||||
// la Vittoria 2-8-0 si produce solo nel 1878: dal 1879 l'Ardita è superata ma senza successore in produzione
|
||||
var files = MemoryDataSource.Snapshot(TestData.Source);
|
||||
var vehicles = JsonNode.Parse(files["vehicles.json"])!;
|
||||
vehicles["vehicles"]!.AsArray().First(v => (string)v!["id"]! == "loco_steam_1878")!["eraTo"] = 1878;
|
||||
files["vehicles.json"] = vehicles.ToJsonString();
|
||||
var data = GameData.Load(new MemoryDataSource(files));
|
||||
var (f, depot) = ValdoriaIn(1878, data);
|
||||
var w = f.W;
|
||||
w.RunDays(w.Calendar.DaysPerYear - 3 - (int)w.Clock.Day);
|
||||
Assert.Equal(1878, w.Clock.Year);
|
||||
// due revisioni generali occupano gli stalli del deposito piccolo oltre la fine dell'anno
|
||||
for (int i = 0; i < w.Network.Depots[depot].Stalls; i++)
|
||||
{
|
||||
int busy = f.Train(depot, $"Occupato {i}", ("loco_steam_1878", 1));
|
||||
Assert.True(f.Do(new ScheduleServiceCommand(new TrainId(busy), "overhaul")).Ok);
|
||||
}
|
||||
int train = f.Train(depot, "Vecchio", ("loco_steam_1850", 1), ("wagon_hopper", 1));
|
||||
var t = w.Trains[train];
|
||||
Assert.Equal(1, Obsolescence.RenewalPlan(w, t).Count, "nel 1878 la Vittoria si compra");
|
||||
Assert.True(f.Do(new ScheduleServiceCommand(new TrainId(train), "renewal")).Ok);
|
||||
var oldLoco = t.Vehicles[0];
|
||||
w.Events.Drain();
|
||||
Assert.True(f.RunUntil(() => !t.InWorkshop, 120), "il rinnovo esce dalla coda");
|
||||
Assert.Equal(1879, w.Clock.Year);
|
||||
Assert.Equal(oldLoco, t.Vehicles[0], "nessun veicolo sostituito");
|
||||
Assert.Equal(0L, t.MaintenanceThisYear, "il lavoro non si paga");
|
||||
Assert.False(t.History.Any(h => h.Intervention == w.Data.Maintenance.InterventionIndex("renewal")), "nessun rinnovo nello storico");
|
||||
Assert.True(w.Events.Drain().Any(e => e.Severity == EventSeverity.Warning && e.Text.Contains("rinnovo annullato", StringComparison.Ordinal)),
|
||||
"notizia di avviso");
|
||||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||||
}
|
||||
|
||||
[Test(Description = "La ricostruzione di un modello fuori produzione non lo rende nuovo nel patrimonio")]
|
||||
public static void RebuildKeepsBookAgeOfRetiredModels()
|
||||
{
|
||||
var (f, depot) = ValdoriaIn(1905);
|
||||
var w = f.W;
|
||||
int train = f.Train(depot, "Vecchio", ("loco_steam_1850", 1), ("wagon_hopper", 1));
|
||||
var t = w.Trains[train];
|
||||
w.RunDays(w.Calendar.DaysPerYear + 10);
|
||||
Assert.Equal(1906, w.Clock.Year);
|
||||
var loco = w.Vehicles[t.Vehicles[0].Value];
|
||||
var wagon = w.Vehicles[t.Vehicles[1].Value];
|
||||
long locoBought = loco.BoughtDay;
|
||||
long locoBook = Obsolescence.BookValueCents(w, loco);
|
||||
loco.Components[0] = 10;
|
||||
var replace = w.Data.Maintenance.Interventions[w.Data.Maintenance.InterventionIndex("repair_catastrophic")];
|
||||
Fleet.Apply(w, t, replace, Fleet.PolicyOf(w, t));
|
||||
Assert.Equal(locoBought, loco.BoughtDay, "l'Ardita non si produce più: età contabile invariata");
|
||||
Assert.Equal(locoBook, Obsolescence.BookValueCents(w, loco), "valore di libro invariato");
|
||||
Assert.True(loco.Components.All(c => c == 100), "componenti ricostruiti");
|
||||
Assert.Approx(1, Fleet.AgeFactor(w, loco), 1e-12, "l'usura riparte da capo");
|
||||
Assert.Equal(w.Clock.Day, wagon.BoughtDay, "il carro, ancora in produzione, torna nuovo");
|
||||
}
|
||||
|
||||
[Test(Description = "La Cronaca registra il contenuto di un anno con soli modelli fuori produzione")]
|
||||
public static void MilestoneOfRetirementOnlyYear()
|
||||
{
|
||||
var d = TestData.Data;
|
||||
Assert.Equal(0, EraSystem.Unlocks(d, 1906).Count, "nel 1906 nessuno sblocco");
|
||||
var (f, _) = ValdoriaIn(1878);
|
||||
EraSystem.Announce(f.W, 1906);
|
||||
string text = f.W.Player.Milestones[^1].Text;
|
||||
Assert.True(text.StartsWith("novità del 1906: ", StringComparison.Ordinal) && text.Contains("fuori produzione: Ardita 2-6-0", StringComparison.Ordinal), text);
|
||||
}
|
||||
|
||||
[Test(Description = "Scelte delle IA: carrozze non superate, rinnovi che non peggiorano trazione, potenza, velocità e potenza/massa")]
|
||||
public static void AiChoicesAvoidSupersededAndWeakerModels()
|
||||
{
|
||||
var (f1949, _) = ValdoriaIn(1878);
|
||||
Assert.Equal("coach_worker", Estimators.CoachFor(f1949.W, PaxClass.Worker, 1949)!.Id);
|
||||
Assert.Equal("coach_modern", Estimators.CoachFor(f1949.W, PaxClass.Worker, 1950)!.Id, "dal 1950 la carrozza operai è superata");
|
||||
Assert.Equal("coach_staff", Estimators.CoachFor(f1949.W, PaxClass.Staff, 1950)!.Id, "senza successore resta quella");
|
||||
|
||||
bool Keeps(int year, params (string Type, int Count)[] vehicles)
|
||||
{
|
||||
var (f, depot) = ValdoriaIn(year);
|
||||
var t = f.W.Trains[f.Train(depot, "Prova", vehicles)];
|
||||
var plan = Obsolescence.RenewalPlan(f.W, t);
|
||||
Assert.True(plan.Count > 0, $"{year}: qualcosa da rinnovare");
|
||||
return Obsolescence.KeepsPerformance(f.W, t, plan);
|
||||
}
|
||||
Assert.True(Keeps(1878, ("loco_steam_1850", 1), ("wagon_hopper", 3)), "Ardita → Vittoria migliora tutto");
|
||||
Assert.False(Keeps(1902, ("loco_steam_1878", 1), ("wagon_hopper", 3)), "Vittoria → Freccia perde sforzo di trazione");
|
||||
Assert.True(Keeps(1925, ("loco_steam_1878", 1), ("wagon_hopper", 3)), "dal 1925 la Vittoria passa all'Aquila D1");
|
||||
Assert.False(Keeps(1950, ("loco_diesel_1925", 1), ("coach_worker", 8)), "carrozze più pesanti con la stessa potenza");
|
||||
}
|
||||
|
||||
[Test(Slow = true, Description = "Le IA rinnovano i treni con locomotive superate, senza comandi rifiutati oltre il 5 %")]
|
||||
public static void AiRenewsSupersededTrains()
|
||||
{
|
||||
var files = MemoryDataSource.Snapshot(TestData.Source);
|
||||
var ai = JsonNode.Parse(files["ai.json"])!;
|
||||
ai["renewal"]!["minSupersededYears"] = 0;
|
||||
files["ai.json"] = ai.ToJsonString();
|
||||
var data = GameData.Load(new MemoryDataSource(files));
|
||||
var w = WorldFactory.Create(data, new NewGameSettings { Seed = 42, SizeKm = 64, StartYear = 1875 });
|
||||
// fino al 1878: le IA costruiscono le prime linee con l'Ardita del 1850
|
||||
w.RunTicks((long)3 * w.Calendar.DaysPerYear * w.Calendar.TicksPerDay - w.Clock.Tick);
|
||||
Assert.Equal(1878, w.Clock.Year);
|
||||
var oldTrains = w.Trains
|
||||
.Where(t => !t.Removed && !w.Company(t.Owner).IsPlayer && t.Vehicles.Any(id => w.Vehicles[id.Value].Def.Id == "loco_steam_1850"))
|
||||
.Select(t => t.Id).ToList();
|
||||
Assert.True(oldTrains.Count > 0, "le IA hanno treni con l'Ardita");
|
||||
w.RunYears(2);
|
||||
int renewed = oldTrains.Count(id => w.Trains[id.Value].Vehicles.Any(v => w.Vehicles[v.Value].Def.Id == "loco_steam_1878"));
|
||||
Assert.True(renewed > 0, $"almeno un treno rinnovato su {oldTrains.Count}");
|
||||
foreach (var s in w.AiStates)
|
||||
Assert.True(s.RejectedShare <= w.Data.Ai.Planning.MaxRejectedShare, $"{w.Company(s.Company).Name}: {s.Rejected} rifiutati su {s.Issued}");
|
||||
Assert.Equal(0L, w.MoneyBalanceSum());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,319 @@
|
||||
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.Systems;
|
||||
using RailEnterprise.Protocol;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using RailEnterprise.Server;
|
||||
using RailEnterprise.Tests.Harness;
|
||||
using RailEnterprise.Tests.Rail;
|
||||
|
||||
namespace RailEnterprise.Tests.Economy;
|
||||
|
||||
/// <summary>Scheda dell'industria dell'immagine 07 (F6, ADR 0021): catena produttiva, coperture, limite, crescita.</summary>
|
||||
public static class IndustryOutlookTests
|
||||
{
|
||||
private static int GoodIndex(World w, string id) => w.Data.Goods.First(g => g.Id == id).Index;
|
||||
|
||||
/// <summary>Valdoria con la rete merci miniere → acciaieria, un treno sulla linea e 40 giorni di servizio.</summary>
|
||||
private static (RailFixture F, int Line, int MillStation) ServedValdoria()
|
||||
{
|
||||
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(40);
|
||||
return (f, line, mill);
|
||||
}
|
||||
|
||||
[Test(Description = "Scheda dell'acciaieria di Valdoria: input, output, fornitore collegato dalla linea, clienti, stazione che serve; nessun effetto sul mondo")]
|
||||
public static void SheetOfTheSteelMill()
|
||||
{
|
||||
var (f, line, millStation) = ServedValdoria();
|
||||
var w = f.W;
|
||||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
ulong hash = StateHasher.Compute(w);
|
||||
var r = IndustryOutlook.Build(w, steel, f.Me);
|
||||
Assert.Equal(hash, StateHasher.Compute(w), "la scheda non cambia il mondo");
|
||||
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
Assert.Equal(steel.Level, r.Level);
|
||||
Assert.Equal(w.Data.Balance.Growth.MaxLevel, r.MaxLevel);
|
||||
Assert.Equal(steel.Efficiency, r.Efficiency);
|
||||
Assert.Equal(steel.Def.StorageDays, r.StorageDays);
|
||||
Assert.Equal(w.Data.Balance.Industry.CoverageWindowDays, r.CoverageWindowDays);
|
||||
|
||||
// input nell'ordine della ricetta: fabbisogno a piena capacità e consumo al ritmo attuale
|
||||
Assert.Equal(2, r.Inputs.Count);
|
||||
int ore = GoodIndex(w, "iron_ore");
|
||||
Assert.Equal(ore, r.Inputs[0].Good);
|
||||
Assert.Equal(GoodIndex(w, "coal"), r.Inputs[1].Good);
|
||||
double cyclesMonth = (double)steel.Def.Capacity(steel.Level) / steel.Def.Recipe.Outputs[0].PerCycle;
|
||||
Assert.Approx(cyclesMonth * 2, r.Inputs[0].FullMonth, 1e-9);
|
||||
Assert.Approx(cyclesMonth * 1, r.Inputs[1].FullMonth, 1e-9);
|
||||
Assert.Approx(r.Inputs[0].FullMonth * steel.Efficiency, r.Inputs[0].CurrentMonth, 1e-9);
|
||||
Assert.Equal(steel.InputStock[0], r.Inputs[0].Stock);
|
||||
Assert.Equal(IndustryMath.InputCapacity(steel, 0, dpm), r.Inputs[0].Storage);
|
||||
|
||||
// output: capacità del livello, produzione al ritmo attuale, magazzino
|
||||
Assert.Equal(1, r.Outputs.Count);
|
||||
Assert.Approx(steel.Def.Capacity(steel.Level), r.Outputs[0].FullMonth, 1e-9);
|
||||
Assert.Approx(r.Outputs[0].FullMonth * steel.Efficiency, r.Outputs[0].CurrentMonth, 1e-9);
|
||||
Assert.Equal(IndustryMath.OutputCapacity(steel, 0, dpm), r.Outputs[0].Storage);
|
||||
if (r.Outputs[0].CurrentMonth > 0)
|
||||
{
|
||||
double perDay = r.Outputs[0].CurrentMonth / dpm;
|
||||
Assert.Approx(Math.Max(0, r.Outputs[0].Storage - r.Outputs[0].Stock) / perDay, r.Outputs[0].Days, 1e-9);
|
||||
}
|
||||
|
||||
// il primo fornitore di minerale è la miniera di Rocca Bruna, collegata dalla linea
|
||||
int perGood = w.Data.Balance.Industry.Outlook.PartnersPerGood;
|
||||
var suppliers = r.Inputs[0].Partners;
|
||||
Assert.True(suppliers.Count is > 0 && suppliers.Count <= perGood, $"fornitori {suppliers.Count}");
|
||||
var mine = w.Industries.First(i => i.Def.Id == "iron_mine");
|
||||
Assert.Equal(ChainPartnerKind.Industry, suppliers[0].Kind);
|
||||
Assert.Equal(mine.Id.Value, suppliers[0].Target);
|
||||
Assert.Equal(line, suppliers[0].Line.Value);
|
||||
Assert.Equal(w.Market.GlobalPrice[ore], suppliers[0].Price);
|
||||
double mineMonth = mine.CyclesPerDayAtFullCapacity(dpm) * dpm * mine.Efficiency;
|
||||
Assert.Approx(mineMonth, suppliers[0].MonthlyUnits, 1e-9);
|
||||
// dopo i collegati, i più vicini
|
||||
for (int i = 1; i < suppliers.Count; i++)
|
||||
{
|
||||
if (suppliers[i - 1].Line.IsValid == suppliers[i].Line.IsValid)
|
||||
Assert.True(suppliers[i - 1].DistanceKm <= suppliers[i].DistanceKm, "ordinati per distanza");
|
||||
else Assert.True(suppliers[i - 1].Line.IsValid, "prima i collegati");
|
||||
}
|
||||
|
||||
// clienti dell'acciaio: la fabbrica di attrezzi al prezzo locale dell'ADR 0004 e il porto, non collegati
|
||||
var customers = r.Outputs[0].Partners;
|
||||
Assert.True(customers.Count is > 0 && customers.Count <= perGood, $"clienti {customers.Count}");
|
||||
Assert.True(customers.All(c => !c.Line.IsValid), "nessun cliente collegato");
|
||||
var tools = w.Industries.First(i => i.Def.Id == "tool_factory");
|
||||
var toolsEntry = customers.FirstOrDefault(c => c.Kind == ChainPartnerKind.Industry && c.Target == tools.Id.Value);
|
||||
Assert.True(toolsEntry.Kind == ChainPartnerKind.Industry && toolsEntry.Target == tools.Id.Value, "la fabbrica di attrezzi compra acciaio");
|
||||
int steelGood = GoodIndex(w, "steel");
|
||||
int slot = tools.InputIndexOf(steelGood);
|
||||
double local = Market.LocalPrice(w.Market.GlobalPrice[steelGood], IndustryMath.InputCapacity(tools, slot, dpm), tools.InputStock[slot], w.Data.Balance.LocalPrice);
|
||||
Assert.Equal(local, toolsEntry.Price);
|
||||
if (customers.FirstOrDefault(c => c.Kind == ChainPartnerKind.Hub) is { Kind: ChainPartnerKind.Hub } port)
|
||||
Assert.Equal(w.Hubs[port.Target].BuyPrice(w.Market.GlobalPrice[steelGood]), port.Price);
|
||||
|
||||
// servita dalla stazione dell'acciaieria con la linea della compagnia
|
||||
Assert.True(r.ServingStations.Contains(new StationId(millStation)), "stazione dell'acciaieria");
|
||||
Assert.Equal(line, r.ServingLine.Value);
|
||||
// per un'altra compagnia nessuna linea collega
|
||||
var other = IndustryOutlook.Build(w, steel, CompanyId.None);
|
||||
Assert.False(other.ServingLine.IsValid);
|
||||
Assert.True(other.Inputs[0].Partners.All(p => !p.Line.IsValid), "senza compagnia nessun collegamento");
|
||||
|
||||
// crescita: punteggio del trimestre dalla stessa funzione della crescita trimestrale
|
||||
var g = w.Data.Balance.Growth;
|
||||
Assert.Equal(IndustryMath.GrowthScore(steel, g), r.Growth.Current);
|
||||
Assert.Equal(g.UpgradeThreshold, r.Growth.UpgradeThreshold);
|
||||
Assert.Equal(g.DowngradeThreshold, r.Growth.DowngradeThreshold);
|
||||
Assert.Equal(steel.QuarterDays, r.Growth.QuarterDay);
|
||||
Assert.Equal(g.QuarterDays, r.Growth.QuarterDays);
|
||||
Assert.True(r.Growth.Served, "servita da un vettore");
|
||||
|
||||
// acquisto: dei privati, livello e avanzamento dai dati (ADR 0018)
|
||||
var tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.BuyIndustry);
|
||||
Assert.True(r.ForSale);
|
||||
Assert.False(r.BuyUnlocked);
|
||||
Assert.Equal(tier.Level, r.BuyTier);
|
||||
Assert.Approx(ClimbOutlook.Requirements(w, w.Player, tier).Progress, r.BuyProgress, 1e-12);
|
||||
Assert.Approx(IndustryMath.AnnualProfit(w, steel), r.AnnualProfit.Cents, 1);
|
||||
|
||||
// prezzo di vendita: il prezzo globale del giorno del prodotto (ADR 0004)
|
||||
Assert.Equal(w.Market.GlobalPrice[steelGood], r.SalePrice);
|
||||
}
|
||||
|
||||
[Test(Description = "La scheda non mostra i pendolari portati da altri vettori, come il Registro degli impieghi; li mostra solo se l'industria è della compagnia")]
|
||||
public static void WorkforceHidesOtherCarriers()
|
||||
{
|
||||
var (f, line, _) = ServedValdoria();
|
||||
var w = f.W;
|
||||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
var rival = new CompanyId(f.Me.Value + 1);
|
||||
var before = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, f.Me);
|
||||
var town = w.Towns.First();
|
||||
var contract = new CommuteContract
|
||||
{
|
||||
Id = new ContractId(w.NextIds.Contract++), Town = town.Id, Workplace = WorkplaceRef.Of(steel.Id), Category = PaxClass.Worker,
|
||||
Headcount = 120, Carrier = rival, ExpectedMinutes = 400, Coverage = 0.9,
|
||||
};
|
||||
contract.Route.Add(new LineId(line));
|
||||
w.Commutes.Add(contract);
|
||||
|
||||
// per la compagnia del giocatore il contratto del rivale non c'è: né provenienza né viaggio medio
|
||||
var mine = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, f.Me);
|
||||
Assert.False(mine.Sources.Any(x => x.Carrier == rival), "nessuna provenienza del rivale");
|
||||
Assert.Equal(before.SourceCount, mine.SourceCount);
|
||||
Assert.Equal(before.AverageMinutes, mine.AverageMinutes);
|
||||
var sheet = Projection.IndustryCard(w, steel, f.Me).Sheet!;
|
||||
Assert.False(sheet.Workers.Sources.Any(x => x.Carrier == rival.Value), "nemmeno nel messaggio");
|
||||
|
||||
// il rivale vede il suo contratto
|
||||
var theirs = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, rival);
|
||||
Assert.True(theirs.Sources.Any(x => x.Carrier == rival && x.Headcount == 120 && x.Town == town.Id), "il vettore vede i suoi pendolari");
|
||||
Assert.True(theirs.AverageMinutes > 0, "viaggio medio dai suoi contratti");
|
||||
|
||||
// l'industria della compagnia mostra i pendolari di tutti i vettori
|
||||
steel.Owner = f.Me;
|
||||
var owned = IndustryOutlook.Workforce(w, steel, PaxClass.Worker, f.Me);
|
||||
Assert.True(owned.Sources.Any(x => x.Carrier == rival), "il proprietario vede tutti i vettori");
|
||||
Assert.Equal(before.SourceCount + 1, owned.SourceCount);
|
||||
}
|
||||
|
||||
[Test(Description = "Forza lavoro della scheda: presenti, quota in sede, posti scoperti e provenienze dai contratti di pendolarismo")]
|
||||
public static void WorkforceComesFromTheCommuteContracts()
|
||||
{
|
||||
var (f, _, _) = ServedValdoria();
|
||||
var w = f.W;
|
||||
var ib = w.Data.Balance.Industry;
|
||||
foreach (var ind in w.Industries.Where(i => !i.Closed))
|
||||
{
|
||||
foreach (var cls in new[] { PaxClass.Worker, PaxClass.Staff })
|
||||
{
|
||||
var o = IndustryOutlook.Workforce(w, ind, cls, f.Me);
|
||||
bool staff = cls == PaxClass.Staff;
|
||||
int jobs = staff ? ind.JobsStaff : ind.JobsWorkers;
|
||||
double present = staff ? ind.StaffPresent : ind.WorkersPresent;
|
||||
Assert.Equal(jobs, o.Jobs);
|
||||
Assert.Equal(present, o.Present);
|
||||
Assert.Approx(jobs * (staff ? ib.OnSiteStaffShare : ib.OnSiteWorkerShare), o.OnSite, 1e-9);
|
||||
Assert.Equal((int)Math.Max(0, Math.Round(jobs - present, MidpointRounding.AwayFromZero)), o.Missing);
|
||||
var contracts = w.Commutes.Where(c => c.Workplace == WorkplaceRef.Of(ind.Id) && c.Category == cls && c.Headcount > 0 && IndustryOutlook.Visible(c, ind, f.Me)).ToList();
|
||||
Assert.True(o.Sources.Count <= ib.Outlook.WorkforceSources && o.Sources.Count <= o.SourceCount, "provenienze entro il limite");
|
||||
if (o.SourceCount <= ib.Outlook.WorkforceSources)
|
||||
Assert.Equal(contracts.Sum(c => c.Headcount), o.Sources.Sum(s => s.Headcount));
|
||||
for (int i = 1; i < o.Sources.Count; i++) Assert.True(o.Sources[i - 1].Headcount >= o.Sources[i].Headcount, "dalle più numerose");
|
||||
var rail = contracts.Where(c => !c.Walking).ToList();
|
||||
if (rail.Count == 0) Assert.Equal(-1.0, o.AverageMinutes);
|
||||
else Assert.Approx(rail.Sum(c => c.ExpectedMinutes * c.Headcount) / rail.Sum(c => c.Headcount), o.AverageMinutes, 1e-9);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[Test(Description = "Il limite dell'efficienza è il fattore più basso sotto 1; fermo e livello 0 hanno la precedenza")]
|
||||
public static void LimitIsTheLowestFactor()
|
||||
{
|
||||
var f = RailFixture.Valdoria();
|
||||
var w = f.W;
|
||||
w.RunDays(2);
|
||||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
var m = w.Data.Balance.IndustryMaintenance;
|
||||
|
||||
steel.CovInput = 1;
|
||||
steel.CovWorkers = 1;
|
||||
steel.CovStaff = 1;
|
||||
steel.RevenueEma = 100;
|
||||
steel.CostEma = 100;
|
||||
steel.Condition = 100;
|
||||
Assert.Equal(IndustryLimit.None, IndustryOutlook.Factors(w, steel).Limit);
|
||||
|
||||
steel.CovStaff = 0.4;
|
||||
steel.CovWorkers = 0.6;
|
||||
Assert.Equal(IndustryLimit.Staff, IndustryOutlook.Factors(w, steel).Limit);
|
||||
steel.CovInput = 0.3;
|
||||
Assert.Equal(IndustryLimit.Inputs, IndustryOutlook.Factors(w, steel).Limit);
|
||||
|
||||
// impianti sotto il 20 %: mc al minimo, sotto le coperture
|
||||
steel.CovInput = 0.9;
|
||||
steel.Condition = 10;
|
||||
var factors = IndustryOutlook.Factors(w, steel);
|
||||
Assert.Equal(m.EfficiencyBelow20, factors.ConditionMultiplier);
|
||||
Assert.Equal(m.EfficiencyBelow20 < 0.4 ? IndustryLimit.Condition : IndustryLimit.Staff, factors.Limit);
|
||||
|
||||
// margine negativo: fattore di profitto sotto 1
|
||||
steel.Condition = 100;
|
||||
steel.CovStaff = 1;
|
||||
steel.CovWorkers = 1;
|
||||
steel.CovInput = 1;
|
||||
steel.RevenueEma = 0;
|
||||
steel.CostEma = 100;
|
||||
Assert.Equal(IndustryLimit.Profit, IndustryOutlook.Factors(w, steel).Limit);
|
||||
Assert.Equal(IndustryMath.ProfitFactor(steel, w.Data.Balance.Industry), IndustryOutlook.Factors(w, steel).ProfitFactor);
|
||||
|
||||
// fermo e livello 0
|
||||
steel.StoppedUntilDay = w.Clock.Day + 5;
|
||||
Assert.Equal(IndustryLimit.Stopped, IndustryOutlook.Factors(w, steel).Limit);
|
||||
steel.StoppedUntilDay = -1;
|
||||
steel.Level = 0;
|
||||
Assert.Equal(IndustryLimit.Dormant, IndustryOutlook.Factors(w, steel).Limit);
|
||||
|
||||
// senza input (miniera) l'input non è mai il limite; giacimento sotto la soglia
|
||||
var mine = w.Industries.First(i => i.Def.Id == "iron_mine");
|
||||
mine.CovInput = 0;
|
||||
mine.CovWorkers = 1;
|
||||
mine.CovStaff = 1;
|
||||
mine.RevenueEma = 100;
|
||||
mine.CostEma = 100;
|
||||
mine.Condition = 100;
|
||||
Assert.Equal(IndustryLimit.None, IndustryOutlook.Factors(w, mine).Limit);
|
||||
var site = w.Sites[mine.Site.Value];
|
||||
site.ReserveTonnes = site.InitialReserveTonnes * w.Data.Balance.Industry.DepletionStartFraction / 2;
|
||||
var depleted = IndustryOutlook.Factors(w, mine);
|
||||
Assert.Equal(IndustryLimit.Depletion, depleted.Limit);
|
||||
Assert.Approx(0.5, depleted.Depletion, 1e-9);
|
||||
Assert.Approx(site.ReserveFraction, depleted.ReserveFraction, 1e-12);
|
||||
}
|
||||
|
||||
[Test(Description = "Il punteggio di crescita trimestrale pesa quota trasportata, copertura e redditività come in balance.json")]
|
||||
public static void GrowthScoreUsesTheWeights()
|
||||
{
|
||||
var f = RailFixture.Valdoria();
|
||||
var w = f.W;
|
||||
var g = w.Data.Balance.Growth;
|
||||
var ind = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
ind.QuarterProduced = 200;
|
||||
ind.QuarterShipped = 150;
|
||||
ind.QuarterCoverageSum = 30;
|
||||
ind.QuarterDays = 60;
|
||||
ind.RevenueEma = 300;
|
||||
ind.CostEma = 100;
|
||||
var s = IndustryMath.GrowthScore(ind, g);
|
||||
Assert.Approx(0.75, s.Shipped, 1e-12);
|
||||
Assert.Approx(0.5, s.Coverage, 1e-12);
|
||||
Assert.Approx((ind.Margin + 1) / 2, s.Profit, 1e-12);
|
||||
Assert.Approx(g.WeightShipped * 0.75 + g.WeightCoverage * 0.5 + g.WeightProfit * s.Profit, s.Score, 1e-12);
|
||||
// spedito oltre il prodotto (scorte vecchie): la quota resta 1
|
||||
ind.QuarterShipped = 500;
|
||||
Assert.Equal(1.0, IndustryMath.GrowthScore(ind, g).Shipped);
|
||||
ind.QuarterProduced = 0;
|
||||
ind.QuarterDays = 0;
|
||||
Assert.Equal(0.0, IndustryMath.GrowthScore(ind, g).Shipped);
|
||||
Assert.Equal(0.0, IndustryMath.GrowthScore(ind, g).Coverage);
|
||||
}
|
||||
|
||||
[Test(Description = "La scheda viaggia nel blocco 1 di IndustryCard e torna identica; senza blocco il lettore la lascia vuota")]
|
||||
public static void SheetRoundTripsInTheIndustryCard()
|
||||
{
|
||||
var (f, line, _) = ServedValdoria();
|
||||
var w = f.W;
|
||||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
var card = Projection.IndustryCard(w, steel, f.Me);
|
||||
Assert.True(card.Sheet is not null, "scheda nel blocco 1");
|
||||
var decoded = (IndustryCard)Frame.Decode(Frame.Encode(card));
|
||||
var sheet = decoded.Sheet!;
|
||||
Assert.True(Frame.Encode(card).AsSpan().SequenceEqual(Frame.Encode(decoded)), "stessi byte");
|
||||
Assert.Equal((byte)steel.Level, sheet.Level);
|
||||
Assert.Equal(2, sheet.Inputs.Count);
|
||||
Assert.Equal(line, sheet.ServingLine);
|
||||
Assert.Equal(line, sheet.Inputs[0].Partners[0].Line);
|
||||
Assert.Equal((float)steel.Efficiency, sheet.Efficiency);
|
||||
Assert.Equal(card.Valuation, decoded.Valuation);
|
||||
Assert.Equal(steel.JobsWorkers, sheet.Workers.Jobs);
|
||||
|
||||
// un messaggio senza blocco (server F5) si legge con la scheda assente
|
||||
var old = new IndustryCard { Industry = 3, Valuation = new Money(100) };
|
||||
var back = (IndustryCard)Frame.Decode(Frame.Encode(old));
|
||||
Assert.True(back.Sheet is null, "nessuna scheda");
|
||||
Assert.Equal(new Money(100), back.Valuation);
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,7 @@ public static class ProtocolTests
|
||||
},
|
||||
DataHash = 12345,
|
||||
Difficulty = "imprenditore",
|
||||
Server = new ServerInfo { Version = "0.6.1", Os = "Linux 6.8", Container = true, UptimeSeconds = 518_400, TickMs = 50, Sessions = 1, MaxSessions = 16, Local = false },
|
||||
};
|
||||
yield return new Reject { Code = RejectCode.BadToken, Reason = "Token errato" };
|
||||
yield return new Pong { Nonce = 7, ServerTick = 123456 };
|
||||
@@ -117,6 +118,36 @@ public static class ProtocolTests
|
||||
MaintenanceSpentYear = new Money(9999), PartsTarget = 9, PartsPerMonth = 3, PartsOrdered = 20, MachineryRequired = 6, UpgradeCost = new Money(3_000_000),
|
||||
Valuation = new Money(4_500_000), Cash = new Money(2_000_000), BreakdownChancePerYear = 0.3f,
|
||||
Stops = [new IndustryStopInfo { Day = 300, Days = 12, Kind = 1 }, new IndustryStopInfo { Day = 500, Days = 30, Kind = 3 }],
|
||||
Sheet = new IndustrySheetInfo
|
||||
{
|
||||
Level = 3, MaxLevel = 5, Efficiency = 0.6f, Limit = 3, CovInput = 0.73f, CovWorkers = 0.8f, CovStaff = 0.6f, CoverageWindowDays = 30,
|
||||
ProfitFactor = 1.05f, Depletion = 1, EventCapacity = 1, ReserveFraction = -1, StorageDays = 30,
|
||||
Inputs =
|
||||
[
|
||||
new IndustryFlowInfo
|
||||
{
|
||||
Good = 2, FullMonth = 480, CurrentMonth = 350, Stock = 105, Storage = 480, Days = 9, Limiting = true,
|
||||
Partners = [new ChainPartnerInfo { Kind = 0, Target = 1, MonthlyUnits = 500, Price = 4_200, Line = 5, DistanceKm = 9.4f }],
|
||||
},
|
||||
],
|
||||
Outputs =
|
||||
[
|
||||
new IndustryFlowInfo
|
||||
{
|
||||
Good = 4, FullMonth = 500, CurrentMonth = 300, Stock = 40, Storage = 500, Days = 46, Limiting = false,
|
||||
Partners = [new ChainPartnerInfo { Kind = 1, Target = 0, MonthlyUnits = 4000, Price = 15_600, Line = -1, DistanceKm = 4.2f }],
|
||||
},
|
||||
],
|
||||
Workers = new WorkforceInfo
|
||||
{
|
||||
Jobs = 200, Present = 160, OnSite = 60, Coverage = 0.8f, Missing = 40, Reason = 5, ReasonLine = 1, AverageMinutes = 38, SourceCount = 2,
|
||||
Sources = [new WorkforceSourceInfo { Town = 0, Headcount = 120, Coverage = 0.95f, Line = 1, Carrier = 0, Minutes = 35, Walking = false }],
|
||||
},
|
||||
Staff = new WorkforceInfo { Jobs = 20, Present = 12, Missing = 8, Reason = 4, ReasonLine = -1, AverageMinutes = -1 },
|
||||
SalePrice = 15_600, AnnualProfit = new Money(41_000_000), LastScore = 0.62f, Shipped = 0.8f, Coverage = 0.6f, Profit = 0.55f, Score = 0.69f,
|
||||
UpgradeThreshold = 0.75f, DowngradeThreshold = 0.35f, UpgradeQuarters = 2, QuartersAbove = 1, QuarterDay = 45, QuarterDays = 90, Served = true,
|
||||
ServingStations = [2, 7], ServingLine = 1, ForSale = true, BuyUnlocked = false, BuyTier = 3, BuyProgress = 0.58f,
|
||||
},
|
||||
};
|
||||
yield return new Chronicle
|
||||
{
|
||||
@@ -188,6 +219,22 @@ public static class ProtocolTests
|
||||
MaxLoan = new Money(100_000_000), LoanAvailable = new Money(88_000_000), NewLoanRate = 0.061f, LoansAllowed = false,
|
||||
History = [new NetWorthPointInfo { Day = 0, Value = new Money(25_000_000) }, new NetWorthPointInfo { Day = 2600, Value = new Money(39_144_993) }],
|
||||
};
|
||||
yield return new FleetReport
|
||||
{
|
||||
Day = 10_100, Company = 0, Year = 1878, Era = "steam", NextEra = "diesel", NextEraYear = 1925, RenewalIntervention = "renewal",
|
||||
BookValueTotal = new Money(1_234_567),
|
||||
Vehicles =
|
||||
[
|
||||
new FleetVehicleInfo { Vehicle = 3, Type = "loco_steam_1850", Train = 1, Depot = -1, AgeYears = 26.5f, LifeYears = 25, Condition = 0.8f,
|
||||
InProduction = true, Superseded = true, SupersededYear = 1878, Successor = "loco_steam_1878", BookValue = new Money(180_000),
|
||||
Resale = new Money(144_000), MaintenanceFactor = 1.5f },
|
||||
new FleetVehicleInfo { Vehicle = 4, Type = "wagon_hopper", Train = -1, Depot = 2, AgeYears = 1f, LifeYears = 40, Condition = 1f,
|
||||
InProduction = true, BookValue = new Money(117_000), Resale = new Money(117_000), MaintenanceFactor = 1f },
|
||||
],
|
||||
Models = [new VehicleModelInfo { Type = "loco_steam_1850", Superseded = true, SupersededYear = 1878, Successor = "loco_steam_1878", LastYear = 1905 },
|
||||
new VehicleModelInfo { Type = "wagon_hopper" }],
|
||||
Trains = [new RenewalTrainInfo { Train = 1, Vehicles = 1, NetCost = new Money(3_056_000), Affordable = true, Booked = true }],
|
||||
};
|
||||
yield return new FinanceReport
|
||||
{
|
||||
Day = 2610, Company = 0, Cash = new Money(-120_000), NetWorth = new Money(39_000_000), Loans = new Money(12_000_000), Overdraft = new Money(120_000),
|
||||
@@ -338,6 +385,31 @@ public static class ProtocolTests
|
||||
foreach (var id in Enum.GetValues<MessageId>()) Assert.True(seen.Contains(id), $"manca l'esemplare di {id}");
|
||||
}
|
||||
|
||||
[Test(Description = "Un Welcome senza blocco 1 (server F5) si legge con lo stato del server assente, stessi byte, e la copia locale lo lascia null")]
|
||||
public static void WelcomeWithoutServerInfoRoundTrips()
|
||||
{
|
||||
var old = new Welcome
|
||||
{
|
||||
SessionId = 9,
|
||||
Summary = new WorldSummary { Seed = 1, SizeKm = 64, StartYear = 1850, Date = "1 gennaio 1850", CompanyName = "Società", WidthCells = 64, HeightCells = 64, CellSizeM = 100, ChunkCells = 64 },
|
||||
DataHash = 7,
|
||||
};
|
||||
byte[] frame = Frame.Encode(old);
|
||||
var back = (Welcome)Frame.Decode(frame);
|
||||
Assert.True(back.Server is null, "nessuno stato del server");
|
||||
Assert.True(frame.AsSpan().SequenceEqual(Frame.Encode(back)), "stessi byte");
|
||||
Assert.Equal(old.SessionId, back.SessionId);
|
||||
Assert.Equal("Società", back.Summary.CompanyName);
|
||||
|
||||
// la copia locale del client resta senza stato del server, anche dopo un Welcome che lo aveva
|
||||
var world = new RailEnterprise.Protocol.Client.ClientWorld(TestData.Data);
|
||||
var withInfo = (Welcome)Frame.Decode(Frame.Encode(new Welcome { Summary = old.Summary, Server = new ServerInfo { Version = "0.6.1" } }));
|
||||
world.Apply(withInfo);
|
||||
Assert.True(world.Server is not null, "stato del server dal Welcome F6");
|
||||
world.Apply(back);
|
||||
Assert.True(world.Server is null, "un Welcome F5 azzera lo stato del server");
|
||||
}
|
||||
|
||||
[Test(Description = "Ogni tipo di comando sopravvive al round-trip dentro un messaggio Command")]
|
||||
public static void EveryCommandRoundTrips()
|
||||
{
|
||||
|
||||
@@ -404,6 +404,55 @@ public static class ServerTests
|
||||
Assert.Equal(Money.FromLire(5_000), after.Loans);
|
||||
}
|
||||
|
||||
[Test(Description = "F6 in rete: la scheda dell'industria arriva su richiesta con la catena produttiva; il Welcome porta lo stato del server e ListSaves l'elenco (ADR 0021)")]
|
||||
public static void IndustrySheetAndServerStatusOnRequest() => RunIndustrySheet().GetAwaiter().GetResult();
|
||||
|
||||
private static async Task RunIndustrySheet()
|
||||
{
|
||||
var scenario = ScenarioHelper.Load("valdoria");
|
||||
var steel = scenario.World.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
await using var server = ServerFixture.Start(scenario.World);
|
||||
await using var client = await TestClient.ConnectAsync(server);
|
||||
var w = client.World;
|
||||
var data = TestData.Data;
|
||||
|
||||
// stato del server nel blocco 1 del Welcome
|
||||
var info = client.Welcome.Server;
|
||||
Assert.True(info is not null, "stato del server nel Welcome");
|
||||
Assert.Equal(server.Host.GameVersion, info!.Version);
|
||||
Assert.Equal(1f, info.TickMs);
|
||||
Assert.True(info.Sessions >= 1 && info.Sessions <= info.MaxSessions, $"sessioni {info.Sessions} su {info.MaxSessions}");
|
||||
Assert.True(info.Local, "server in processo avviato come locale");
|
||||
Assert.True(info.Os.Length > 0 && info.UptimeSeconds >= 0, "sistema e tempo di attività");
|
||||
Assert.True(w.Server is not null && w.Server.Version == info.Version, "la copia locale tiene lo stato del server");
|
||||
|
||||
// elenco dei salvataggi: risposta a ListSaves, poi a Save con il salvataggio nuovo
|
||||
await client.Connection.SendAsync(new ListSaves());
|
||||
var empty = await client.WaitFor(() => w.Saves, "elenco dei salvataggi");
|
||||
var stale = w.Saves;
|
||||
await client.Connection.SendAsync(new Save { Name = "Valdoria" });
|
||||
var saves = await client.WaitFor(() => ReferenceEquals(w.Saves, stale) ? null : w.Saves, "elenco dopo il salvataggio");
|
||||
Assert.Equal(empty.Saves.Count + 1, saves.Saves.Count);
|
||||
Assert.True(saves.Saves.Any(x => !x.Autosave && (x.Name.Contains("Valdoria", StringComparison.Ordinal) || x.SaveId.Contains("Valdoria", StringComparison.OrdinalIgnoreCase))), "il salvataggio nuovo è nell'elenco");
|
||||
|
||||
// scheda dell'industria: si aspetta la risposta alla richiesta, non una scheda vecchia
|
||||
await client.WaitUntil(() => w.LastDigest is { Day: >= 2 }, "due giorni di partita");
|
||||
var old = w.IndustryCards.GetValueOrDefault(steel.Id.Value);
|
||||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Industry, Target = steel.Id.Value });
|
||||
var card = await client.WaitFor(() => w.IndustryCards.TryGetValue(steel.Id.Value, out var c) && !ReferenceEquals(c, old) ? c : null, "scheda dell'industria");
|
||||
var sheet = card.Sheet;
|
||||
Assert.True(sheet is not null, "scheda nel blocco 1");
|
||||
Assert.Equal(steel.Def.Recipe.Inputs.Count, sheet!.Inputs.Count);
|
||||
Assert.Equal(steel.Def.Recipe.Outputs.Count, sheet.Outputs.Count);
|
||||
Assert.Equal(data.Goods.First(g => g.Id == "iron_ore").Index, sheet.Inputs[0].Good);
|
||||
Assert.True(sheet.Inputs[0].Partners.Count > 0 && sheet.Inputs[0].Partners.All(p => p.Line == -1), "fornitori, nessuno collegato");
|
||||
Assert.Equal(data.Balance.Growth.MaxLevel, (int)sheet.MaxLevel);
|
||||
Assert.Equal(-1, sheet.ServingLine);
|
||||
Assert.True(sheet.ForSale && !sheet.BuyUnlocked, "in vendita, acquisto non ancora sbloccato");
|
||||
Assert.Equal(data.Tiers.Tiers.First(t => t.Unlocks.BuyIndustry).Level, (int)sheet.BuyTier);
|
||||
Assert.Equal(steel.JobsWorkers, sheet.Workers.Jobs);
|
||||
}
|
||||
|
||||
[Test(Description = "Hello con token errato, dati diversi o protocollo vecchio riceve Reject")]
|
||||
public static void HandshakeRejections() => RunRejections().GetAwaiter().GetResult();
|
||||
|
||||
@@ -447,6 +496,12 @@ public static class ServerTests
|
||||
Assert.Equal(1, list.Saves.Count);
|
||||
Assert.True(list.Saves[0].SaveId.StartsWith("prova_rete-", StringComparison.Ordinal), list.Saves[0].SaveId);
|
||||
await client.WaitFor(() => client.Received.OfType<EntitySnapshot>().FirstOrDefault(), "snapshot");
|
||||
// un Load rifiutato risponde con un avviso del server: giorno −1, distinto dagli eventi del mondo
|
||||
await client.Connection.SendAsync(new Load { SaveId = "non-esiste" });
|
||||
var refused = await client.WaitFor(() => client.Received.OfType<Notification>().FirstOrDefault(n => n.Event.Day < 0), "avviso del Load rifiutato");
|
||||
Assert.Equal(GameHost.ServerNoticeDay, refused.Event.Day);
|
||||
Assert.True(refused.Event.Text.StartsWith("Caricamento non riuscito", StringComparison.Ordinal), refused.Event.Text);
|
||||
Assert.False(client.Received.OfType<Notification>().Any(n => n.Event.Day >= 0 && n.Event.Text.StartsWith("Caricamento", StringComparison.Ordinal)), "nessun evento del mondo scambiato per l'avviso");
|
||||
}
|
||||
// ripresa con lo stesso id: stessa sessione, stato rimandato per intero
|
||||
await using (var again = await TestClient.ConnectAsync(server, resume: sessionId))
|
||||
|
||||
Reference in new issue
Block a user