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.Systems; using RailEnterprise.Protocol; using RailEnterprise.Protocol.Messages; using RailEnterprise.Server; using RailEnterprise.Tests.Harness; using RailEnterprise.Tests.Rail; namespace RailEnterprise.Tests.Economy; /// Livelli, sblocchi e pannello «La tua scalata» (F6, ADR 0018). public static class ClimbTests { private static CommandResult Do(World w, GameCommand c) { w.Enqueue(c with { Issuer = w.Player.Id }); w.RunTicks(1); return w.DrainResults().Last(); } /// Valdoria con la rete merci, un treno sulla linea e 40 giorni di servizio. private static RailFixture 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; } /// Dati con il livello 2 raggiungibile subito (patrimonio di un centesimo, nessuna città, rating D). private static GameData EasyTierTwo() { var files = MemoryDataSource.Snapshot(TestData.Source); var tiers = JsonNode.Parse(files["tiers.json"])!; var req = tiers["tiers"]![1]!["requirements"]!; req["netWorth"] = 1; req["connectedTownsOver"]!["count"] = 0; req["creditRating"] = "D"; files["tiers.json"] = tiers.ToJsonString(); return GameData.Load(new MemoryDataSource(files)); } [Test(Description = "Requisiti e avanzamento coerenti con Tiers: soddisfatti esattamente quando Tiers.Meets, avanzamento = media delle frazioni")] public static void RequirementsAgreeWithTiers() { var f = ServedValdoria(); var w = f.W; var c = w.Player; ulong hash = StateHasher.Compute(w); var report = ClimbOutlook.Build(w, c.Id); Assert.Equal(hash, StateHasher.Compute(w), "il quadro non cambia il mondo"); var tiers = w.Data.Tiers.Tiers; Assert.Equal(tiers.Count, report.Tiers.Count); Assert.Equal(c.Tier, report.Tier); Assert.Equal(tiers[c.Tier].Level, report.NextTier); Assert.Equal(c.FoundedDay, report.Tiers[0].ReachedDay, "il livello 1 vale dalla fondazione"); for (int i = 0; i < tiers.Count; i++) Assert.Equal(c.Tier >= tiers[i].Level, report.Tiers[i].Reached, $"livello {i + 1}"); foreach (var tier in tiers) { var req = ClimbOutlook.Requirements(w, c, tier); Assert.Equal(Tiers.Meets(w, c, tier.Requirements), req.AllMet, $"livello {tier.Level}"); Assert.Equal(Tiers.ConnectedTowns(w, c.Id, tier.Requirements.ConnectedTownsOver.Population), req.Towns); Assert.Equal(c.NetWorth, req.NetWorth); Assert.Approx((req.NetWorthFraction + req.TownsFraction + req.RatingFraction) / 3, req.Progress, 1e-12); Assert.InRange(req.Progress, 0, 1); Assert.Equal(req.AllMet, req.Progress >= 1, "avanzamento pieno solo con tutti i requisiti"); double worth = tier.Requirements.NetWorth <= 0 ? 1 : Math.Clamp((double)c.NetWorth.Cents / tier.Requirements.NetWorth, 0, 1); Assert.Approx(worth, req.NetWorthFraction, 1e-12); } var next = report.Next!; Assert.Equal(tiers[c.Tier].Level, next.Level); Assert.True(report.Tiers.Skip(c.Tier).All(t => t.ReachedDay == -1), "livelli non raggiunti senza giorno"); // rating: gradini risaliti dalla D rispetto a quelli richiesti var bbb = tiers.First(t => t.Requirements.CreditRating == CreditRating.BBB); var saved = c.Rating; c.Rating = CreditRating.B; // indice 5, D = 9, BBB = 3: (9 − 5) / (9 − 3) Assert.Approx(4.0 / 6, ClimbOutlook.Requirements(w, c, bbb).RatingFraction, 1e-12); c.Rating = CreditRating.AA; Assert.Equal(1.0, ClimbOutlook.Requirements(w, c, bbb).RatingFraction); Assert.True(ClimbOutlook.Requirements(w, c, bbb).RatingMet); c.Rating = saved; // all'ultimo livello non c'è un prossimo c.Tier = tiers.Count; var top = ClimbOutlook.Build(w, c.Id); Assert.Equal(0, top.NextTier); Assert.True(top.Next is null, "nessun requisito oltre l'ultimo livello"); } [Test(Description = "Gli sblocchi di ogni livello vengono da tiers.json e construction.json: ogni funzione compare una volta, al primo livello che la dà")] public static void UnlocksComeFromTheData() { var w = TestWorlds.NoAi(1801); var c = w.Player; var tiers = w.Data.Tiers.Tiers; var first = Tiers.NewUnlocks(w, c, 1); Assert.Equal(new TierUnlock(UnlockKind.LoanLimit, (c.BaseCredit * tiers[0].Unlocks.MaxLoanFactor).Cents), first[0]); Assert.Equal(new TierUnlock(UnlockKind.Crews, w.Data.Construction.Crews.CrewsByTier[0]), first[1]); Assert.Equal(FinanceSystem.MaxLoan(w, c).Cents, first[0].Value, "il fido del livello 1 è quello del motore"); var features = new (UnlockKind Kind, Func Has)[] { (UnlockKind.Trading, u => u.Trading), (UnlockKind.BuyIndustry, u => u.BuyIndustry), (UnlockKind.Ipo, u => u.Ipo), (UnlockKind.HostileTakeover, u => u.HostileTakeover), (UnlockKind.Concessions, u => u.Concessions), }; for (int level = 1; level <= tiers.Count; level++) { var unlocks = Tiers.NewUnlocks(w, c, level); var u = tiers[level - 1].Unlocks; var prev = level > 1 ? tiers[level - 2].Unlocks : null; foreach (var (kind, has) in features) { bool expected = has(u) && (prev is null || !has(prev)); Assert.Equal(expected, unlocks.Any(x => x.Kind == kind), $"livello {level}, {kind}"); } bool loanUp = prev is null || u.MaxLoanFactor > prev.MaxLoanFactor; Assert.Equal(loanUp, unlocks.Any(x => x.Kind == UnlockKind.LoanLimit && x.Value == (c.BaseCredit * u.MaxLoanFactor).Cents), $"fido al livello {level}"); Assert.Equal(u.Crews, Tiers.Crews(w, level), "squadre uguali nei due file"); Assert.True(unlocks.Select(x => x.Kind).SequenceEqual(unlocks.Select(x => x.Kind).Order()), "in ordine di tipo"); } // le funzioni dell'ultimo livello compaiono ciascuna una volta sola var all = Enumerable.Range(1, tiers.Count).SelectMany(l => Tiers.NewUnlocks(w, c, l)).Where(x => x.Kind >= UnlockKind.Trading).ToList(); Assert.Equal(all.Count, all.Select(x => x.Kind).Distinct().Count()); Assert.Equal(features.Count(x => x.Has(tiers[^1].Unlocks)), all.Count); Assert.Equal("compravendita in proprio", Tiers.UnlockLabel(new TierUnlock(UnlockKind.Trading, 0))); } [Test(Description = "Lo stato patrimoniale per voce (con industria, merce propria, prestito e scoperto) somma esattamente al patrimonio netto del motore")] public static void BalanceSheetSumsToTheEngineNetWorth() { var f = ServedValdoria(); var w = f.W; var c = w.Player; // prestito, industria comprata al livello 3, merce propria in magazzino Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(20_000))).Ok); w.Money.Transfer(Account.External, Account.Of(c.Id), Money.FromLire(10_000_000), LedgerEntry.Other); c.Tier = 3; var mine = w.Industries.First(i => !i.Closed && i.Level > 0 && !i.Owner.IsValid); var bought = Do(w, new BuyIndustryCommand(mine.Id, IndustryMath.Valuation(w, mine) + Money.FromLire(100))); Assert.True(bought.Ok, bought.Message); var station = w.Network.Stations.First(s => s.Owner == c.Id && w.Network.IsAlive(s)); int coal = w.Data.Goods.First(g => g.Id == "coal").Index; TradingMath.AddToWarehouse(station, coal, 50, w.Data.GoodCount); w.Goods.Produced[coal] += 50; w.RunDays(w.Calendar.DaysPerMonth); // il valore contabile si aggiorna a inizio mese // le voci scritte ogni mese sono la scomposizione calcolata dal motore var parts = FinanceSystem.BookValues(w)[c.Id.Value]; Assert.True(parts[(int)AssetCategory.Industries] > 0, "l'industria posseduta è tra gli attivi"); Assert.Equal(IndustryMath.BookValue(w, mine).Cents, parts[(int)AssetCategory.Industries], "impianti più cassa dell'impresa"); Assert.True(parts[(int)AssetCategory.Goods] > 0, "merce propria"); Assert.True(parts[(int)AssetCategory.Track] > 0 && parts[(int)AssetCategory.Stations] > 0 && parts[(int)AssetCategory.Vehicles] > 0, "rete e flotta"); void Check(string when) { var b = ClimbOutlook.Balance(c); Assert.Equal(c.AssetBookValue.Cents, b.Assets.Sum(a => a.Value.Cents), $"voci = valore contabile ({when})"); Assert.Equal(b.TotalAssets.Cents, b.Assets.Sum(a => a.Value.Cents) + b.Portfolio.Cents + b.Cash.Cents, $"totale attivo ({when})"); Assert.Equal(b.TotalLiabilities, b.Loans + b.Overdraft, $"totale debiti ({when})"); Assert.Equal(c.NetWorth, b.NetWorth, $"patrimonio netto del motore ({when})"); Assert.Equal(c.NetWorth, b.TotalAssets - b.TotalLiabilities, $"attivo − debiti ({when})"); Assert.Equal(c.Debt, b.Loans); } Check("con cassa positiva"); var balance = ClimbOutlook.Balance(c); Assert.Approx(c.Loans.Sum(l => (double)l.Remaining.Cents * l.AnnualRate) / c.Debt.Cents, balance.LoansRate, 1e-12); // scoperto: la cassa negativa passa tra i debiti, il patrimonio resta quello del motore var cash = c.Cash; w.Money.Transfer(Account.Of(c.Id), Account.External, cash + Money.FromLire(1_000), LedgerEntry.Other); Assert.True(c.Cash.IsNegative); Check("con lo scoperto"); Assert.Equal(Money.FromLire(1_000), ClimbOutlook.Balance(c).Overdraft); Assert.Equal(Money.Zero, ClimbOutlook.Balance(c).Cash); // conto economico: le righe sommano all'utile operativo var income = ClimbOutlook.Income(w, c); Assert.Equal(income.Profit.Cents, income.Lines.Sum(l => l.Value.Cents)); Assert.Equal(w.Clock.Year, income.Year); Assert.True(income.Partial, "primo anno: anno in corso"); Assert.Equal(Company.OperatingProfit(c.YearEntries), income.Profit.Cents); } [Test(Description = "Al passaggio di livello la notizia elenca gli sblocchi ottenuti; il giorno resta annotato")] public static void PromotionNewsListsTheUnlocks() { var data = EasyTierTwo(); var w = WorldFactory.Create(data, new NewGameSettings { Seed = 1802, SizeKm = 64, DifficultyId = "imprenditore", DifficultyOverride = DifficultyOverrides.Apply(data.DifficultyPreset("imprenditore"), new[] { ("aiCompetitors", 0.0) }), }); Assert.Equal(1, w.Player.Tier); w.RunDays(w.Calendar.DaysPerMonth + 1); Assert.Equal(2, w.Player.Tier); long day = w.Player.TierReachedDay[1]; Assert.Equal((long)w.Calendar.DaysPerMonth, day, "promosso alla chiusura del primo mese"); var tier = data.Tiers.Tiers[1]; var news = w.Events.Recent.Single(e => e.Kind == EventKind.Company && e.Text.Contains($"«{tier.NameIt}»")); Assert.Equal(EventSeverity.Opportunity, news.Severity); Assert.Equal(Tiers.PromotionText(w, w.Player, 2), news.Text); Assert.True(news.Text.Contains("(livello 2): sblocca"), news.Text); Assert.True(news.Text.Contains("compravendita in proprio"), news.Text); Assert.True(news.Text.Contains($"fido fino a {FinanceSystem.MaxLoan(w, w.Player).ToString("short")}"), news.Text); Assert.True(news.Text.Contains($"{data.Construction.Crews.CrewsByTier[1]} squadre di cantiere"), news.Text); var report = ClimbOutlook.Build(w, w.Player.Id); Assert.Equal(day, report.Tiers[1].ReachedDay); Assert.True(w.Player.Milestones.Any(m => m.Day == day && m.Text == $"diventa «{tier.NameIt}»"), "fatto saliente"); } [Test(Description = "I comandi bloccati dal livello dicono quale livello serve e come si chiama, dai dati")] public static void LockedCommandsNameTheTier() { var w = TestWorlds.Small(1803); var tiers = w.Data.Tiers.Tiers; string Named(Func unlock) { var t = tiers.First(x => unlock(x.Unlocks)); return $"livello {t.Level}, «{t.NameIt}»"; } w.RunDays(2); var ind = w.Industries.First(i => !i.Closed && i.Level > 0 && !i.Owner.IsValid); var buy = Do(w, new BuyIndustryCommand(ind.Id, Money.FromLire(1))); Assert.Equal(CommandError.TierLocked, buy.Error); Assert.True(buy.Message.Contains(Named(u => u.BuyIndustry)), buy.Message); var ipo = Do(w, new IpoCommand(0.2)); Assert.Equal(CommandError.TierLocked, ipo.Error); Assert.True(ipo.Message.Contains(Named(u => u.Ipo)), ipo.Message); var rival = w.Companies.First(x => !x.IsPlayer && !x.Defunct); var bid = Do(w, new LaunchBidCommand(rival.Id, Money.FromLire(1), 0.51)); Assert.Equal(CommandError.TierLocked, bid.Error); Assert.True(bid.Message.Contains(Named(u => u.HostileTakeover)), bid.Message); // il livello si controlla prima della stazione var goods = Do(w, new BuyGoodsCommand(new StationId(0), "coal", 1, Money.FromLire(1000))); Assert.Equal(CommandError.TierLocked, goods.Error); Assert.True(goods.Message.Contains(Named(u => u.Trading)), goods.Message); // fido: quanto resta e quale livello lo alza var max = FinanceSystem.MaxLoan(w, w.Player); var loan = Do(w, new TakeLoanCommand(max + Money.FromLire(1))); Assert.Equal(CommandError.CreditLimit, loan.Error); var next = tiers[1]; Assert.True(loan.Message.Contains($"livello {next.Level}, «{next.NameIt}», porta il fido a {Tiers.LoanLimit(w.Player, next)}"), loan.Message); w.Player.Tier = tiers.Count; var top = CommandProcessor.LoanLimitText(w, w.Player, FinanceSystem.MaxLoan(w, w.Player)); Assert.False(top.Contains("livello"), "all'ultimo livello nessun livello successivo"); } [Test(Description = "Voci del patrimonio e giorni dei livelli nel salvataggio (versione 6) e nell'hash; la versione 5 si migra con lo stesso totale")] public static void BalanceSheetSurvivesSavesAndMigrates() { var f = ServedValdoria(); var w = f.W; var c = w.Player; w.RunDays(w.Calendar.DaysPerMonth); c.TierReachedDay[1] = 17; c.Tier = 2; Corporate.Milestone(w, c, $"diventa «{w.Data.Tiers.Tiers[1].NameIt}»"); Assert.True(c.AssetBookValue.Cents > 0, "attivi a valore di libro"); var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test")); var lc = loaded.Player; Assert.True(c.BookValues.SequenceEqual(lc.BookValues), "voci identiche"); Assert.True(c.TierReachedDay.SequenceEqual(lc.TierReachedDay), "giorni dei livelli identici"); Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded)); // le voci entrano nell'hash ulong hash = StateHasher.Compute(w); c.BookValues[(int)AssetCategory.Track]--; c.BookValues[(int)AssetCategory.Vehicles]++; Assert.NotEqual(hash, StateHasher.Compute(w), "spostare valore tra le voci cambia l'hash"); c.BookValues[(int)AssetCategory.Track]++; c.BookValues[(int)AssetCategory.Vehicles]--; // versione 5: solo il totale; la migrazione lo ripartisce senza cambiarlo var v5 = new SaveWriter(1 << 20); WorldSerializer.Write(w, v5, 5); var migrated = WorldSerializer.Read(TestData.Data, new SaveReader(v5.WrittenSpan.ToArray())); var mc = migrated.Player; Assert.Equal(c.AssetBookValue, mc.AssetBookValue, "stesso totale"); Assert.Equal(c.NetWorth, mc.NetWorth, "stesso patrimonio netto"); Assert.True(mc.BookValues.All(v => v >= 0), "voci non negative"); Assert.True(mc.BookValues.Count(v => v > 0) >= 3, "ripartito tra rete, stazioni e veicoli"); Assert.Equal(17L, c.TierReachedDay[1]); Assert.Equal(w.Clock.Day, mc.TierReachedDay[1], "giorno ricostruito dal fatto saliente"); Assert.Equal(-1L, mc.TierReachedDay[2]); foreach (var other in migrated.Companies) Assert.Equal(w.Company(other.Id).AssetBookValue, other.AssetBookValue, other.Name); migrated.RunDays(3); Assert.Equal(0L, migrated.MoneyBalanceSum(), "la partita migrata prosegue"); } [Test(Description = "Proiezione del quadro della scalata: stessi numeri del Core e round-trip del messaggio ClimbReport")] public static void ClimbReportProjectionRoundTrips() { var f = ServedValdoria(); var w = f.W; Assert.True(Do(w, new TakeLoanCommand(Money.FromLire(10_000))).Ok); var core = ClimbOutlook.Build(w, w.Player.Id); var message = Projection.Climb(w, w.Player.Id); var decoded = (ClimbReport)Frame.Decode(Frame.Encode(message)); Assert.True(Frame.Encode(message).AsSpan().SequenceEqual(Frame.Encode(decoded)), "byte identici"); Assert.Equal(w.Clock.Day, decoded.Day); Assert.Equal((byte)core.Tier, decoded.Tier); Assert.Equal((byte)core.NextTier, decoded.NextTier); Assert.Equal(core.Tiers.Count, decoded.Tiers.Count); Assert.Equal(core.Tiers[0].Unlocks.Count, decoded.Tiers[0].Unlocks.Count); Assert.Equal(w.Player.NetWorth, decoded.BalanceNetWorth); Assert.Equal(decoded.BalanceNetWorth, decoded.TotalAssets - decoded.TotalLiabilities); Assert.Equal(AssetCategories.Count, decoded.Assets.Count); Assert.Equal(core.Next!.NetWorthRequired, decoded.NetWorthRequired); Assert.Approx(core.Next.Progress, decoded.Progress, 1e-6); Assert.Equal(1, decoded.LoanList.Count); Assert.Equal(w.Player.Debt, decoded.Loans); Assert.Equal(decoded.Profit.Cents, decoded.Income.Sum(i => i.Value.Cents)); Assert.True(decoded.History.Count >= 2, "fondazione e oggi"); Assert.Equal(w.Player.NetWorth, decoded.History[^1].Value); Assert.Equal(new Money(w.Difficulty.InitialCapital), decoded.History[0].Value); } }