F6: livelli e sblocchi visibili, pannello La tua scalata
I livelli esistevano dalla F5 ma il giocatore li vedeva solo come distintivo e come rifiuti con nomi scritti a mano. Ora il motore espone un quadro della scalata e il client lo mostra come l'immagine di riferimento 08. - ClimbOutlook (Core, sola lettura): livelli con gli sblocchi letti dai dati, giorno in cui sono stati raggiunti, requisiti del prossimo livello con valore, soglia, frazione e avanzamento (media delle tre frazioni, ora anche nel Mercato globale), stato patrimoniale, conto economico, prestiti, storico del patrimonio dalla Cronaca. - Stato patrimoniale con una sola fonte: FinanceSystem.BookValues scompone il valore contabile per voce e AssetBookValue ne e' la somma, cosi' il pannello somma al centesimo al patrimonio netto del motore. Le industrie possedute entrano nel patrimonio (impianti piu' cassa, senza avviamento): prima comprarle bruciava patrimonio. - Notizia di promozione con gli sblocchi ottenuti; rifiuti dei comandi bloccati con il livello che serve e il suo nome dai dati (compravendita, industrie, quotazione, scalate, concessioni, fido). - Salvataggio versione 6 (BalanceSheetSerializer) con voci e giorni dei livelli nell'hash; le versioni 1-5 si migrano con lo stesso patrimonio. - Protocollo: DetailKind.Climb (8) e ClimbReport (134), su richiesta. - Client: pannello ClimbPanel a tutto schermo, pulsante Scalata, livello e avanzamento nella barra superiore, schermata nel pilota automatico. - Test: Economy/ClimbTests.cs e quadro via WebSocket (170 test verdi). Decisioni in docs/adr/0018-scalata-e-livelli.md. Refs #38. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a61bf1dc27
commit
d473e21708
37 files changed
+2060
-70
No files matched your search
@@ -0,0 +1,335 @@
|
||||
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);
|
||||
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<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)
|
||||
{
|
||||
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<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);
|
||||
|
||||
// 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);
|
||||
}
|
||||
}
|
||||
@@ -186,9 +186,20 @@ public static class EconomyTests
|
||||
w.Enqueue(new TakeLoanCommand(Money.FromLire(1)) { Issuer = new CompanyId(99), Seq = 10 });
|
||||
w.Pipeline.Get<CommandSystem>().Step(w.Context);
|
||||
var results = w.DrainResults();
|
||||
Assert.Equal(CommandError.NotImplemented, results[0].Error);
|
||||
// al livello 1 le concessioni si rifiutano per il livello (ADR 0018), con il livello che le sblocca
|
||||
var tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.Concessions);
|
||||
Assert.Equal(CommandError.TierLocked, results[0].Error);
|
||||
Assert.True(results[0].Message.Contains($"livello {tier.Level}, «{tier.NameIt}»"), results[0].Message);
|
||||
Assert.Equal(CommandError.UnknownCompany, results[1].Error);
|
||||
Assert.Equal(before, RailEnterprise.Core.Persistence.StateHasher.Compute(w));
|
||||
|
||||
// sbloccate dal livello, restano un comando non ancora disponibile (F7)
|
||||
w.Player.Tier = tier.Level;
|
||||
before = RailEnterprise.Core.Persistence.StateHasher.Compute(w);
|
||||
w.Enqueue(new BuyConcessionCommand(new RegionId(0)) { Issuer = w.Player.Id, Seq = 11 });
|
||||
w.Pipeline.Get<CommandSystem>().Step(w.Context);
|
||||
Assert.Equal(CommandError.NotImplemented, w.DrainResults()[0].Error);
|
||||
Assert.Equal(before, RailEnterprise.Core.Persistence.StateHasher.Compute(w));
|
||||
}
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -226,9 +226,10 @@ public static class MarketOutlookTests
|
||||
Assert.False(trading.Unlocked);
|
||||
Assert.Equal(tier.Requirements.CreditRating, trading.RatingRequired);
|
||||
Assert.InRange(trading.Fraction, 0, 1);
|
||||
double worth = Math.Clamp((double)w.Player.NetWorth.Cents / tier.Requirements.NetWorth, 0, 1);
|
||||
double towns = Math.Clamp((double)trading.TownsConnected / tier.Requirements.ConnectedTownsOver.Count, 0, 1);
|
||||
Assert.Approx(Math.Min(worth, towns), trading.Fraction, 1e-12);
|
||||
// stesso avanzamento del pannello «La tua scalata» (ADR 0018): media dei tre requisiti
|
||||
var climb = ClimbOutlook.Requirements(w, w.Player, tier);
|
||||
Assert.Approx(climb.Progress, trading.Fraction, 1e-12);
|
||||
Assert.Approx((climb.NetWorthFraction + climb.TownsFraction + climb.RatingFraction) / 3, trading.Fraction, 1e-12);
|
||||
w.Player.Tier = tier.Level;
|
||||
Assert.True(MarketOutlook.Trading(w, f.Me).Unlocked);
|
||||
Assert.Equal(1.0, MarketOutlook.Trading(w, f.Me).Fraction);
|
||||
|
||||
@@ -158,6 +158,36 @@ public static class ProtocolTests
|
||||
new WarehouseInfo { Station = 5, Capacity = 500 },
|
||||
],
|
||||
};
|
||||
yield return new ClimbReport
|
||||
{
|
||||
Day = 2600, Company = 0, FoundedDay = 0, InitialCapital = new Money(25_000_000), Tier = 2, NextTier = 3,
|
||||
Tiers =
|
||||
[
|
||||
new TierInfo
|
||||
{
|
||||
Level = 1, NameIt = "Compagnia locale", NameEn = "Local company", RatingRequired = "D", Reached = true, ReachedDay = 0,
|
||||
Unlocks = [new UnlockInfo { Kind = UnlockInfo.LoanLimit, Value = 50_000_000 }, new UnlockInfo { Kind = UnlockInfo.Crews, Value = 2 }],
|
||||
},
|
||||
new TierInfo
|
||||
{
|
||||
Level = 3, NameIt = "Compagnia nazionale", NameEn = "National company", NetWorthRequired = new Money(100_000_000), TownsRequired = 3,
|
||||
TownPopulation = 1000, RatingRequired = "BBB", Reached = false, ReachedDay = -1,
|
||||
Unlocks = [new UnlockInfo { Kind = UnlockInfo.BuyIndustry }, new UnlockInfo { Kind = UnlockInfo.Concessions }],
|
||||
},
|
||||
],
|
||||
NetWorth = new Money(65_000_000), NetWorthRequired = new Money(100_000_000), NetWorthFraction = 0.65f, NetWorthMet = false,
|
||||
Towns = 1, TownsRequired = 3, TownPopulation = 1000, TownsFraction = 0.333f, TownsMet = false,
|
||||
Rating = "BBB", RatingRequired = "BBB", RatingFraction = 1, RatingMet = true, Progress = 0.661f,
|
||||
Assets = [new AmountInfo { Kind = ClimbReport.AssetTrack, Value = new Money(24_500_000) }, new AmountInfo { Kind = ClimbReport.AssetGoods, Value = new Money(-3) }],
|
||||
Portfolio = new Money(1_000), Cash = new Money(12_845_000), TotalAssets = new Money(51_145_000), Loans = new Money(12_000_000), LoansRate = 0.055f,
|
||||
Overdraft = new Money(7), TotalLiabilities = new Money(12_000_007), BalanceNetWorth = new Money(39_144_993),
|
||||
IncomeYear = 1871, IncomePartial = true,
|
||||
Income = [new AmountInfo { Kind = ClimbReport.IncomeFares, Value = new Money(19_600_000) }, new AmountInfo { Kind = ClimbReport.IncomeInterest, Value = new Money(-660_000) }],
|
||||
Profit = new Money(5_440_000),
|
||||
LoanList = [new LoanInfo { Loan = 4, Remaining = new Money(12_000_000), AnnualRate = 0.055f, MonthsLeft = 97 }],
|
||||
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 CommandResultMessage { Seq = 99, Type = (ushort)CommandType.BuildTrack, Error = 10, Message = "Pendenza eccessiva", Created = [1, 2, 3], Tick = 4000 };
|
||||
yield return new Notification { Event = SampleEvent() };
|
||||
yield return new Newspaper { Day = 30, Title = "La Cronaca di Valdoria", Articles = [("Nuova linea", "Inaugurata la linea per il valico."), ("Prezzi", "Il carbone sale.")] };
|
||||
|
||||
@@ -309,6 +309,48 @@ public static class ServerTests
|
||||
Assert.True(report.TradingProgress is >= 0 and < 1, $"avanzamento {report.TradingProgress}");
|
||||
}
|
||||
|
||||
[Test(Description = "F6 in rete: il quadro della scalata arriva su richiesta con livelli, sblocchi, requisiti e stato patrimoniale")]
|
||||
public static void ClimbReportOnRequest() => RunClimb().GetAwaiter().GetResult();
|
||||
|
||||
private static async Task RunClimb()
|
||||
{
|
||||
var scenario = ScenarioHelper.Load("valdoria");
|
||||
await using var server = ServerFixture.Start(scenario.World);
|
||||
await using var client = await TestClient.ConnectAsync(server);
|
||||
var w = client.World;
|
||||
var data = TestData.Data;
|
||||
await client.WaitUntil(() => w.LastDigest is { Day: >= 2 }, "due giorni di partita");
|
||||
|
||||
// il server non manda il quadro da solo: si aspetta la risposta a questa richiesta
|
||||
Assert.True(w.Climb is null, "nessun quadro prima della richiesta");
|
||||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Climb, Target = 0 });
|
||||
var report = await client.WaitFor(() => w.Climb, "quadro della scalata");
|
||||
Assert.True(report.Day >= 2, $"giorno {report.Day}");
|
||||
Assert.Equal(w.Summary!.CompanyId, report.Company);
|
||||
Assert.Equal((byte)1, report.Tier);
|
||||
Assert.Equal((byte)2, report.NextTier);
|
||||
Assert.Equal(data.Tiers.Tiers.Count, report.Tiers.Count);
|
||||
var tier = data.Tiers.Tiers[1];
|
||||
Assert.Equal(tier.NameIt, report.Tiers[1].NameIt);
|
||||
Assert.Equal(new Money(tier.Requirements.NetWorth), report.NetWorthRequired);
|
||||
Assert.Equal(tier.Requirements.CreditRating.ToString(), report.RatingRequired);
|
||||
Assert.True(report.Tiers[0].Reached && !report.Tiers[1].Reached, "solo il livello 1 raggiunto");
|
||||
Assert.True(report.Tiers[1].Unlocks.Any(u => u.Kind == UnlockInfo.Trading), "il livello 2 sblocca il commercio");
|
||||
Assert.True(report.Progress is >= 0 and < 1, $"avanzamento {report.Progress}");
|
||||
Assert.Equal(report.BalanceNetWorth, report.TotalAssets - report.TotalLiabilities);
|
||||
Assert.Equal(5, report.Assets.Count);
|
||||
Assert.True(report.History.Count >= 1, "storico del patrimonio");
|
||||
|
||||
// dopo un prestito una nuova richiesta riporta il debito: si aspetta la risposta nuova, non quella vecchia
|
||||
var result = await client.Do(new TakeLoanCommand(Money.FromLire(5_000)));
|
||||
Assert.True(result.Error == 0, result.Message);
|
||||
var stale = w.Climb;
|
||||
await client.Connection.SendAsync(new RequestDetail { Kind = DetailKind.Climb, Target = 0 });
|
||||
var after = await client.WaitFor(() => ReferenceEquals(w.Climb, stale) ? null : w.Climb, "quadro aggiornato");
|
||||
Assert.Equal(1, after.LoanList.Count);
|
||||
Assert.Equal(Money.FromLire(5_000), after.Loans);
|
||||
}
|
||||
|
||||
[Test(Description = "Hello con token errato, dati diversi o protocollo vecchio riceve Reject")]
|
||||
public static void HandshakeRejections() => RunRejections().GetAwaiter().GetResult();
|
||||
|
||||
|
||||
Reference in new issue
Block a user