La revisione del pannello «La tua scalata» ha trovato numeri che promettevano più di quanto il motore concede e qualche incoerenza con l'immagine 08. - Avanzamento: il client mostra le percentuali per difetto (Fmt.Progress), così il 100 % compare solo a requisito o livello raggiunto; prima 0,996 si leggeva «100%» senza promozione. Il tetto del motore resta 0,999. - Rating: la frazione è 1 − gradini mancanti / ratingProgressSteps (2,5 in tiers.json, con schema e validatore). Lo stato dell'immagine 08 torna al 58 % (rating al 60 %); misurato dalla D dava l'86 % per un solo gradino. - Concessioni: non compaiono più tra gli sblocchi né nella notizia finché il comando non esiste (F7); il rifiuto dice che non sono ancora disponibili. - Validatore: gli sblocchi non possono diminuire salendo di livello (fido e funzioni), come presumono notizie, rifiuti e pannello. - Industrie possedute inattive (livello 0): a libro valgono solo la cassa. - Migrazione 1-5: il giorno del livello ricostruito dallo storico è quello della fotografia (primo giorno dell'anno dopo), tra fondazione e oggi. - Storico del patrimonio: un punto per anno di calendario (oggi sostituisce il primo giorno dell'anno in corso); i livelli si segnano sull'anno della promozione, anche sull'ultimo punto. - Barra superiore: richiede di nuovo il quadro se uno stato completo lo ha azzerato. - ADR 0018 aggiornato; ADR 0015 §12 segnato come sostituito. - Test nuovi per avanzamento, storico, migrazione, concessioni, industria inattiva e validatore (174 test verdi). Refs #38. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
446 lines
25 KiB
C#
446 lines
25 KiB
C#
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;
|
||
|
||
/// <summary>Livelli, sblocchi e pannello «La tua scalata» (F6, ADR 0018).</summary>
|
||
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();
|
||
}
|
||
|
||
/// <summary>Valdoria con la rete merci, un treno sulla linea e 40 giorni di servizio.</summary>
|
||
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;
|
||
}
|
||
|
||
/// <summary>Dati con il livello 2 raggiungibile subito (patrimonio di un centesimo, nessuna città, rating D).</summary>
|
||
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);
|
||
double average = (req.NetWorthFraction + req.TownsFraction + req.RatingFraction) / 3;
|
||
Assert.Approx(req.AllMet ? average : Math.Min(average, ClimbOutlook.ProgressCap), 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: 1 − gradini mancanti / ratingProgressSteps (2,5 nei dati)
|
||
var bbb = tiers.First(t => t.Requirements.CreditRating == CreditRating.BBB);
|
||
var saved = c.Rating;
|
||
double steps = w.Data.Tiers.RatingProgressSteps;
|
||
c.Rating = CreditRating.BB; // un gradino sotto BBB
|
||
Assert.Approx(1 - 1 / steps, ClimbOutlook.Requirements(w, c, bbb).RatingFraction, 1e-12);
|
||
c.Rating = CreditRating.D; // troppo lontano: zero
|
||
Assert.Equal(0.0, ClimbOutlook.Requirements(w, c, bbb).RatingFraction);
|
||
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<TierUnlocks, bool> 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)
|
||
{
|
||
// le concessioni non si annunciano finché il comando non esiste (F7)
|
||
bool available = kind != UnlockKind.Concessions || Tiers.ConcessionsAvailable;
|
||
bool expected = available && 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) && (x.Kind != UnlockKind.Concessions || Tiers.ConcessionsAvailable)), 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);
|
||
|
||
// un'industria posseduta inattiva (livello 0) non si vende: a libro vale solo la sua cassa
|
||
int level = mine.Level;
|
||
mine.Level = 0;
|
||
Assert.Equal(Money.Max(Money.Zero, mine.Cash), IndustryMath.BookValue(w, mine), "impianti a livello 0");
|
||
mine.Level = level;
|
||
Assert.True(IndustryMath.BookValue(w, mine) > Money.Max(Money.Zero, mine.Cash), "impianti al livello attuale");
|
||
}
|
||
|
||
[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<TierUnlocks, bool> 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);
|
||
|
||
// concessioni (F7): prima del livello il rifiuto dice che non ci sono ancora e dove si sbloccheranno,
|
||
// dopo restano «non ancora disponibili»; nessuna notizia o pannello le annuncia
|
||
var concession = Do(w, new BuyConcessionCommand(new RegionId(0)));
|
||
Assert.Equal(CommandError.TierLocked, concession.Error);
|
||
Assert.True(concession.Message.Contains("non sono ancora disponibili") && concession.Message.Contains(Named(u => u.Concessions)), concession.Message);
|
||
int saved = w.Player.Tier;
|
||
w.Player.Tier = tiers.First(t => t.Unlocks.Concessions).Level;
|
||
var later = Do(w, new BuyConcessionCommand(new RegionId(0)));
|
||
Assert.Equal(CommandError.NotImplemented, later.Error);
|
||
Assert.True(later.Message.Contains("non sono ancora disponibili"), later.Message);
|
||
Assert.False(Tiers.PromotionText(w, w.Player, w.Player.Tier).Contains("concessioni"), "la notizia non promette le concessioni");
|
||
w.Player.Tier = saved;
|
||
|
||
// 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);
|
||
}
|
||
|
||
[Test(Description = "L'avanzamento resta sotto il pieno (e sotto il 100 % per difetto) finché un requisito manca; il rating dell'immagine 08")]
|
||
public static void ProgressIsFullOnlyWhenAllRequirementsAreMet()
|
||
{
|
||
var data = EasyTierTwo();
|
||
var w = WorldFactory.Create(data, new NewGameSettings
|
||
{
|
||
Seed = 1804, SizeKm = 64, DifficultyId = "imprenditore",
|
||
DifficultyOverride = DifficultyOverrides.Apply(data.DifficultyPreset("imprenditore"), new[] { ("aiCompetitors", 0.0) }),
|
||
});
|
||
var c = w.Player;
|
||
var tier = data.Tiers.Tiers[1];
|
||
// soglia del patrimonio a 1000 volte il patrimonio attuale, poi il 99,7 % della soglia
|
||
var req = new TierRequirements
|
||
{
|
||
NetWorth = Math.Max(1_000_000, c.NetWorth.Cents) * 1000,
|
||
ConnectedTownsOver = tier.Requirements.ConnectedTownsOver,
|
||
CreditRating = tier.Requirements.CreditRating,
|
||
};
|
||
var def = new TierDef { Level = tier.Level, NameIt = tier.NameIt, NameEn = tier.NameEn, Requirements = req, Unlocks = tier.Unlocks };
|
||
void SetNetWorth(long cents)
|
||
{
|
||
long delta = cents - c.NetWorth.Cents;
|
||
if (delta > 0) w.Money.Transfer(Account.External, Account.Of(c.Id), new Money(delta), LedgerEntry.Other);
|
||
else if (delta < 0) w.Money.Transfer(Account.Of(c.Id), Account.External, new Money(-delta), LedgerEntry.Other);
|
||
Assert.Equal(cents, c.NetWorth.Cents);
|
||
}
|
||
SetNetWorth(req.NetWorth * 997 / 1000);
|
||
var near = ClimbOutlook.Requirements(w, c, def);
|
||
Assert.True(near.TownsMet && near.RatingMet && !near.NetWorthMet, "manca solo il patrimonio");
|
||
Assert.False(Tiers.Meets(w, c, req));
|
||
Assert.True(near.Progress < 1 && near.Progress <= ClimbOutlook.ProgressCap, $"avanzamento {near.Progress}");
|
||
Assert.Equal(99.0, Math.Floor(near.Progress * 100), "per difetto si legge 99 %");
|
||
Assert.Equal(99.0, Math.Floor(near.NetWorthFraction * 100), "patrimonio al 99 %");
|
||
|
||
SetNetWorth(req.NetWorth);
|
||
var met = ClimbOutlook.Requirements(w, c, def);
|
||
Assert.True(met.AllMet && Tiers.Meets(w, c, req));
|
||
Assert.Equal(1.0, met.Progress);
|
||
|
||
// immagine 08: 65 % del patrimonio, 1 città su 2, BBB verso A danno il 58 %
|
||
double rating = ClimbOutlook.RatingFraction(w, CreditRating.BBB, CreditRating.A);
|
||
Assert.Approx(0.6, rating, 1e-12);
|
||
Assert.Equal(58.0, Math.Floor((0.65 + 0.5 + rating) / 3 * 100));
|
||
Assert.Equal(1.0, ClimbOutlook.RatingFraction(w, CreditRating.A, CreditRating.A));
|
||
}
|
||
|
||
[Test(Description = "Lo storico del patrimonio ha un punto per anno di calendario: oggi sostituisce la fotografia del primo giorno dell'anno")]
|
||
public static void HistoryHasOnePointPerCalendarYear()
|
||
{
|
||
var w = TestWorlds.NoAi(1805);
|
||
var c = w.Player;
|
||
int dpy = w.Calendar.DaysPerYear, start = w.Calendar.StartYear;
|
||
Assert.Equal(0L, c.FoundedDay);
|
||
w.Clock.Restore((3L * dpy + 100) * w.Calendar.TicksPerDay);
|
||
for (int y = 0; y < 3; y++) c.History.Add(new CompanyYear(start + y, 1_000 * (y + 1), 0, 0, 0, 1, 0, 0, 0));
|
||
var points = ClimbOutlook.History(w, c);
|
||
Assert.True(points.Select(p => p.Day).SequenceEqual(new[] { 0L, dpy, 2L * dpy, w.Clock.Day }), string.Join(",", points.Select(p => p.Day)));
|
||
var years = points.Select(p => w.Calendar.DateOfDay(p.Day).Year).ToList();
|
||
Assert.Equal(years.Count, years.Distinct().Count(), "anni distinti");
|
||
Assert.Equal(new Money(2_000), points[2].Value, "fine anno dal secondo anno dello storico");
|
||
Assert.Equal(c.NetWorth, points[^1].Value);
|
||
}
|
||
|
||
[Test(Description = "Migrazione senza fatto saliente: il giorno del livello è quello della prima fotografia annuale che lo mostra (primo giorno dell'anno dopo)")]
|
||
public static void MigratedTierDayComesFromTheSnapshotDay()
|
||
{
|
||
var w = TestWorlds.NoAi(1806);
|
||
var c = w.Player;
|
||
int dpy = w.Calendar.DaysPerYear, start = w.Calendar.StartYear;
|
||
w.Clock.Restore((3L * dpy + 100) * w.Calendar.TicksPerDay);
|
||
c.Tier = 3;
|
||
c.History.Add(new CompanyYear(start, 0, 0, 0, 0, 1, 0, 0, 0));
|
||
c.History.Add(new CompanyYear(start + 1, 0, 0, 0, 0, 2, 0, 0, 0));
|
||
c.History.Add(new CompanyYear(start + 2, 0, 0, 0, 0, 3, 0, 0, 0));
|
||
Assert.False(c.Milestones.Any(m => m.Text.StartsWith("diventa", StringComparison.Ordinal)), "nessun fatto saliente dei livelli");
|
||
var v5 = new SaveWriter(1 << 20);
|
||
WorldSerializer.Write(w, v5, 5);
|
||
var mc = WorldSerializer.Read(TestData.Data, new SaveReader(v5.WrittenSpan.ToArray())).Player;
|
||
// livello 2 nella fotografia del secondo anno, scattata il primo giorno del terzo
|
||
Assert.Equal(2L * dpy, mc.TierReachedDay[1]);
|
||
Assert.Equal(3L * dpy, mc.TierReachedDay[2]);
|
||
Assert.Equal(-1L, mc.TierReachedDay[3]);
|
||
}
|
||
}
|