F6: livelli e sblocchi visibili, pannello «La tua scalata» #40
No files matched your search
@@ -550,3 +550,57 @@ entro,,within
|
||||
fino al,,until
|
||||
da domani,,from tomorrow
|
||||
dal,,from
|
||||
La tua scalata,,Your climb
|
||||
Stato patrimoniale,,Balance sheet
|
||||
Chiedi un prestito,,Request a loan
|
||||
In attesa del quadro dal server…,,Waiting for the report from the server…
|
||||
Fido fino a,,Credit up to
|
||||
squadre di cantiere,,construction crews
|
||||
Acquisto di industrie,,Industry purchases
|
||||
Scalate ai concorrenti,,Takeovers of rivals
|
||||
Concessioni,,Concessions
|
||||
fondata nel,,founded in
|
||||
con,,with
|
||||
verso,,towards
|
||||
raggiunta nel,,reached in
|
||||
raggiunta,,reached
|
||||
avanzamento,,progress
|
||||
patrimonio,,net worth
|
||||
Lo storico cresce anno dopo anno,,The history grows year by year
|
||||
a,,to
|
||||
in,,in
|
||||
anno,,year
|
||||
Hai raggiunto il livello più alto,,You have reached the highest tier
|
||||
Per diventare,,To become
|
||||
Patrimonio netto di,,Net worth of
|
||||
città oltre,,towns over
|
||||
collegata su,,connected out of
|
||||
collegate su,,connected out of
|
||||
Rating creditizio,,Credit rating
|
||||
attuale,,current
|
||||
Binari e opere,,Track and structures
|
||||
Stazioni e depositi,,Stations and depots
|
||||
Materiale rotabile,,Rolling stock
|
||||
Industrie possedute,,Owned industries
|
||||
Merce propria,,Own goods
|
||||
Partecipazioni,,Shareholdings
|
||||
Totale attivo,,Total assets
|
||||
Prestiti al,,Loans at
|
||||
Prestiti,,Loans
|
||||
Scoperto di cassa,,Overdraft
|
||||
Conto economico,,Income statement
|
||||
(finora),,(so far)
|
||||
Ricavi da tariffe e noli,,Fares and freight revenue
|
||||
Altri ricavi,,Other income
|
||||
Costi operativi,,Operating costs
|
||||
Interessi,,Interest
|
||||
Utile netto,,Net profit
|
||||
Rimborsa,,Repay
|
||||
Fido disponibile,,Available credit
|
||||
su,,of
|
||||
al,,at
|
||||
In amministrazione controllata non si possono chiedere prestiti,,Loans cannot be requested under receivership
|
||||
livello più alto,,highest tier
|
||||
prossimo,,next
|
||||
Clic per aprire «La tua scalata»,,Click to open «Your climb»
|
||||
Scalata,,Climb
|
||||
|
@@ -240,6 +240,11 @@ public partial class AutoPilot : Node
|
||||
await Until(() => World.Market is not null, "quadro del mercato", 30);
|
||||
await Shot("16_mercato", 40);
|
||||
|
||||
// La tua scalata (immagine 08): livelli, sblocchi, requisiti, stato patrimoniale
|
||||
_game.OpenClimb();
|
||||
await Until(() => World.Climb is not null, "quadro della scalata", 30);
|
||||
await Shot("17_scalata", 40);
|
||||
|
||||
// Cronaca provvisoria
|
||||
_game.OpenChronicle();
|
||||
await Until(() => _game.ChronicleVisible, "cronaca", 30);
|
||||
|
||||
@@ -5,7 +5,7 @@ using static RailEnterprise.Client.App.Localization;
|
||||
namespace RailEnterprise.Client.Hud;
|
||||
|
||||
/// <summary>Strumenti e pannelli della barra sinistra (immagine 01).</summary>
|
||||
public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Maintenance, Employment, Industries, Market, Companies, Finance, Demolish }
|
||||
public enum Tool { None, Track, Station, Signal, Depot, Trains, Lines, Maintenance, Employment, Industries, Market, Companies, Climb, Finance, Demolish }
|
||||
|
||||
/// <summary>
|
||||
/// Barra degli strumenti a sinistra: icone disegnate in codice con l'etichetta sotto. I pulsanti
|
||||
@@ -37,7 +37,7 @@ public partial class Toolbar : PanelContainer
|
||||
{
|
||||
(Tool.Track, "Binari"), (Tool.Station, "Stazione"), (Tool.Signal, "Segnali"), (Tool.Depot, "Deposito"),
|
||||
(Tool.Trains, "Treni"), (Tool.Lines, "Linee"), (Tool.Maintenance, "Officine"), (Tool.Employment, "Impieghi"),
|
||||
(Tool.Industries, "Industrie"), (Tool.Market, "Mercato"), (Tool.Companies, "Compagnie"), (Tool.Finance, "Finanze"),
|
||||
(Tool.Industries, "Industrie"), (Tool.Market, "Mercato"), (Tool.Companies, "Compagnie"), (Tool.Climb, "Scalata"), (Tool.Finance, "Finanze"),
|
||||
(Tool.Demolish, "Demolisci"),
|
||||
})
|
||||
{
|
||||
@@ -159,6 +159,13 @@ public partial class Toolbar : PanelContainer
|
||||
DrawPolyline([c + new Vector2(-11, 8), c + new Vector2(-4, 0), c + new Vector2(2, 5), c + new Vector2(11, -7)], col, w);
|
||||
DrawLine(c + new Vector2(-11, 11), c + new Vector2(11, 11), col, w);
|
||||
break;
|
||||
case Tool.Climb:
|
||||
// gradini che salgono verso una bandierina
|
||||
DrawPolyline([c + new Vector2(-11, 11), c + new Vector2(-11, 5), c + new Vector2(-4, 5), c + new Vector2(-4, -1),
|
||||
c + new Vector2(3, -1), c + new Vector2(3, -7), c + new Vector2(10, -7), c + new Vector2(10, 11), c + new Vector2(-11, 11)], col, w);
|
||||
DrawLine(c + new Vector2(10, -7), c + new Vector2(10, -13), col, w);
|
||||
DrawColoredPolygon([c + new Vector2(10, -13), c + new Vector2(4, -11), c + new Vector2(10, -9)], col);
|
||||
break;
|
||||
case Tool.Finance:
|
||||
DrawArc(c + new Vector2(0, -7), 9, 0, MathF.Tau, 24, col, w);
|
||||
DrawLine(c + new Vector2(-9, -7), c + new Vector2(-9, 7), col, w);
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Client.Panels;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Hud;
|
||||
@@ -11,6 +13,12 @@ public partial class TopBar : PanelContainer
|
||||
private GameSession? _session;
|
||||
private readonly Label _company = UiTheme.TitleLabel("", 30);
|
||||
private readonly PanelContainer _tier = UiTheme.Badge("");
|
||||
private readonly Label _climb = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private long _climbRequestedMonth = long.MinValue;
|
||||
private double _sinceClimbRequest = double.MaxValue;
|
||||
|
||||
/// <summary>Clic sul livello: apre «La tua scalata».</summary>
|
||||
public event Action? ClimbRequested;
|
||||
private readonly Label _date = UiTheme.Text("", 17, bold: true);
|
||||
private readonly Label _cash = UiTheme.Text("", 20, Palette.AmberLight, bold: true);
|
||||
private readonly Label _worth = UiTheme.Text("", 20, bold: true);
|
||||
@@ -18,6 +26,7 @@ public partial class TopBar : PanelContainer
|
||||
private readonly Label _server = UiTheme.Text("", 14);
|
||||
private readonly ColorRect _serverDot = new() { CustomMinimumSize = new Vector2(10, 10) };
|
||||
private readonly List<Button> _speeds = [];
|
||||
private VBoxContainer? _tierBox;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
@@ -28,9 +37,22 @@ public partial class TopBar : PanelContainer
|
||||
AddChild(row);
|
||||
row.AddChild(new Logo { CustomMinimumSize = new Vector2(40, 40) });
|
||||
row.AddChild(_company);
|
||||
var tierBox = new CenterContainer();
|
||||
tierBox.AddChild(_tier);
|
||||
// livello attuale e avanzamento verso il prossimo (dal quadro della scalata): un clic apre il pannello
|
||||
var tierBox = new VBoxContainer { Alignment = BoxContainer.AlignmentMode.Center, MouseFilter = MouseFilterEnum.Stop };
|
||||
tierBox.AddThemeConstantOverride("separation", 2);
|
||||
tierBox.MouseDefaultCursorShape = CursorShape.PointingHand;
|
||||
var badgeRow = new HBoxContainer();
|
||||
badgeRow.AddChild(_tier);
|
||||
tierBox.AddChild(badgeRow);
|
||||
tierBox.AddChild(_climb);
|
||||
tierBox.GuiInput += e =>
|
||||
{
|
||||
if (e is InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left }) ClimbRequested?.Invoke();
|
||||
};
|
||||
_tier.MouseFilter = MouseFilterEnum.Pass;
|
||||
_climb.MouseFilter = MouseFilterEnum.Pass;
|
||||
row.AddChild(tierBox);
|
||||
_tierBox = tierBox;
|
||||
row.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
|
||||
row.AddChild(_date);
|
||||
var speeds = new HBoxContainer();
|
||||
@@ -83,7 +105,24 @@ public partial class TopBar : PanelContainer
|
||||
var me = w.Companies.GetValueOrDefault(w.Summary.CompanyId);
|
||||
_company.Text = me?.Name ?? w.Summary.CompanyName;
|
||||
int tier = Math.Clamp(me?.Tier ?? 1, 1, w.Data.Tiers.Tiers.Count);
|
||||
((Label)_tier.GetChild(0)).Text = TranslationServer.GetLocale().StartsWith("en") ? w.Data.Tiers.Tiers[tier - 1].NameEn : w.Data.Tiers.Tiers[tier - 1].NameIt;
|
||||
((Label)_tier.GetChild(0)).Text = $"{tier} · {Fmt.Tier(w, tier)}";
|
||||
// il quadro della scalata si chiede una volta al mese di gioco (il pannello lo chiede ogni giorno), e
|
||||
// di nuovo dopo 5 s se manca: uno stato completo (ripresa della sessione, nuova partita) lo azzera
|
||||
_sinceClimbRequest += delta;
|
||||
long month = w.Calendar is { } cal ? Fmt.Today(w) / cal.DaysPerMonth : 0;
|
||||
if ((month != _climbRequestedMonth || (w.Climb is null && _sinceClimbRequest > 5)) && _session!.IsOpen)
|
||||
{
|
||||
_climbRequestedMonth = month;
|
||||
_sinceClimbRequest = 0;
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Climb, Target = 0 });
|
||||
}
|
||||
var climb = w.Climb;
|
||||
bool top = tier >= w.Data.Tiers.Tiers.Count;
|
||||
_climb.Text = top ? T("livello più alto")
|
||||
: climb is not null && climb.Tier == tier ? $"{Fmt.Progress(climb.Progress)} {T("verso")} {Fmt.Tier(w, tier + 1)}"
|
||||
: $"{T("prossimo")}: {Fmt.Tier(w, tier + 1)}";
|
||||
if (_tierBox is not null)
|
||||
_tierBox.TooltipText = $"{T("Livello")} {tier} {T("di")} {w.Data.Tiers.Tiers.Count}. {T("Clic per aprire «La tua scalata»")}";
|
||||
_date.Text = w.LastDigest?.Date ?? w.Summary.Date;
|
||||
_cash.Text = (w.LastDigest?.Cash ?? me?.Cash ?? default).ToString();
|
||||
_worth.Text = (w.LastDigest?.NetWorth ?? me?.NetWorth ?? default).ToString("short");
|
||||
|
||||
@@ -0,0 +1,463 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Protocol.Client;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Panels;
|
||||
|
||||
/// <summary>
|
||||
/// «La tua scalata» a tutto schermo (immagine di riferimento 08): in alto il binario dei livelli con
|
||||
/// il treno che avanza verso il prossimo, sotto ogni stazione il nome, quando è stato raggiunto (o
|
||||
/// l'avanzamento, o il patrimonio richiesto) e gli sblocchi; a sinistra lo storico del patrimonio
|
||||
/// netto con i livelli raggiunti e i requisiti del prossimo livello; a destra lo stato patrimoniale,
|
||||
/// il conto economico e i prestiti. Tutti i numeri arrivano dal server (ClimbReport, ADR 0018): il
|
||||
/// pannello li chiede all'apertura, a ogni nuovo giorno e dopo un prestito, e li mostra com'è.
|
||||
/// </summary>
|
||||
public partial class ClimbPanel : VBoxContainer
|
||||
{
|
||||
private readonly GameSession _session;
|
||||
private readonly Label _subtitle = UiTheme.Text("", 14, Palette.TextSecondary);
|
||||
private readonly Label _worth = UiTheme.Text("", 30, Palette.AmberLight, bold: true);
|
||||
private readonly TierTrack _track = new();
|
||||
private readonly HBoxContainer _stations = PanelKit.Row(8);
|
||||
private readonly Label _historyCaption = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private readonly SeriesChart _chart = new(250);
|
||||
private readonly Label _nextTitle = UiTheme.Text("", 16, bold: true);
|
||||
private readonly HBoxContainer _requirements = PanelKit.Row(24);
|
||||
private readonly VBoxContainer _balance = PanelKit.Column(6);
|
||||
private readonly Label _incomeTitle = UiTheme.Text("", 20, bold: true);
|
||||
private readonly VBoxContainer _income = PanelKit.Column(6);
|
||||
private readonly SpinBox _amount = new() { MinValue = 1_000, MaxValue = 100_000_000, Step = 1_000, Value = 50_000, Prefix = "₤", CustomMinimumSize = new Vector2(150, 0) };
|
||||
private readonly Button _borrow = new() { Text = "", CustomMinimumSize = new Vector2(0, 48), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly Button _repay = new() { Text = "", CustomMinimumSize = new Vector2(0, 48), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
private readonly Label _status = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private ClimbReport? _shown;
|
||||
private long _requestedDay = long.MinValue;
|
||||
private double _sinceRequest = double.MaxValue;
|
||||
|
||||
public event Action? CloseRequested;
|
||||
|
||||
public ClimbPanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
AddThemeConstantOverride("separation", 16);
|
||||
SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
|
||||
var header = PanelKit.Row(24);
|
||||
var titles = PanelKit.Column(0);
|
||||
titles.AddChild(UiTheme.TitleLabel(T("La tua scalata"), 44));
|
||||
titles.AddChild(_subtitle);
|
||||
header.AddChild(titles);
|
||||
var worth = PanelKit.Column(0);
|
||||
worth.SizeFlagsHorizontal = SizeFlags.ShrinkEnd;
|
||||
worth.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
var worthCaption = UiTheme.Text(T("Patrimonio netto"), 13, Palette.TextSecondary);
|
||||
worthCaption.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
_worth.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
worth.AddChild(worthCaption);
|
||||
worth.AddChild(_worth);
|
||||
header.AddChild(worth);
|
||||
var close = new Button { Text = T("Torna alla mappa"), SizeFlagsVertical = SizeFlags.ShrinkCenter, CustomMinimumSize = new Vector2(170, 48) };
|
||||
close.Pressed += () => CloseRequested?.Invoke();
|
||||
header.AddChild(close);
|
||||
AddChild(header);
|
||||
|
||||
// binario dei livelli
|
||||
var trackCard = Card();
|
||||
var trackCol = (VBoxContainer)trackCard.GetChild(0);
|
||||
trackCol.AddChild(_track);
|
||||
trackCol.AddChild(_stations);
|
||||
AddChild(trackCard);
|
||||
|
||||
var body = PanelKit.Row(20);
|
||||
body.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
AddChild(body);
|
||||
|
||||
var left = Column(body, 1.15f);
|
||||
var historyHeader = PanelKit.Row(8);
|
||||
var historyTitle = UiTheme.Text(T("Patrimonio netto"), 20, bold: true);
|
||||
historyTitle.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
historyHeader.AddChild(historyTitle);
|
||||
_historyCaption.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
historyHeader.AddChild(_historyCaption);
|
||||
left.AddChild(historyHeader);
|
||||
left.AddChild(_chart);
|
||||
left.AddChild(_nextTitle);
|
||||
left.AddChild(_requirements);
|
||||
|
||||
var right = Column(body, 0.85f);
|
||||
right.AddChild(UiTheme.Text(T("Stato patrimoniale"), 20, bold: true));
|
||||
right.AddChild(_balance);
|
||||
right.AddChild(new Control { CustomMinimumSize = new Vector2(0, 6) });
|
||||
right.AddChild(_incomeTitle);
|
||||
right.AddChild(_income);
|
||||
right.AddChild(new Control { SizeFlagsVertical = SizeFlags.ExpandFill });
|
||||
var loanRow = PanelKit.Row(10);
|
||||
loanRow.AddChild(_amount);
|
||||
loanRow.AddChild(_borrow);
|
||||
loanRow.AddChild(_repay);
|
||||
right.AddChild(loanRow);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
right.AddChild(_status);
|
||||
_borrow.Text = T("Chiedi un prestito");
|
||||
_borrow.Pressed += Borrow;
|
||||
_repay.Pressed += Repay;
|
||||
_amount.ValueChanged += _ => UpdateLoanButtons();
|
||||
|
||||
_subtitle.Text = T("In attesa del quadro dal server…");
|
||||
}
|
||||
|
||||
private static PanelContainer Card()
|
||||
{
|
||||
var card = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
card.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 24));
|
||||
card.AddChild(PanelKit.Column(10));
|
||||
return card;
|
||||
}
|
||||
|
||||
private static VBoxContainer Column(HBoxContainer body, float ratio)
|
||||
{
|
||||
var frame = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill, SizeFlagsStretchRatio = ratio };
|
||||
frame.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 12, 24));
|
||||
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
frame.AddChild(scroll);
|
||||
var margin = new MarginContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
margin.AddThemeConstantOverride("margin_right", 10);
|
||||
scroll.AddChild(margin);
|
||||
var col = PanelKit.Column(12);
|
||||
col.SizeFlagsVertical = SizeFlags.ExpandFill;
|
||||
margin.AddChild(col);
|
||||
body.AddChild(frame);
|
||||
return col;
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
var w = _session.World;
|
||||
_sinceRequest += delta;
|
||||
// il quadro si chiede all'apertura e a ogni nuovo giorno (di nuovo dopo 5 s se non arriva)
|
||||
long today = Fmt.Today(w);
|
||||
if (today != _requestedDay || (w.Climb is null && _sinceRequest > 5)) Request(today);
|
||||
if (w.Climb is { } report && !ReferenceEquals(report, _shown)) Refresh(w, report);
|
||||
}
|
||||
|
||||
private void Request(long day)
|
||||
{
|
||||
_requestedDay = day;
|
||||
_sinceRequest = 0;
|
||||
_session.Send(new RequestDetail { Kind = DetailKind.Climb, Target = 0 });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ dati di comodo (solo lettura)
|
||||
|
||||
private static int YearOf(ClientWorld w, long day) =>
|
||||
w.Calendar is { } c ? c.DateOfDay(Math.Max(0, day)).Year : 0;
|
||||
|
||||
private static string TierName(TierInfo t) =>
|
||||
TranslationServer.GetLocale().StartsWith("en") ? t.NameEn : t.NameIt;
|
||||
|
||||
private static string Short(Money m) => m.ToString("short");
|
||||
|
||||
/// <summary>Sblocco nella lingua dell'interfaccia (i valori arrivano dal server).</summary>
|
||||
public static string UnlockText(UnlockInfo u) => u.Kind switch
|
||||
{
|
||||
UnlockInfo.LoanLimit => $"{T("Fido fino a")} {Short(new Money(u.Value))}",
|
||||
UnlockInfo.Crews => $"{u.Value} {T("squadre di cantiere")}",
|
||||
UnlockInfo.Trading => T("Compravendita in proprio"),
|
||||
UnlockInfo.BuyIndustry => T("Acquisto di industrie"),
|
||||
UnlockInfo.Ipo => T("Quotazione in borsa"),
|
||||
UnlockInfo.HostileTakeover => T("Scalate ai concorrenti"),
|
||||
UnlockInfo.Concessions => T("Concessioni"),
|
||||
_ => "",
|
||||
};
|
||||
|
||||
// ------------------------------------------------------------------ aggiornamento
|
||||
|
||||
private void Refresh(ClientWorld w, ClimbReport report)
|
||||
{
|
||||
_shown = report;
|
||||
string company = Fmt.Company(w, report.Company);
|
||||
_subtitle.Text = $"{company}, {T("fondata nel")} {YearOf(w, report.FoundedDay)} {T("con")} {report.InitialCapital}";
|
||||
_worth.Text = report.BalanceNetWorth.ToString();
|
||||
RefreshTrack(w, report);
|
||||
RefreshHistory(w, report);
|
||||
RefreshRequirements(report);
|
||||
RefreshBalance(report);
|
||||
RefreshIncome(report);
|
||||
UpdateLoanButtons();
|
||||
}
|
||||
|
||||
private void RefreshTrack(ClientWorld w, ClimbReport report)
|
||||
{
|
||||
var next = report.Tiers.FirstOrDefault(t => t.Level == report.NextTier);
|
||||
_track.Set(report.Tiers.Count, report.Tier, report.NextTier > 0 ? report.Progress : 1,
|
||||
next is null ? "" : $"{Fmt.Progress(report.Progress)} {T("verso")} {TierName(next)}");
|
||||
foreach (var c in _stations.GetChildren()) c.QueueFree();
|
||||
foreach (var t in report.Tiers)
|
||||
{
|
||||
bool current = t.Level == report.Tier, isNext = t.Level == report.NextTier;
|
||||
var col = PanelKit.Column(2);
|
||||
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
var name = UiTheme.TitleLabel(TierName(t), 30, current ? Palette.AmberLight : t.Reached || isNext ? Palette.Text : Palette.TextSecondary);
|
||||
name.HorizontalAlignment = HorizontalAlignment.Center;
|
||||
col.AddChild(name);
|
||||
string status = t.Level == 1 ? $"{T("dal")} {YearOf(w, t.ReachedDay)}"
|
||||
: t.Reached ? (t.ReachedDay >= 0 ? $"{T("raggiunta nel")} {YearOf(w, t.ReachedDay)}" : T("raggiunta"))
|
||||
: isNext ? $"{T("avanzamento")} {Fmt.Progress(report.Progress)}"
|
||||
: $"{T("patrimonio")} {Short(t.NetWorthRequired)}";
|
||||
var statusLabel = UiTheme.Text(status, 14, current ? Palette.AmberLight : Palette.Text, bold: true);
|
||||
statusLabel.HorizontalAlignment = HorizontalAlignment.Center;
|
||||
col.AddChild(statusLabel);
|
||||
col.AddChild(new Control { CustomMinimumSize = new Vector2(0, 8) });
|
||||
foreach (var u in t.Unlocks)
|
||||
{
|
||||
var l = UiTheme.Text(UnlockText(u), 13, Palette.TextSecondary);
|
||||
l.HorizontalAlignment = HorizontalAlignment.Center;
|
||||
l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
col.AddChild(l);
|
||||
}
|
||||
_stations.AddChild(col);
|
||||
}
|
||||
}
|
||||
|
||||
private void RefreshHistory(ClientWorld w, ClimbReport report)
|
||||
{
|
||||
var values = report.History.Select(p => (double)p.Value.Cents).ToList();
|
||||
var labels = report.History.Select(p => YearOf(w, p.Day).ToString()).ToList();
|
||||
_chart.Show(values, labels, v => new Money((long)v).ToString("short"), SeriesChart.Style.Line, Palette.Amber, T("Lo storico cresce anno dopo anno"));
|
||||
// i livelli raggiunti si segnano sul punto dell'anno della promozione (un punto per anno di
|
||||
// calendario, l'ultimo è oggi); in mancanza sul primo punto dopo la promozione
|
||||
var markers = new List<(int Index, string Label)>();
|
||||
foreach (var t in report.Tiers.Where(t => t.Level > 1 && t.Reached && t.ReachedDay >= 0))
|
||||
{
|
||||
int year = YearOf(w, t.ReachedDay);
|
||||
int index = report.History.FindIndex(p => YearOf(w, p.Day) == year);
|
||||
if (index < 0) index = report.History.FindIndex(p => p.Day >= t.ReachedDay);
|
||||
if (index >= 0) markers.Add((index, TierName(t)));
|
||||
}
|
||||
_chart.SetMarkers(markers);
|
||||
if (report.History.Count >= 2)
|
||||
{
|
||||
var first = report.History[0];
|
||||
var last = report.History[^1];
|
||||
int years = Math.Max(0, YearOf(w, last.Day) - YearOf(w, first.Day));
|
||||
_historyCaption.Text = $"{T("da")} {first.Value} {T("a")} {Short(last.Value)} {T("in")} {years} {(years == 1 ? T("anno") : T("anni"))}";
|
||||
}
|
||||
else _historyCaption.Text = "";
|
||||
}
|
||||
|
||||
private void RefreshRequirements(ClimbReport report)
|
||||
{
|
||||
foreach (var c in _requirements.GetChildren()) c.QueueFree();
|
||||
var next = report.Tiers.FirstOrDefault(t => t.Level == report.NextTier);
|
||||
if (next is null)
|
||||
{
|
||||
_nextTitle.Text = T("Hai raggiunto il livello più alto");
|
||||
return;
|
||||
}
|
||||
_nextTitle.Text = $"{T("Per diventare")} {TierName(next)}";
|
||||
_requirements.AddChild(Requirement($"{T("Patrimonio netto di")} {Short(report.NetWorthRequired)}", report.NetWorthFraction, report.NetWorthMet,
|
||||
$"{Short(report.NetWorth)}, {Fmt.Progress(report.NetWorthFraction)}"));
|
||||
_requirements.AddChild(Requirement($"{report.TownsRequired} {T("città oltre")} {Fmt.Number(report.TownPopulation, 0)} {T("abitanti")}",
|
||||
report.TownsFraction, report.TownsMet, $"{report.Towns} {(report.Towns == 1 ? T("collegata su") : T("collegate su"))} {report.TownsRequired}"));
|
||||
_requirements.AddChild(Requirement($"{T("Rating creditizio")} {report.RatingRequired}", report.RatingFraction, report.RatingMet,
|
||||
$"{T("attuale")} {report.Rating}"));
|
||||
}
|
||||
|
||||
private static Control Requirement(string caption, float fraction, bool met, string value)
|
||||
{
|
||||
var col = PanelKit.Column(6);
|
||||
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
col.AddChild(UiTheme.Text(caption, 14));
|
||||
var color = met ? Palette.Ok : Palette.Amber;
|
||||
var bar = new ProgressBar { MinValue = 0, MaxValue = 1, Step = 0.001, Value = Math.Clamp(fraction, 0, 1), ShowPercentage = false, CustomMinimumSize = new Vector2(0, 8) };
|
||||
bar.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 4, 0));
|
||||
bar.AddThemeStyleboxOverride("fill", UiTheme.Box(color, color, 4, 0));
|
||||
col.AddChild(bar);
|
||||
col.AddChild(UiTheme.Text((met ? "✓ " : "") + value, 13, met ? Palette.Ok : Palette.TextSecondary));
|
||||
return col;
|
||||
}
|
||||
|
||||
private static string AssetName(byte kind) => kind switch
|
||||
{
|
||||
ClimbReport.AssetTrack => T("Binari e opere"),
|
||||
ClimbReport.AssetStations => T("Stazioni e depositi"),
|
||||
ClimbReport.AssetVehicles => T("Materiale rotabile"),
|
||||
ClimbReport.AssetIndustries => T("Industrie possedute"),
|
||||
ClimbReport.AssetGoods => T("Merce propria"),
|
||||
_ => "",
|
||||
};
|
||||
|
||||
private void RefreshBalance(ClimbReport report)
|
||||
{
|
||||
foreach (var c in _balance.GetChildren()) c.QueueFree();
|
||||
foreach (var a in report.Assets)
|
||||
{
|
||||
// le voci di base si vedono sempre, industrie e merce solo se ci sono
|
||||
bool always = a.Kind is ClimbReport.AssetTrack or ClimbReport.AssetStations or ClimbReport.AssetVehicles;
|
||||
if (always || a.Value.Cents != 0) _balance.AddChild(Line(AssetName(a.Kind), a.Value.ToString()));
|
||||
}
|
||||
if (report.Portfolio.Cents != 0) _balance.AddChild(Line(T("Partecipazioni"), report.Portfolio.ToString()));
|
||||
_balance.AddChild(Line(T("Cassa"), report.Cash.ToString()));
|
||||
_balance.AddChild(PanelKit.Separator());
|
||||
_balance.AddChild(Line(T("Totale attivo"), report.TotalAssets.ToString(), bold: true));
|
||||
string loans = report.Loans.Cents > 0 ? $"{T("Prestiti al")} {Fmt.Pct(report.LoansRate, 1)}" : T("Prestiti");
|
||||
_balance.AddChild(Line(loans, report.Loans.ToString()));
|
||||
if (report.Overdraft.Cents > 0) _balance.AddChild(Line(T("Scoperto di cassa"), report.Overdraft.ToString(), color: Palette.Danger));
|
||||
_balance.AddChild(Line(T("Patrimonio netto"), report.BalanceNetWorth.ToString(), bold: true, color: Palette.AmberLight));
|
||||
}
|
||||
|
||||
private void RefreshIncome(ClimbReport report)
|
||||
{
|
||||
_incomeTitle.Text = $"{T("Conto economico")} {report.IncomeYear}{(report.IncomePartial ? " " + T("(finora)") : "")}";
|
||||
foreach (var c in _income.GetChildren()) c.QueueFree();
|
||||
foreach (var i in report.Income)
|
||||
{
|
||||
string name = i.Kind switch
|
||||
{
|
||||
ClimbReport.IncomeFares => T("Ricavi da tariffe e noli"),
|
||||
ClimbReport.IncomeOther => T("Altri ricavi"),
|
||||
ClimbReport.IncomeOperating => T("Costi operativi"),
|
||||
ClimbReport.IncomeMaintenance => T("Manutenzione"),
|
||||
ClimbReport.IncomeInterest => T("Interessi"),
|
||||
_ => "",
|
||||
};
|
||||
if (i.Kind == ClimbReport.IncomeOther && i.Value.Cents == 0) continue;
|
||||
// i costi si mostrano in valore assoluto: l'etichetta dice già che sono costi
|
||||
bool cost = i.Kind is ClimbReport.IncomeOperating or ClimbReport.IncomeMaintenance or ClimbReport.IncomeInterest;
|
||||
var value = cost ? new Money(Math.Abs(i.Value.Cents)) : i.Value;
|
||||
_income.AddChild(Line(name, value.ToString()));
|
||||
}
|
||||
_income.AddChild(PanelKit.Separator());
|
||||
_income.AddChild(Line(T("Utile netto"), report.Profit.ToString(), bold: true, color: report.Profit.IsNegative ? Palette.Danger : Palette.AmberLight));
|
||||
}
|
||||
|
||||
private static Control Line(string caption, string value, bool bold = false, Color? color = null)
|
||||
{
|
||||
var row = PanelKit.Row(8);
|
||||
var c = UiTheme.Text(caption, 14, bold ? Palette.Text : Palette.TextSecondary, bold);
|
||||
c.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
var v = UiTheme.Text(value, 14, color ?? Palette.Text, bold);
|
||||
v.HorizontalAlignment = HorizontalAlignment.Right;
|
||||
row.AddChild(c);
|
||||
row.AddChild(v);
|
||||
return row;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ prestiti (comandi al server)
|
||||
|
||||
/// <summary>Prestito da rimborsare per primo: quello con il tasso più alto (scelta dell'interfaccia).</summary>
|
||||
private LoanInfo? LoanToRepay() => _shown?.LoanList.OrderByDescending(l => l.AnnualRate).ThenBy(l => l.Loan).FirstOrDefault();
|
||||
|
||||
private Money Amount => Money.FromLire((long)_amount.Value);
|
||||
|
||||
private void UpdateLoanButtons()
|
||||
{
|
||||
var report = _shown;
|
||||
var loan = LoanToRepay();
|
||||
var repay = loan is null ? Amount : Money.Min(Amount, loan.Remaining);
|
||||
_repay.Text = $"{T("Rimborsa")} {repay}";
|
||||
_repay.Disabled = loan is null;
|
||||
_borrow.Disabled = report is null || !report.LoansAllowed;
|
||||
_borrow.TooltipText = report is null ? "" : report.LoansAllowed
|
||||
? $"{T("Fido disponibile")} {report.LoanAvailable} {T("su")} {report.MaxLoan}, {T("al")} {Fmt.Pct(report.NewLoanRate, 1)}"
|
||||
: T("In amministrazione controllata non si possono chiedere prestiti");
|
||||
}
|
||||
|
||||
private void Borrow() =>
|
||||
_session.Command(new TakeLoanCommand(Amount), r =>
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
Request(Fmt.Today(_session.World));
|
||||
});
|
||||
|
||||
private void Repay()
|
||||
{
|
||||
var loan = LoanToRepay();
|
||||
if (loan is null) return;
|
||||
_session.Command(new RepayLoanCommand(new LoanId(loan.Loan), Money.Min(Amount, loan.Remaining)), r =>
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
Request(Fmt.Today(_session.World));
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Binario dei livelli (immagine 08): rotaie e traversine da una stazione all'altra, ambra fino al
|
||||
/// treno, cerchi pieni per i livelli raggiunti, anello per quello attuale, il treno e la sua etichetta.
|
||||
/// </summary>
|
||||
private sealed partial class TierTrack : Control
|
||||
{
|
||||
private int _count = 5, _tier = 1;
|
||||
private float _progress;
|
||||
private string _label = "";
|
||||
|
||||
public TierTrack()
|
||||
{
|
||||
CustomMinimumSize = new Vector2(0, 112);
|
||||
MouseFilter = MouseFilterEnum.Ignore;
|
||||
}
|
||||
|
||||
public void Set(int count, int tier, float progress, string label)
|
||||
{
|
||||
_count = Math.Max(1, count);
|
||||
_tier = Math.Clamp(tier, 1, _count);
|
||||
_progress = Math.Clamp(progress, 0, 1);
|
||||
_label = label;
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
private float X(int level) => (level - 0.5f) * Size.X / _count;
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
const float y = 78;
|
||||
float x0 = X(1), x1 = X(_count);
|
||||
float trainX = _tier >= _count ? x1 : X(_tier) + (X(_tier + 1) - X(_tier)) * _progress;
|
||||
var dim = Palette.Rails.Lerp(Palette.Border, 0.4f);
|
||||
// traversine, poi le due rotaie
|
||||
for (float x = x0; x <= x1; x += 12)
|
||||
DrawLine(new Vector2(x, y - 9), new Vector2(x, y + 9), x <= trainX ? Palette.WithAlpha(Palette.Amber, 0.45f) : Palette.Border, 3);
|
||||
foreach (float dy in new[] { -5f, 5f })
|
||||
{
|
||||
DrawLine(new Vector2(x0, y + dy), new Vector2(trainX, y + dy), Palette.Amber, 3);
|
||||
if (trainX < x1) DrawLine(new Vector2(trainX, y + dy), new Vector2(x1, y + dy), dim, 3);
|
||||
}
|
||||
for (int level = 1; level <= _count; level++)
|
||||
{
|
||||
var c = new Vector2(X(level), y);
|
||||
bool reached = level <= _tier;
|
||||
if (level == _tier)
|
||||
{
|
||||
DrawCircle(c, 32, Palette.Panel);
|
||||
DrawArc(c, 31, 0, MathF.Tau, 48, Palette.Amber, 2.5f, true);
|
||||
}
|
||||
DrawCircle(c, 21, reached ? Palette.Amber : Palette.Panel);
|
||||
DrawArc(c, 21, 0, MathF.Tau, 40, reached ? Palette.AppBackground : Palette.Border.Lerp(Palette.TextSecondary, 0.35f), 3, true);
|
||||
}
|
||||
if (_label.Length > 0 && _tier < _count) DrawTrain(new Vector2(trainX, y - 16));
|
||||
}
|
||||
|
||||
/// <summary>Locomotiva stilizzata con l'etichetta dell'avanzamento sopra.</summary>
|
||||
private void DrawTrain(Vector2 at)
|
||||
{
|
||||
var body = Palette.AmberLight;
|
||||
DrawRect(new Rect2(at.X - 30, at.Y - 22, 46, 20), body);
|
||||
DrawRect(new Rect2(at.X + 10, at.Y - 34, 20, 32), body);
|
||||
DrawRect(new Rect2(at.X - 24, at.Y - 32, 8, 10), body);
|
||||
foreach (float dx in new[] { -18f, -2f, 14f })
|
||||
{
|
||||
DrawCircle(new Vector2(at.X + dx, at.Y + 4), 6, Palette.AppBackground);
|
||||
DrawArc(new Vector2(at.X + dx, at.Y + 4), 6, 0, MathF.Tau, 16, body, 2.5f, true);
|
||||
}
|
||||
var font = UiTheme.BodyBold;
|
||||
var dims = font.GetStringSize(_label, HorizontalAlignment.Left, -1, 15);
|
||||
float x = Math.Clamp(at.X - dims.X / 2, 4, Size.X - dims.X - 4);
|
||||
DrawString(font, new Vector2(x, at.Y - 44), _label, HorizontalAlignment.Left, -1, 15, Palette.AmberLight);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,12 @@ public static class Fmt
|
||||
/// <summary>Quota (0–1) in percentuale («12,4%»).</summary>
|
||||
public static string Pct(double fraction, int decimals = 1) => Number(fraction * 100, decimals) + "%";
|
||||
|
||||
/// <summary>
|
||||
/// Avanzamento (0–1) in percentuale intera per difetto («99%»): il 100 % compare solo quando la
|
||||
/// frazione è piena, cioè con il requisito o il livello davvero raggiunto (ADR 0018).
|
||||
/// </summary>
|
||||
public static string Progress(double fraction) => Number(Math.Floor(Math.Clamp(fraction, 0, 1) * 100 + 1e-9), 0) + "%";
|
||||
|
||||
/// <summary>Variazione con il segno («+1,2%», «−0,8%»).</summary>
|
||||
public static string Change(double fraction) => (fraction > 0 ? "+" : "") + Pct(fraction);
|
||||
|
||||
|
||||
@@ -523,7 +523,7 @@ public partial class MarketPanel : VBoxContainer
|
||||
}
|
||||
col.AddChild(Wrapped($"{T("Compra merci all'origine e rivendile dove il prezzo è più alto. Si sblocca al livello")} {tier}.", 13, Palette.Text));
|
||||
col.AddChild(Bar(report.TradingProgress, Palette.Amber));
|
||||
col.AddChild(UiTheme.Text($"{T("Avanzamento verso")} {tier}: {Fmt.Pct(report.TradingProgress, 0)}", 12, Palette.TextSecondary));
|
||||
col.AddChild(UiTheme.Text($"{T("Avanzamento verso")} {tier}: {Fmt.Progress(report.TradingProgress)}", 12, Palette.TextSecondary));
|
||||
// merce già in magazzino (per esempio ereditata da una fusione): si vende e si spedisce anche senza lo sblocco
|
||||
if (report.Warehouses.Any(h => h.Incoming > 0 || h.Goods.Any(g => g.Units > 0)))
|
||||
{
|
||||
|
||||
@@ -21,6 +21,7 @@ public partial class SeriesChart : Control
|
||||
private string _empty = "";
|
||||
private IReadOnlyList<double> _forecast = [], _low = [], _high = [];
|
||||
private string _todayLabel = "", _forecastLabel = "";
|
||||
private IReadOnlyList<(int Index, string Label)> _markers = [];
|
||||
|
||||
public SeriesChart(float height = 150)
|
||||
{
|
||||
@@ -38,6 +39,17 @@ public partial class SeriesChart : Control
|
||||
_color = color;
|
||||
_empty = empty;
|
||||
_forecast = _low = _high = [];
|
||||
_markers = [];
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Segni sulla serie a linea (dopo <see cref="Show"/>): un punto con l'etichetta sopra, per
|
||||
/// esempio i livelli raggiunti nello storico del patrimonio (immagine 08).
|
||||
/// </summary>
|
||||
public void SetMarkers(IReadOnlyList<(int Index, string Label)> markers)
|
||||
{
|
||||
_markers = markers;
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
@@ -118,6 +130,19 @@ public partial class SeriesChart : Control
|
||||
DrawColoredPolygon(fill.ToArray(), Palette.WithAlpha(_color, 0.18f));
|
||||
DrawPolyline(points, _color, 2.5f, true);
|
||||
if (f > 0) DrawForecast(area, points[^1], step, Y, font, fontSize);
|
||||
foreach (var (index, label) in _markers)
|
||||
{
|
||||
if (index < 0 || index >= n) continue;
|
||||
var p = points[index];
|
||||
bool atEnd = index == n - 1;
|
||||
DrawCircle(p, 5, Palette.AmberLight);
|
||||
DrawArc(p, 5, 0, MathF.Tau, 16, Palette.AppBackground, 1.5f, true);
|
||||
var dims = font.GetStringSize(label, HorizontalAlignment.Left, -1, 12);
|
||||
// sull'ultimo punto (che ha sopra il suo valore) l'etichetta va a sinistra, alla sua altezza
|
||||
float mx = atEnd ? Math.Max(area.Position.X, p.X - dims.X - 10) : Math.Clamp(p.X - dims.X / 2, area.Position.X, Size.X - dims.X - 4);
|
||||
float my = atEnd ? p.Y + 16 : p.Y - 12 < area.Position.Y + 10 ? p.Y + 20 : p.Y - 12;
|
||||
DrawString(font, new Vector2(mx, my), label, HorizontalAlignment.Left, -1, 12, Palette.AmberLight);
|
||||
}
|
||||
DrawCircle(points[^1], 4, Palette.AmberLight);
|
||||
string last = _format(_values[^1]);
|
||||
var lastDims = font.GetStringSize(last, HorizontalAlignment.Left, -1, 12);
|
||||
|
||||
@@ -43,6 +43,7 @@ public partial class GameScreen : Node
|
||||
private IndustryPanel? _industryPanel;
|
||||
private CompaniesPanel? _companies;
|
||||
private MarketPanel? _market;
|
||||
private ClimbPanel? _climb;
|
||||
// pannelli a tutto schermo (Compagnie e borsa, Mercato globale): coprono mappa e pannello destro, la barra resta
|
||||
private readonly PanelContainer _full = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, Visible = false };
|
||||
private Control? _mapArea;
|
||||
@@ -117,6 +118,12 @@ public partial class GameScreen : Node
|
||||
if (good >= 0) _market?.Select(good);
|
||||
}
|
||||
|
||||
/// <summary>Apre «La tua scalata» a tutto schermo (dal pulsante o dal livello nella barra superiore).</summary>
|
||||
public void OpenClimb()
|
||||
{
|
||||
if (_tool != Tool.Climb) _toolbar.Select(Tool.Climb);
|
||||
}
|
||||
|
||||
/// <summary>Dal Mercato globale: strumento binari con la mappa centrata sull'hub da collegare.</summary>
|
||||
private void PlanLineToHub(int hub)
|
||||
{
|
||||
@@ -218,6 +225,7 @@ public partial class GameScreen : Node
|
||||
_map.Bind(_session);
|
||||
_minimap.Bind(_session.World, _map);
|
||||
_top.Bind(_session);
|
||||
_top.ClimbRequested += OpenClimb;
|
||||
_toolbar.Selected += SelectTool;
|
||||
_map.Clicked += OnMapClicked;
|
||||
_map.Hovered += OnMapHovered;
|
||||
@@ -393,8 +401,9 @@ public partial class GameScreen : Node
|
||||
_industryPanel = null;
|
||||
_companies = null;
|
||||
_market = null;
|
||||
_climb = null;
|
||||
foreach (var c in _full.GetChildren()) c.QueueFree();
|
||||
bool full = tool is Tool.Companies or Tool.Market;
|
||||
bool full = tool is Tool.Companies or Tool.Market or Tool.Climb;
|
||||
_full.Visible = full;
|
||||
if (_mapArea is not null) _mapArea.Visible = !full;
|
||||
if (_side is not null) _side.Visible = !full;
|
||||
@@ -464,6 +473,12 @@ public partial class GameScreen : Node
|
||||
_full.AddChild(_market);
|
||||
panel = NewInfoPanel();
|
||||
break;
|
||||
case Tool.Climb:
|
||||
_climb = new ClimbPanel(_session);
|
||||
_climb.CloseRequested += () => _toolbar.Select(Tool.None);
|
||||
_full.AddChild(_climb);
|
||||
panel = NewInfoPanel();
|
||||
break;
|
||||
case Tool.Finance:
|
||||
panel = new FinancePanel(_session);
|
||||
break;
|
||||
|
||||
@@ -31,6 +31,10 @@
|
||||
"maxItems": 10,
|
||||
"uniqueItems": true
|
||||
},
|
||||
"ratingProgressSteps": {
|
||||
"type": "number",
|
||||
"exclusiveMinimum": 0
|
||||
},
|
||||
"tiers": {
|
||||
"type": "array",
|
||||
"items": {
|
||||
@@ -152,6 +156,7 @@
|
||||
"required": [
|
||||
"version",
|
||||
"ratingScale",
|
||||
"ratingProgressSteps",
|
||||
"tiers"
|
||||
],
|
||||
"additionalProperties": false
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
"$schema": "schema/tiers.schema.json",
|
||||
"version": 1,
|
||||
"ratingScale": [ "AAA", "AA", "A", "BBB", "BB", "B", "CCC", "CC", "C", "D" ],
|
||||
"ratingProgressSteps": 2.5,
|
||||
"tiers": [
|
||||
{ "level": 1, "name_it": "Compagnia locale", "name_en": "Local company",
|
||||
"requirements": { "netWorth": 0, "connectedTownsOver": { "count": 0, "population": 0 }, "creditRating": "D" },
|
||||
|
||||
@@ -60,7 +60,7 @@ Sistemi implementati (F1–F5), nella loro posizione:
|
||||
| `IndustryMaintenanceSystem` | giorno/mese | condizione degli impianti (usura con l'utilizzo, recupero del budget), consumo di ricambi, fermi e incidenti, revisioni e ammodernamenti in attesa di macchinari, scelte dei proprietari privati, conguaglio con il proprietario (ADR 0011) |
|
||||
| `TownSystem` | giorno/mese/anno | consumo e soddisfazione, crescita, migrazione, espansione dell'abitato |
|
||||
| `MarketSystem` | giorno | prezzi globali con componente mondiale e shock, domanda insoddisfatta |
|
||||
| `FinanceSystem` | giorno/mese/anno | costi di esercizio di veicoli, stazioni e depositi, valori di libro, cassa negativa e bancarotta, rate dei prestiti, rating, livelli (`Tiers`), utile mensile nell'anello dei 12 mesi, chiusura dei conti |
|
||||
| `FinanceSystem` | giorno/mese/anno | costi di esercizio di veicoli, stazioni e depositi, valori di libro per voce (`BookValues`, ADR 0018), cassa negativa e bancarotta, rate dei prestiti, rating, livelli (`Tiers`), utile mensile nell'anello dei 12 mesi, chiusura dei conti |
|
||||
| `StockMarketSystem` | giorno/mese/anno | prezzi e sentiment, valore delle partecipazioni, offerte pubbliche (adesioni, esito), controllo e utili delle controllate, amministrazione controllata del giocatore, fallimenti e aste, storico annuale, nuovi concorrenti (ADR 0012) |
|
||||
| `AiSystem` | giorno/mese | agenti delle compagnie IA: progetti, stalli, offerte; una volta al mese (giorno diverso per IA) finanza, treni aggiuntivi, borsa, industrie, linee dei ricambi e nuovi progetti, tutto con i comandi (ADR 0013) |
|
||||
| `EventSystem` | giorno | eventi del mondo (F6, ADR 0017): chiude quelli scaduti, estrae i nuovi dal catalogo `events.json` con il flusso «events» e la frequenza della difficoltà, notizie d'inizio e di fine (posto di «Events») |
|
||||
@@ -92,7 +92,7 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
|
||||
## 6. Economia e contabilità
|
||||
|
||||
- Entità in `RailEnterprise.Core.Economy`: `Town`, `Industry`, `Hub`, `ResourceSite`, `Company` (con `Loan`), `CommuteContract`, `Market`, `Tariffs`; `MarketOutlook` (F6, ADR 0015) è l'analisi in sola lettura per il pannello «Mercato globale»: storico mensile, previsione dalla componente mondiale, destinazioni di vendita, hub, evento in corso, avanzamento verso il commercio.
|
||||
- Entità in `RailEnterprise.Core.Economy`: `Town`, `Industry`, `Hub`, `ResourceSite`, `Company` (con `Loan`), `CommuteContract`, `Market`, `Tariffs`; `MarketOutlook` (F6, ADR 0015) è l'analisi in sola lettura per il pannello «Mercato globale»: storico mensile, previsione dalla componente mondiale, destinazioni di vendita, hub, evento in corso, avanzamento verso il commercio. `ClimbOutlook` (F6, ADR 0018) è l'analisi in sola lettura per «La tua scalata»: livelli con gli sblocchi dai dati (`Tiers.NewUnlocks`), requisiti del prossimo livello con l'avanzamento (media delle tre frazioni, usata anche dal Mercato globale), stato patrimoniale per voce che somma al patrimonio netto del motore, conto economico, prestiti, storico del patrimonio dalla Cronaca.
|
||||
- Ogni movimento di denaro passa dal registro (`MoneyLedger.Transfer`) tra conti: compagnie, industrie e il conto `Esterno` (famiglie, clienti delle tariffe, mercato mondiale). La somma di tutti i saldi è sempre zero: è l'invariante «denaro» dei test. Le voci del conto economico delle compagnie (`LedgerEntry`) si accumulano per mese e per anno.
|
||||
- Ogni unità di merce sta in un magazzino tracciato (industrie, città, magazzini delle compagnie nelle stazioni, pacchetti in stazione e a bordo dei treni) e `GoodsCounters` registra prodotto, consumato, deperito, importato, esportato: giacenza = prodotto + importato − consumato − deperito − esportato. È l'invariante «merci».
|
||||
- Compravendita in proprio (F6, ADR 0016): `TradingCommandHandlers` esegue `BuyGoods`, `SellGoods` e `ShipGoods` con il prezzo locale marginale di `Systems/TradingMath` (unità per unità, controparti ordinate per prezzo). La merce comprata sta in `Station.Stock`; quella spedita viaggia in pacchetti con `Packet.Owned`, senza tariffa né consumatore, ed entra nel magazzino della stazione d'arrivo. Gli scambi con le industrie passano dal registro sulla voce «Commercio», quelli con gli hub contano come importazione ed esportazione; `StationSystem` addebita ogni mese la giacenza dei magazzini.
|
||||
@@ -108,6 +108,7 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
- Corpo versione 3 (F5): `CorporateSerializer` aggiunge manutenzione e proprietà delle industrie, libro dei soci, prezzi, controllo e storico delle compagnie, offerte, aste, fine partita e stato degli agenti IA (progetti, candidati scartati); i salvataggi precedenti si migrano (ADR 0012).
|
||||
- Corpo versione 4 (F6): `TradingSerializer` aggiunge i magazzini delle compagnie nelle stazioni (beni per id testuale) e gli id dei pacchetti di merce propria in stazione e a bordo; i salvataggi precedenti si caricano con i magazzini vuoti. `WorldSerializer.Write(w, s, versione)` scrive un corpo di una versione precedente per i test di migrazione (ADR 0016).
|
||||
- Corpo versione 5 (F6): `EventSerializer` aggiunge il prossimo id e gli eventi del mondo attivi (tipo e bene per id testuale, bersaglio, giorni, intensità; la zona si ricalcola dal catalogo); le impostazioni salvano `eventFrequencyMultiplier`. I salvataggi precedenti si caricano senza eventi e con la frequenza del preset (ADR 0017).
|
||||
- Corpo versione 6 (F6): `BalanceSheetSerializer` aggiunge per ogni compagnia il valore contabile per voce (`AssetCategory`) e il giorno in cui ha raggiunto ogni livello. I salvataggi precedenti ripartiscono il totale salvato in proporzione alle voci calcolate al caricamento (stesso patrimonio netto) e ricostruiscono i giorni dai fatti salienti o dallo storico (ADR 0018).
|
||||
|
||||
## 8. Server
|
||||
|
||||
@@ -125,7 +126,7 @@ Requisito: stesso seme + stessi comandi agli stessi tick ⇒ stesso hash di stat
|
||||
- `Main` → `MenuScreen` / `ConnectScreen` / `GameScreen`. `LocalServerLauncher` avvia il server come processo figlio per la partita locale.
|
||||
- `GameSession` applica i messaggi a `ClientWorld` (Protocol) sul thread principale; i comandi sono l'unico modo di cambiare il mondo; le anteprime del tracciato usano `TrackPreview` di Core.
|
||||
- `MapView` (Node2D + Camera2D): `TerrainLayer` (texture per chunk con fasce, ombreggiatura, sponde e curve di livello; shader per le rive), `EntityLayer` (case, industrie, stazioni, depositi, alberi in MultiMesh), `TrackLayer` (massicciata, traversine, rotaie, opere, cantieri, segnali), `TrainLayer` (veicoli interpolati, fumo, avvisi), `ToolOverlay`; `LabelLayer` disegna le etichette in coordinate schermo.
|
||||
- HUD: `TopBar`, `Toolbar`, pannello destro (pannelli degli strumenti e schede) con `Minimap`, `Ticker`. Pannelli: binari con profilo, stazione, deposito, treni, linee, officine (politica della flotta, avvisi, flotta per condizione, cartella di manutenzione, Registro officina, scorta di ricambi, mappa di calore), impieghi (Registro degli impieghi e convenzioni), mercato, finanze, scheda dell'entità (con manutenzione del treno, lavoratori dell'industria, dove lavorano gli abitanti, avvisi degli eventi in corso). Sopra la minimappa il riquadro «Eventi in corso» (`WorldEventsBox`, testi in `WorldEventText`) elenca gli eventi del mondo del `DailyDigest`; il Mercato globale mostra quelli sulla domanda di un bene.
|
||||
- HUD: `TopBar`, `Toolbar`, pannello destro (pannelli degli strumenti e schede) con `Minimap`, `Ticker`. Pannelli: binari con profilo, stazione, deposito, treni, linee, officine (politica della flotta, avvisi, flotta per condizione, cartella di manutenzione, Registro officina, scorta di ricambi, mappa di calore), impieghi (Registro degli impieghi e convenzioni), mercato, finanze; a tutto schermo «Compagnie e borsa», «Mercato globale» (`MarketPanel`, immagine 06) e «La tua scalata» (`ClimbPanel`, immagine 08: binario dei livelli, storico del patrimonio con `SeriesChart` e i livelli segnati, requisiti, stato patrimoniale, conto economico, prestiti), che si apre anche dal livello nella `TopBar`; scheda dell'entità (con manutenzione del treno, lavoratori dell'industria, dove lavorano gli abitanti, avvisi degli eventi in corso). Sopra la minimappa il riquadro «Eventi in corso» (`WorldEventsBox`, testi in `WorldEventText`) elenca gli eventi del mondo del `DailyDigest`; il Mercato globale mostra quelli sulla domanda di un bene.
|
||||
- Collaudo: pilota automatico (`-- --autopilot cartella`, `scripts/client-autopilot.sh`) con schermate.
|
||||
|
||||
## 10. Prestazioni
|
||||
|
||||
+5
-2
@@ -77,7 +77,7 @@ costMultiplier: f64 }`
|
||||
| 7 | Save | `name: string` |
|
||||
| 8 | Load | `saveId: string` |
|
||||
| 9 | NewGame | `seed: u64`, `sizeKm: i32`, `startYear: i32` (0 = predefinito), `difficultyPreset: string`, `overrides: [(key: string, value: f64)]`, `endlessFlags: u32` |
|
||||
| 10 | RequestDetail | `kind: u8` (1 cartella di manutenzione di un treno, 2 registro officina di un deposito, 3 registro degli impieghi; dalla F5: 4 scheda di una compagnia, 5 scheda di un'industria, 6 Cronaca; dalla F6: 7 quadro del mercato globale), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; ignorato per 3, 6 e 7). Aggiunto in F4 |
|
||||
| 10 | RequestDetail | `kind: u8` (1 cartella di manutenzione di un treno, 2 registro officina di un deposito, 3 registro degli impieghi; dalla F5: 4 scheda di una compagnia, 5 scheda di un'industria, 6 Cronaca; dalla F6: 7 quadro del mercato globale, 8 quadro della scalata), `target: i32` (id del treno, del deposito, della compagnia o dell'industria; ignorato per 3, 6, 7 e 8). Aggiunto in F4 |
|
||||
|
||||
### Comandi (`Command.type`, payload in ordine)
|
||||
|
||||
@@ -160,6 +160,7 @@ loro fase i comandi 35–38 rispondono `NotImplemented`. Il server imposta l'emi
|
||||
| 131 | Notification | `EventInfo` |
|
||||
| 132 | Newspaper | `day: i64`, `title: string`, `articles: [(headline: string, body: string)]` |
|
||||
| 133 | SaveList | `saves: [SaveInfo]` |
|
||||
| 134 | ClimbReport | `day: i64, company: i32, foundedDay: i64, initialCapital: Money, tier: u8, nextTier: u8 (0 all'ultimo livello), tiers: [TierInfo]`; requisiti del prossimo livello: `netWorth, netWorthRequired: Money, netWorthFraction: f32, netWorthMet: bool, towns, townsRequired, townPopulation: i32, townsFraction: f32, townsMet: bool, rating, ratingRequired: string, ratingFraction: f32, ratingMet: bool, progress: f32` (media delle tre frazioni); stato patrimoniale: `assets: [AmountInfo]` (kind 0 binari e opere, 1 stazioni e depositi, 2 veicoli, 3 industrie possedute, 4 merce propria), `portfolio, cash (positiva), totalAssets, loans: Money, loansRate: f32 (medio), overdraft (scoperto), totalLiabilities, balanceNetWorth: Money` (= totalAssets − totalLiabilities = patrimonio netto del motore); conto economico: `incomeYear: i32, incomePartial: bool, income: [AmountInfo]` (kind 0 tariffe e noli, 1 altri ricavi, 2 costi operativi, 3 manutenzione, 4 interessi; con segno), `profit: Money`; prestiti: `loanList: [LoanInfo], maxLoan, loanAvailable: Money, newLoanRate: f32, loansAllowed: bool`; `history: [NetWorthPointInfo]` (fondazione, fine di ogni anno, oggi) (su richiesta, F6; ADR 0018) |
|
||||
|
||||
Record (ognuno chiude con `flags`):
|
||||
|
||||
@@ -196,6 +197,8 @@ Record (ognuno chiude con `flags`):
|
||||
- `IndustryStopInfo { day: i64, days, kind: u8 }`, `RecordInfo { title, value: string, year }`
|
||||
- `SaveInfo { saveId, name, gameDate, sizeBytes: i64, savedUnixMs: i64, autosave }`
|
||||
- `GoodMarketInfo { good, available, price: f64 (centesimi), change: f32 (30 giorni), supplyMonth, demandMonth, worldSupplyMonth, worldDemandMonth, stockUnits: f64, stockMonths: f32 (−1 senza domanda), history: [PricePointInfo { day: i64, price: f64 }] (un campione per mese, l'ultimo è oggi), forecast: [ForecastInfo { months: u8, price, low, high: f64 }], sellPlaces: [SellPlaceInfo { kind: u8 (0 industria, 1 hub), target, price: f64, line: i32 (−1 non collegato) }] }`
|
||||
- `TierInfo { level: u8, nameIt, nameEn: string, netWorthRequired: Money, townsRequired, townPopulation: i32, ratingRequired: string, reached: bool, reachedDay: i64 (fondazione per il livello 1; −1 se non raggiunto o sconosciuto), unlocks: [UnlockInfo] }`; `UnlockInfo { kind: u8 (0 fido, 1 squadre di cantiere, 2 compravendita in proprio, 3 acquisto di industrie, 4 quotazione, 5 scalate ostili, 6 concessioni), value: i64 (fido in centesimi o numero di squadre; 0 per gli altri) }`: gli sblocchi che il livello aggiunge al precedente
|
||||
- `AmountInfo { kind: u8, value: Money }`, `LoanInfo { loan, remaining: Money, annualRate: f32, monthsLeft: i32 }`, `NetWorthPointInfo { day: i64, value: Money }`
|
||||
- `HubMarketInfo { hub, kind: u8 (0 porto, 1 valico), monthlyCapacity, duty: f32, usedThisMonth, line: i32 (−1 non collegato) }`
|
||||
- `WarehouseInfo { station, capacity, incoming: i32 (merce propria in viaggio verso la stazione), goods: [WarehouseGoodInfo] }` (stazioni vive della compagnia)
|
||||
- `WarehouseGoodInfo { good, units: i32 (in magazzino), buyPrice: f64 (centesimi, prossima unità; −1 nessun venditore), buyUnits: i32, sellPrice: f64 (−1 nessun compratore), sellUnits: i32 }` (beni in magazzino o scambiabili nel bacino)
|
||||
@@ -219,7 +222,7 @@ Record (ognuno chiude con `flags`):
|
||||
`CompanyCard` (qualunque compagnia), `IndustryCard` (qualunque industria aperta) e `Chronicle`; la
|
||||
Cronaca arriva da sola, una volta per sessione, quando la partita del giocatore finisce. Dalla F6
|
||||
`MarketReport` (quadro del mercato globale per la compagnia della sessione), che il pannello chiede
|
||||
all'apertura e a ogni nuovo giorno; il server non lo manda da solo.
|
||||
all'apertura e a ogni nuovo giorno; il server non lo manda da solo. Così anche `ClimbReport` (quadro della scalata), che il pannello chiede all'apertura, a ogni nuovo giorno e dopo un prestito, e la barra superiore una volta al mese.
|
||||
- Backpressure: i moti si scartano oltre 256 KB in coda; oltre 64 MB di messaggi affidabili la
|
||||
sessione si chiude (il client può riprenderla).
|
||||
- Obiettivo di banda in regime: < 100 KB/s per client.
|
||||
+12
-3
@@ -121,21 +121,30 @@ Aggiornato alla fine di ogni fase (guida, sezione 18).
|
||||
- le IA non reagiscono agli eventi: ne subiscono gli effetti attraverso i sistemi, ma stimano i candidati sui valori senza eventi (domanda delle città, posti scoperti, efficienza delle industrie di trasformazione; ADR 0017 §9);
|
||||
- correzioni della revisione: un evento è in vigore nei giorni [inizio, fine) per tutti (sistemi giornalieri, treni a ogni tick, usura del traffico del giorno prima) ed esce dall'elenco il mattino del primo giorno libero con la notizia di fine; nessuna sovrapposizione di zone tra due maltempi o tra due eventi sulla domanda dello stesso bene; `{until}` è l'ultimo giorno; client: conto alla rovescia dalla durata a 1 e «da domani» per gli eventi estratti oggi, avviso anche nelle città della zona e nel Registro officina del deposito, notiziario senza doppioni (dal resoconto solo le notizie di fine, le altre arrivano come `Notification`);
|
||||
- test (`Simulation/EventTests.cs`, 19): catalogo e validazione, effetti di ogni tipo e loro fine, solo la zona per domanda e maltempo, treni rallentati, officina senza personale, durata, niente doppioni né zone sovrapposte, giorni del maltempo per treni, usura e resoconto con il conto alla rovescia, presenti senza eventi per l'IA, frequenza 0, stesso seme stessi eventi, salvataggio con eventi attivi, migrazione dalla versione 4, un anno di eventi frequenti con gli invarianti (lento), eventi nel `DailyDigest` e nel `MarketReport`. 162 test (144 senza i lenti).
|
||||
- Restano della F6: finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot.
|
||||
- **Livelli e sblocchi visibili, «La tua scalata» (issue #38, ADR 0018)**:
|
||||
- `ClimbOutlook` (Core, sola lettura): livelli con gli sblocchi letti dai dati (`Tiers.NewUnlocks`: fido, squadre di cantiere, compravendita, acquisto di industrie, quotazione, scalate, concessioni), quando sono stati raggiunti, requisiti del prossimo livello con valore, soglia, frazione e avanzamento complessivo (media delle tre frazioni, ora anche nel Mercato globale al posto del minimo dell'ADR 0015), stato patrimoniale, conto economico dell'ultimo anno chiuso, prestiti, storico del patrimonio netto dalla Cronaca;
|
||||
- stato patrimoniale per voce con una sola fonte: `FinanceSystem.BookValues` (binari e opere, stazioni e depositi, veicoli, industrie possedute, merce propria) scritto ogni mese in `Company.BookValues`; `AssetBookValue` ne è la somma e la scomposizione (con partecipazioni, cassa, prestiti e scoperto) somma al centesimo al patrimonio netto del motore; le industrie possedute entrano nel patrimonio al valore degli impianti più la loro cassa (prezzo d'acquisto senza avviamento);
|
||||
- notizia di promozione con gli sblocchi ottenuti e giorno annotato (`Company.TierReachedDay`); rifiuti con il livello che serve e il suo nome dai dati (compravendita, acquisto di industrie, quotazione, scalate ostili, concessioni, fido insufficiente con il livello che alza il fido); il validatore pretende squadre per livello uguali in `tiers.json` e `construction.json`;
|
||||
- salvataggio: corpo versione 6 (`BalanceSheetSerializer`) con voci e giorni dei livelli nell'hash; le versioni 1–5 ripartiscono il totale salvato (stesso patrimonio netto) e ricostruiscono i giorni dai fatti salienti o dallo storico;
|
||||
- protocollo: `DetailKind.Climb` (8) e `ClimbReport` (134); server: quadro su richiesta; `ClientWorld.Climb`;
|
||||
- client: pannello «La tua scalata» a tutto schermo come l'immagine 08 (`ClimbPanel`: binario dei livelli con il treno e l'avanzamento, sblocchi sotto ogni livello, storico del patrimonio con i livelli segnati in `SeriesChart`, «Per diventare…» con tre barre, stato patrimoniale, conto economico, «Chiedi un prestito» e «Rimborsa»), pulsante «Scalata» nella barra degli strumenti, livello e avanzamento nella barra superiore (un clic apre il pannello), testi in `strings.csv`, schermata `17_scalata` nel pilota automatico;
|
||||
- test (`Economy/ClimbTests.cs`, 7, più il quadro via WebSocket in `ServerTests`): requisiti coerenti con `Tiers.Meets` e avanzamento, sblocchi dai dati, stato patrimoniale con industria, merce, prestito e scoperto che somma al patrimonio netto, notizia di promozione con gli sblocchi, rifiuti con il livello, salvataggio versione 6 e migrazione dalla 5, proiezione e round-trip di `ClimbReport`. 170 test (152 senza i lenti).
|
||||
- Restano della F6: finanza completa, ere e obsolescenza, pannello 07, tooltip «perché», tutorial, audio, bilanciamento con i bot.
|
||||
|
||||
## Prossimo passo
|
||||
|
||||
- F6: finanza completa, livelli e sblocchi nell'interfaccia, ere e obsolescenza, pannelli 07–08, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`.
|
||||
- F6: finanza completa, ere e obsolescenza, pannello 07, tooltip «perché», tutorial, audio, bilanciamento con i bot su `simulate`.
|
||||
|
||||
## Limiti noti
|
||||
|
||||
- Godot non è eseguibile nell'ambiente cloud: il client potrà essere compilato con `Godot.NET.Sdk` ma non avviato né esportato qui.
|
||||
- Senza vettori il mondo è in lento declino: le città perdono circa l'1 % di abitanti l'anno e le industrie lavorano a circa il 15–30 % (voluto, ADR 0004).
|
||||
- Il client non è stato provato su Windows né esportato (servono i template di esportazione di Godot); la partita locale usa il server compilato dal repository o `RE_SERVER_PATH`.
|
||||
- Nella vista d'insieme i fiumi larghi una cella mostrano ancora gradini. Le immagini di riferimento 06–09 sono arrivate (novembre 2026): il Mercato globale è allineato alla 06 (F6, non ancora provato in Godot: qui manca l'editor); Industria, Scalata e la schermata di connessione vanno allineati in F6.
|
||||
- Nella vista d'insieme i fiumi larghi una cella mostrano ancora gradini. Le immagini di riferimento 06–09 sono arrivate (novembre 2026): il Mercato globale è allineato alla 06 e «La tua scalata» alla 08 (F6, non ancora provati in Godot: qui manca l'editor); Industria e la schermata di connessione vanno allineati in F6.
|
||||
- Compravendita in proprio (ADR 0016): la quotazione nel pannello non considera la cassa delle industrie compratrici; una spedizione tiene occupato lo spazio di destinazione per tutto il viaggio; se una linea sparisce durante il viaggio la merce si ferma nel magazzino della stazione dove si trova anche oltre la capacità; un treno che lascia la linea in viaggio lascia la merce propria alla prossima fermata senza percorrere il tratto; la merce in attesa in stazione scade come le altre merci (la scadenza riparte a ogni trasbordo); il riquadro non è ancora stato provato in Godot (qui manca l'editor).
|
||||
- Eventi del mondo (ADR 0017): le medie mobili (coperture a 30 giorni, margini) si riprendono gradualmente dopo un evento; il maltempo prende un arco per intero secondo il suo punto medio; la notizia di fine arriva la sera dell'ultimo giorno; il riquadro mostra al massimo quattro eventi; le IA non reagiscono; client non ancora provato in Godot (qui manca l'editor).
|
||||
- Mercato globale (ADR 0015): la previsione segue solo la componente mondiale (ciclo e shock), non domanda e offerta della mappa; «Dove conviene vendere» dà il prezzo alla destinazione, senza il costo del trasporto.
|
||||
- Scalata (ADR 0018): il livello non scende; lo storico del patrimonio ha un punto all'anno (più la fondazione e oggi); il capitale iniziale mostrato è quello della difficoltà; il valore contabile si aggiorna a inizio mese, mentre cassa, partecipazioni e debiti sono del giorno; i salvataggi delle versioni 1–5 ripartiscono il totale degli attivi in proporzione alle voci del giorno di caricamento fino al ricalcolo del mese; il pannello non è ancora stato provato in Godot (qui manca l'editor).
|
||||
- In F3 tutte le sessioni guidano la compagnia del giocatore (ADR 0009).
|
||||
- Il bilanciamento economico è provvisorio (F6): nello scenario l'acciaieria cresce di livello ogni due trimestri finché la linea operai non satura; il prezzo del minerale sale oltre 1,5 volte il base e il margine dei trasformatori diventa negativo quando la domanda supera l'offerta delle miniere.
|
||||
- La lunghezza dei marciapiedi non è modellata; i segnali sono solo a blocco fisso (niente segnali di percorso).
|
||||
|
||||
@@ -69,7 +69,8 @@ né come migrare i salvataggi con lo storico di un anno.
|
||||
(oggi il 2, «Compagnia regionale»). Se la compagnia ce l'ha è «sbloccata»; altrimenti l'avanzamento
|
||||
è il minimo tra le frazioni dei requisiti numerici (patrimonio netto / richiesto, città collegate /
|
||||
richieste, entrambe limitate a 1); il rating è soddisfatto o no e si mostra a parte, perché non ha
|
||||
una frazione sensata.
|
||||
una frazione sensata. *Sostituito dall'ADR 0018 §2: l'avanzamento è la media delle tre frazioni
|
||||
(patrimonio, città, rating), la stessa del pannello «La tua scalata».*
|
||||
|
||||
## Conseguenze
|
||||
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
# ADR 0018 — Scalata: livelli e sblocchi visibili, stato patrimoniale per voce (F6)
|
||||
|
||||
Stato: accettato (F6, issue #38).
|
||||
|
||||
## Contesto
|
||||
|
||||
Il motore ha i livelli dalla F5 (ADR 0011 §6: `tiers.json`, `Tiers`, promozione mensile dopo il rating,
|
||||
nessuna retrocessione), ma il giocatore li vedeva solo come distintivo nella barra e come rifiuti dei comandi
|
||||
con il nome del livello scritto a mano. La F6 chiede il pannello «La tua scalata» dell'immagine di
|
||||
riferimento 08: binario dei livelli con il treno che avanza, sblocchi di ogni livello, storico del
|
||||
patrimonio netto con i livelli raggiunti, requisiti del prossimo livello, stato patrimoniale, conto
|
||||
economico e prestiti. La guida non dice come scomporre il patrimonio netto, come misurare l'avanzamento,
|
||||
né come valutare le industrie possedute, che finora non entravano nel patrimonio.
|
||||
|
||||
## Decisione
|
||||
|
||||
1. **Quadro come pura funzione del mondo.** `ClimbOutlook` (Core, `Economy/ClimbOutlook.cs`) legge il
|
||||
mondo e non scrive nulla, come `MarketOutlook` (ADR 0015). Il server lo proietta in `ClimbReport` (134)
|
||||
su richiesta (`RequestDetail` con `DetailKind.Climb` = 8); il client lo mostra com'è. Il pannello lo
|
||||
chiede all'apertura, a ogni nuovo giorno e dopo un comando di prestito; la barra superiore una volta
|
||||
al mese di gioco, per l'avanzamento accanto al livello.
|
||||
2. **Requisiti e avanzamento.** Per il prossimo livello: patrimonio netto, città collegate sopra la
|
||||
popolazione (lo stesso `Tiers.ConnectedTowns`) e rating, con valore attuale, soglia, soddisfatto o no
|
||||
(gli stessi confronti di `Tiers.Meets`) e frazione: patrimonio/soglia e città/città richieste limitate
|
||||
a 1; per il rating 1 − gradini mancanti / `ratingProgressSteps` di `tiers.json` (2,5), limitata tra 0
|
||||
e 1 (1 se soddisfatto: un gradino sotto vale il 60 %, tre o più lo 0 %). **L'avanzamento complessivo è
|
||||
la media delle tre frazioni**: con lo stato dell'immagine 08 (65 % di patrimonio, 1 città su 2, BBB
|
||||
verso A) le frazioni sono 0,65, 0,5 e 0,6 e l'avanzamento il 58 %, come nell'immagine. Misurare il
|
||||
rating dalla D (prima scelta) dava l'86 % per un solo gradino mancante e il 67 % complessivo, e gonfiava
|
||||
l'avanzamento fin dall'inizio. L'avanzamento vale 1 solo con tutti e tre i requisiti soddisfatti
|
||||
(altrimenti al massimo 0,999), e il client mostra queste percentuali per difetto, quindi il 100 %
|
||||
compare solo a requisito o livello raggiunto. Il quadro del Mercato globale usa la stessa funzione:
|
||||
l'ADR 0015 §12 (minimo dei requisiti numerici) è sostituito, così i due pannelli mostrano lo stesso numero.
|
||||
3. **Sblocchi dai dati.** `Tiers.NewUnlocks` elenca ciò che un livello aggiunge al precedente, nell'ordine
|
||||
di `UnlockKind`: fido massimo (fido iniziale × `maxLoanFactor`, se cresce), squadre di cantiere (se
|
||||
crescono), compravendita in proprio, acquisto di industrie, quotazione, scalate ostili, concessioni (le
|
||||
funzioni che passano da `false` a `true`); il livello 1 elenca la dotazione di partenza (fido e squadre).
|
||||
Le concessioni non si annunciano finché il comando non esiste (F7, `Tiers.ConcessionsAvailable`): il
|
||||
gioco non promette uno sblocco che non funziona. Il validatore pretende che gli sblocchi non diminuiscano
|
||||
salendo di livello (`maxLoanFactor` non decrescente, le funzioni non tornano `false`), come presumono
|
||||
notizie, rifiuti e pannello (ADR 0011: gli sblocchi restano acquisiti).
|
||||
Le squadre per livello stanno in due file (`construction.json`, usato dal cantiere, e `tiers.json`): il
|
||||
validatore ora pretende che coincidano. Nessun testo di regola è scritto a mano: il Core ha solo le
|
||||
etichette italiane degli sblocchi, il client le sue chiavi di traduzione.
|
||||
4. **Notizia di promozione.** Il passaggio di livello esisteva già; il testo ora elenca gli sblocchi
|
||||
ottenuti: «X diventa «Compagnia regionale» (livello 2): sblocca fido fino a …, 4 squadre di
|
||||
cantiere, compravendita in proprio» (il fido è quello della compagnia). Il livello non scende (ADR 0011): nessuna notizia di retrocessione.
|
||||
5. **Rifiuti con il livello.** I comandi bloccati dal livello dicono quale livello serve e come si chiama,
|
||||
dai dati (`Tiers.LockedText`): compravendita in proprio, acquisto di industrie, quotazione, scalate
|
||||
ostili e concessioni (che fino alla F7 sono «non ancora disponibili»: prima del livello il rifiuto è per
|
||||
il livello e dice che si sbloccheranno lì, dopo resta «non ancora disponibili»). Il fido insufficiente dice quanto resta su quanto e quale livello alza il
|
||||
fido e a quanto.
|
||||
6. **Stato patrimoniale per voce, una sola fonte.** `FinanceSystem.BookValues` calcola il valore contabile
|
||||
per compagnia e per voce (`AssetCategory`: binari e opere, stazioni e depositi, veicoli, industrie
|
||||
possedute, merce propria); `UpdateBookValues` (ogni mese, come prima) le scrive in `Company.BookValues`
|
||||
e `AssetBookValue` ne è la somma. Il patrimonio netto del motore resta cassa + attivi + partecipazioni −
|
||||
debiti; il pannello lo scompone in attivi per voce, partecipazioni, cassa positiva, prestiti (con il
|
||||
tasso medio pesato sul residuo) e scoperto di cassa (la cassa negativa), e la somma coincide al
|
||||
centesimo con `Company.NetWorth`.
|
||||
7. **Industrie possedute nel patrimonio.** Finora comprare un'industria toglieva il prezzo dalla cassa
|
||||
senza aggiungere nulla agli attivi. Ora entrano al valore contabile `IndustryMath.BookValue`: la parte
|
||||
del prezzo d'acquisto (ADR 0011 §5) senza l'avviamento, cioè impianti (`PlantValue`: costo
|
||||
d'ammodernamento × livello × quota, secondo le condizioni) più la cassa dell'impresa. Gli impianti
|
||||
contano al livello attuale: un'industria inattiva (livello 0), che non si può vendere, vale solo la sua
|
||||
cassa (il prezzo d'acquisto conta invece almeno un livello, come prima). Comprare costa
|
||||
quindi al patrimonio solo l'avviamento (il multiplo degli utili), e il rating e il prezzo dell'azione
|
||||
vedono gli impianti. Il prezzo di vendita (`Valuation`) non cambia.
|
||||
8. **Salvataggio versione 6.** Le voci non si possono ricostruire al caricamento (dipendono dal giorno del
|
||||
calcolo mensile e da attivi venduti o demoliti dopo), quindi il corpo versione 6
|
||||
(`BalanceSheetSerializer`, in coda allo stato dinamico e nell'hash) salva per ogni compagnia le voci e il
|
||||
giorno in cui ogni livello è stato raggiunto (`Company.TierReachedDay`, annotato da `Tiers.Evaluate`;
|
||||
il livello 1 vale dalla fondazione). Le versioni 1–5 salvano solo il totale: la migrazione lo ripartisce
|
||||
in proporzione alle voci calcolate al giorno del caricamento (resto dell'arrotondamento sulla voce più
|
||||
grande, tutto sui binari se non c'è nulla da ripartire), quindi il patrimonio netto non cambia fino al
|
||||
ricalcolo del mese; i giorni dei livelli si ricostruiscono dai fatti salienti («diventa «nome»») o, in
|
||||
mancanza, dalla prima fotografia dello storico con quel livello: quella dell'anno Y si scatta il primo
|
||||
giorno di Y+1, dopo la chiusura del mese che può aver promosso la compagnia, quindi si usa quel giorno
|
||||
(tra la fondazione e oggi).
|
||||
9. **Storico del patrimonio.** Nessuno stato nuovo: si riusa lo storico annuale della Cronaca
|
||||
(`Company.History`, fotografia di fine anno al primo giorno dell'anno dopo), preceduto dal capitale
|
||||
iniziale della difficoltà alla fondazione e seguito dal valore di oggi, che prende il posto della
|
||||
fotografia del primo giorno dell'anno in corso: un punto per anno di calendario, etichettato con il suo
|
||||
anno. I livelli raggiunti si segnano sul punto dell'anno della promozione, anche sull'ultimo (oggi).
|
||||
10. **Conto economico.** L'ultimo anno chiuso (o l'anno in corso fino a oggi, per una compagnia fondata
|
||||
quest'anno), con le voci del registro raggruppate in tariffe e noli, altri ricavi (commercio, contratti,
|
||||
industrie, controllate), costi operativi (esercizio, salari, penali), manutenzione (binari e flotta) e
|
||||
interessi: le righe sommano esattamente a `Company.OperatingProfit` («Utile netto» nel pannello).
|
||||
11. **Prestiti dal pannello.** «Chiedi un prestito» e «Rimborsa» mandano i comandi esistenti (`TakeLoan`,
|
||||
`RepayLoan`); il pannello rimborsa per primo il prestito con il tasso più alto (scelta dell'interfaccia:
|
||||
il server limita comunque l'importo al residuo e alla cassa).
|
||||
|
||||
## Conseguenze
|
||||
|
||||
- Le compagnie che possiedono industrie (giocatore dal livello 3, IA dal livello 3) hanno un patrimonio
|
||||
netto più alto di prima: salgono di livello un po' prima e il loro titolo vale di più. Le soglie restano
|
||||
provvisorie fino al bilanciamento della F6.
|
||||
- Il quadro della scalata costa poco (cinque livelli, una scansione di stazioni e treni per le città
|
||||
collegate) e si calcola solo su richiesta.
|
||||
- Il salvataggio cresce di 10 numeri per compagnia; l'hash giornaliero include le voci e i giorni dei
|
||||
livelli.
|
||||
@@ -136,6 +136,22 @@ public static class DataValidator
|
||||
if (!levels.SequenceEqual(Enumerable.Range(1, levels.Count))) Err("tiers.json", "i livelli devono essere 1, 2, 3, 4, 5 in ordine");
|
||||
Increasing("tiers.json", "requirements.netWorth", d.Tiers.Tiers.Select(t => (double)t.Requirements.NetWorth), errors, strictFromSecond: true);
|
||||
if (!d.Tiers.RatingScale.SequenceEqual(Enum.GetValues<CreditRating>())) Err("tiers.json", "ratingScale deve elencare i rating da AAA a D");
|
||||
if (!(d.Tiers.RatingProgressSteps > 0)) Err("tiers.json", "ratingProgressSteps deve essere positivo");
|
||||
// gli sblocchi restano acquisiti salendo (ADR 0011): notizie, rifiuti e pannello lo presumono (ADR 0018)
|
||||
var unlocks = d.Tiers.Tiers.Select(t => t.Unlocks).ToList();
|
||||
for (int i = 1; i < unlocks.Count; i++)
|
||||
{
|
||||
var (prev, cur) = (unlocks[i - 1], unlocks[i]);
|
||||
if (cur.MaxLoanFactor < prev.MaxLoanFactor) Err("tiers.json", $"unlocks.maxLoanFactor non può scendere dal livello {i} al livello {i + 1}");
|
||||
foreach (var (name, had, has) in new[]
|
||||
{
|
||||
("trading", prev.Trading, cur.Trading), ("buyIndustry", prev.BuyIndustry, cur.BuyIndustry), ("ipo", prev.Ipo, cur.Ipo),
|
||||
("hostileTakeover", prev.HostileTakeover, cur.HostileTakeover), ("concessions", prev.Concessions, cur.Concessions),
|
||||
})
|
||||
{
|
||||
if (had && !has) Err("tiers.json", $"unlocks.{name} non può tornare falso dal livello {i} al livello {i + 1}");
|
||||
}
|
||||
}
|
||||
|
||||
// --- difficoltà
|
||||
Unique("difficulty.json", d.Difficulty.Presets.Select(p => p.Id), errors);
|
||||
@@ -191,6 +207,10 @@ public static class DataValidator
|
||||
}
|
||||
RequireKeys("construction.json", "crews.metersPerDay", c.Crews.MetersPerDay.Keys, WorkKeys, errors);
|
||||
if (c.Crews.CrewsByTier.Length != 5) Err("construction.json", "crews.crewsByTier deve avere 5 valori");
|
||||
// le squadre per livello stanno in due file: il cantiere usa construction.json, il pannello della scalata
|
||||
// le mostra tra gli sblocchi; devono coincidere (ADR 0018)
|
||||
else if (!d.Tiers.Tiers.Select(t => t.Unlocks.Crews).SequenceEqual(c.Crews.CrewsByTier))
|
||||
Err("tiers.json", "unlocks.crews deve coincidere con crews.crewsByTier di construction.json");
|
||||
RequireKeys("construction.json", "costs.depotBySize", c.Costs.DepotBySize.Keys, SizeKeys, errors);
|
||||
foreach (string k in c.Costs.TerrainModifiers.Keys)
|
||||
{
|
||||
|
||||
@@ -8,6 +8,11 @@ public sealed class TiersFile
|
||||
[JsonPropertyName("$schema")] public string? Schema { get; init; }
|
||||
public required int Version { get; init; }
|
||||
public required List<CreditRating> RatingScale { get; init; }
|
||||
/// <summary>
|
||||
/// Gradini di rating sotto quello richiesto a cui l'avanzamento del requisito vale zero (ADR 0018):
|
||||
/// la frazione è 1 − gradini mancanti / questo valore, limitata tra 0 e 1.
|
||||
/// </summary>
|
||||
public required double RatingProgressSteps { get; init; }
|
||||
public required List<TierDef> Tiers { get; init; }
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,295 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Economy;
|
||||
|
||||
/// <summary>
|
||||
/// Requisiti di un livello per una compagnia: per ciascuno il valore attuale, la soglia, se è
|
||||
/// soddisfatto e la frazione raggiunta (0–1), più l'avanzamento complessivo (media delle tre frazioni).
|
||||
/// </summary>
|
||||
public sealed class RequirementProgress
|
||||
{
|
||||
public required int Level { get; init; }
|
||||
public required Money NetWorth { get; init; }
|
||||
public required Money NetWorthRequired { get; init; }
|
||||
public required double NetWorthFraction { get; init; }
|
||||
public required bool NetWorthMet { get; init; }
|
||||
public required int Towns { get; init; }
|
||||
public required int TownsRequired { get; init; }
|
||||
public required int TownPopulation { get; init; }
|
||||
public required double TownsFraction { get; init; }
|
||||
public required bool TownsMet { get; init; }
|
||||
public required CreditRating Rating { get; init; }
|
||||
public required CreditRating RatingRequired { get; init; }
|
||||
public required double RatingFraction { get; init; }
|
||||
public required bool RatingMet { get; init; }
|
||||
/// <summary>Media delle frazioni dei tre requisiti: 1 solo quando sono tutti soddisfatti.</summary>
|
||||
public required double Progress { get; init; }
|
||||
public bool AllMet => NetWorthMet && TownsMet && RatingMet;
|
||||
}
|
||||
|
||||
/// <summary>Un livello di tiers.json visto dalla compagnia: requisiti, se e quando è stato raggiunto, sblocchi.</summary>
|
||||
public sealed class TierOutlook
|
||||
{
|
||||
public required int Level { get; init; }
|
||||
public required string NameIt { get; init; }
|
||||
public required string NameEn { get; init; }
|
||||
public required TierRequirements Requirements { get; init; }
|
||||
public required bool Reached { get; init; }
|
||||
/// <summary>Giorno in cui è stato raggiunto (fondazione per il livello 1; −1 se non raggiunto o sconosciuto).</summary>
|
||||
public required long ReachedDay { get; init; }
|
||||
/// <summary>Sblocchi che il livello aggiunge al precedente (<see cref="Tiers.NewUnlocks"/>).</summary>
|
||||
public required List<TierUnlock> Unlocks { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Voce degli attivi non monetari dello stato patrimoniale.</summary>
|
||||
public readonly record struct AssetLine(AssetCategory Category, Money Value);
|
||||
|
||||
/// <summary>
|
||||
/// Stato patrimoniale della compagnia: attivi per voce (dal valore contabile del motore),
|
||||
/// partecipazioni, cassa; debiti (prestiti e scoperto di cassa). Il patrimonio netto è quello del
|
||||
/// motore (<see cref="Company.NetWorth"/>): Totale attivo − Totale debiti.
|
||||
/// </summary>
|
||||
public sealed class BalanceSheet
|
||||
{
|
||||
public required List<AssetLine> Assets { get; init; }
|
||||
/// <summary>Azioni di altre compagnie al prezzo di mercato.</summary>
|
||||
public required Money Portfolio { get; init; }
|
||||
/// <summary>Cassa positiva (lo scoperto va tra i debiti).</summary>
|
||||
public required Money Cash { get; init; }
|
||||
public required Money TotalAssets { get; init; }
|
||||
public required Money Loans { get; init; }
|
||||
/// <summary>Tasso medio dei prestiti pesato sul residuo (0 senza prestiti).</summary>
|
||||
public required double LoansRate { get; init; }
|
||||
/// <summary>Scoperto di cassa (cassa negativa), tra gli altri debiti.</summary>
|
||||
public required Money Overdraft { get; init; }
|
||||
public required Money TotalLiabilities { get; init; }
|
||||
public required Money NetWorth { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Righe del conto economico del pannello: raggruppano le voci del registro.</summary>
|
||||
public enum IncomeLineKind : byte
|
||||
{
|
||||
/// <summary>Tariffe passeggeri e noli merci.</summary>
|
||||
Fares = 0,
|
||||
/// <summary>Commercio in proprio, contratti, industrie possedute, controllate.</summary>
|
||||
OtherIncome = 1,
|
||||
/// <summary>Costi d'esercizio, salari, penali.</summary>
|
||||
OperatingCosts = 2,
|
||||
/// <summary>Manutenzione dei binari e della flotta.</summary>
|
||||
Maintenance = 3,
|
||||
Interest = 4,
|
||||
}
|
||||
|
||||
public readonly record struct IncomeLine(IncomeLineKind Kind, Money Value);
|
||||
|
||||
/// <summary>Conto economico di un anno (le righe sommano esattamente all'utile operativo del motore).</summary>
|
||||
public sealed class IncomeStatement
|
||||
{
|
||||
public required int Year { get; init; }
|
||||
/// <summary>Anno in corso (fino a oggi) invece dell'ultimo anno chiuso.</summary>
|
||||
public required bool Partial { get; init; }
|
||||
public required List<IncomeLine> Lines { get; init; }
|
||||
public required Money Profit { get; init; }
|
||||
}
|
||||
|
||||
public readonly record struct LoanOutlook(LoanId Id, Money Remaining, double AnnualRate, int MonthsLeft);
|
||||
|
||||
/// <summary>Patrimonio netto a un giorno della partita.</summary>
|
||||
public readonly record struct NetWorthPoint(long Day, Money Value);
|
||||
|
||||
public sealed class ClimbOutlookReport
|
||||
{
|
||||
public required long Day { get; init; }
|
||||
public required CompanyId Company { get; init; }
|
||||
public required long FoundedDay { get; init; }
|
||||
/// <summary>Capitale iniziale della difficoltà (quello del giocatore).</summary>
|
||||
public required Money InitialCapital { get; init; }
|
||||
public required int Tier { get; init; }
|
||||
/// <summary>Livello successivo (0 all'ultimo livello).</summary>
|
||||
public required int NextTier { get; init; }
|
||||
public required List<TierOutlook> Tiers { get; init; }
|
||||
/// <summary>Requisiti del livello successivo (null all'ultimo livello).</summary>
|
||||
public required RequirementProgress? Next { get; init; }
|
||||
public required BalanceSheet Balance { get; init; }
|
||||
public required IncomeStatement Income { get; init; }
|
||||
public required List<LoanOutlook> Loans { get; init; }
|
||||
public required Money MaxLoan { get; init; }
|
||||
public required Money LoanAvailable { get; init; }
|
||||
public required double NewLoanRate { get; init; }
|
||||
/// <summary>In amministrazione controllata i prestiti non si possono chiedere.</summary>
|
||||
public required bool LoansAllowed { get; init; }
|
||||
/// <summary>Patrimonio netto: fondazione, fine di ogni anno dello storico, oggi.</summary>
|
||||
public required List<NetWorthPoint> History { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quadro della scalata per il pannello «La tua scalata» (ADR 0018): pura funzione del mondo, come
|
||||
/// <see cref="MarketOutlook"/>. Livelli e sblocchi da tiers.json, requisiti del prossimo livello con
|
||||
/// l'avanzamento, stato patrimoniale dalle voci del valore contabile del motore, conto economico
|
||||
/// dell'ultimo anno, prestiti e storico del patrimonio netto (lo storico annuale della Cronaca).
|
||||
/// </summary>
|
||||
public static class ClimbOutlook
|
||||
{
|
||||
public static ClimbOutlookReport Build(World w, CompanyId company)
|
||||
{
|
||||
var c = w.Company(company);
|
||||
var tiers = w.Data.Tiers.Tiers;
|
||||
var list = new List<TierOutlook>(tiers.Count);
|
||||
foreach (var t in tiers)
|
||||
{
|
||||
list.Add(new TierOutlook
|
||||
{
|
||||
Level = t.Level, NameIt = t.NameIt, NameEn = t.NameEn, Requirements = t.Requirements,
|
||||
Reached = c.Tier >= t.Level,
|
||||
ReachedDay = t.Level <= 1 ? c.FoundedDay : c.Tier >= t.Level ? c.TierReachedDay[Math.Min(t.Level, c.TierReachedDay.Length) - 1] : -1,
|
||||
Unlocks = Simulation.Systems.Tiers.NewUnlocks(w, c, t.Level),
|
||||
});
|
||||
}
|
||||
var max = FinanceSystem.MaxLoan(w, c);
|
||||
return new ClimbOutlookReport
|
||||
{
|
||||
Day = w.Clock.Day,
|
||||
Company = c.Id,
|
||||
FoundedDay = c.FoundedDay,
|
||||
InitialCapital = new Money(w.Difficulty.InitialCapital),
|
||||
Tier = c.Tier,
|
||||
NextTier = c.Tier < tiers.Count ? tiers[c.Tier].Level : 0,
|
||||
Tiers = list,
|
||||
Next = c.Tier < tiers.Count ? Requirements(w, c, tiers[c.Tier]) : null,
|
||||
Balance = Balance(c),
|
||||
Income = Income(w, c),
|
||||
Loans = c.Loans.Select(l => new LoanOutlook(l.Id, l.Remaining, l.AnnualRate, l.MonthsLeft)).ToList(),
|
||||
MaxLoan = max,
|
||||
LoanAvailable = Money.Max(Money.Zero, max - c.Debt),
|
||||
NewLoanRate = FinanceSystem.LoanRate(w, c),
|
||||
LoansAllowed = !c.Receivership,
|
||||
History = History(w, c),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Requisiti di un livello per la compagnia, con gli stessi confronti di <see cref="Simulation.Systems.Tiers.Meets"/>.
|
||||
/// Frazioni: patrimonio / soglia e città / città richieste (limitate a 1; 1 se la soglia è zero); per il
|
||||
/// rating 1 − gradini mancanti / <see cref="TiersFile.RatingProgressSteps"/> (limitata tra 0 e 1).
|
||||
/// L'avanzamento è la loro media, sotto 1 finché un requisito manca (<see cref="ProgressCap"/>).
|
||||
/// </summary>
|
||||
public static RequirementProgress Requirements(World w, Company c, TierDef tier)
|
||||
{
|
||||
var req = tier.Requirements;
|
||||
int towns = Simulation.Systems.Tiers.ConnectedTowns(w, c.Id, req.ConnectedTownsOver.Population);
|
||||
double worth = req.NetWorth <= 0 ? 1 : DMath.Clamp((double)c.NetWorth.Cents / req.NetWorth, 0, 1);
|
||||
double townsFraction = req.ConnectedTownsOver.Count <= 0 ? 1 : DMath.Clamp((double)towns / req.ConnectedTownsOver.Count, 0, 1);
|
||||
double rating = RatingFraction(w, c.Rating, req.CreditRating);
|
||||
bool worthMet = c.NetWorth.Cents >= req.NetWorth, townsMet = towns >= req.ConnectedTownsOver.Count, ratingMet = c.Rating <= req.CreditRating;
|
||||
double progress = (worth + townsFraction + rating) / 3;
|
||||
if (!(worthMet && townsMet && ratingMet)) progress = Math.Min(progress, ProgressCap);
|
||||
return new RequirementProgress
|
||||
{
|
||||
Level = tier.Level,
|
||||
NetWorth = c.NetWorth, NetWorthRequired = new Money(req.NetWorth), NetWorthFraction = worth, NetWorthMet = worthMet,
|
||||
Towns = towns, TownsRequired = req.ConnectedTownsOver.Count, TownPopulation = req.ConnectedTownsOver.Population,
|
||||
TownsFraction = townsFraction, TownsMet = townsMet,
|
||||
Rating = c.Rating, RatingRequired = req.CreditRating, RatingFraction = rating, RatingMet = ratingMet,
|
||||
Progress = progress,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tetto dell'avanzamento finché un requisito manca: una frazione arrotondata a 1 non basta, il pieno
|
||||
/// arriva solo con tutti i requisiti soddisfatti. Non è un parametro di gioco (non cambia la promozione,
|
||||
/// che segue <see cref="Simulation.Systems.Tiers.Meets"/>): il client mostra le percentuali per difetto,
|
||||
/// quindi sotto il tetto legge al massimo «99%».
|
||||
/// </summary>
|
||||
public const double ProgressCap = 0.999;
|
||||
|
||||
/// <summary>
|
||||
/// Frazione del requisito di rating: 1 se soddisfatto, altrimenti 1 − gradini mancanti /
|
||||
/// ratingProgressSteps di tiers.json, limitata tra 0 e 1 (immagine 08: un gradino sotto vale il 60 %).
|
||||
/// </summary>
|
||||
public static double RatingFraction(World w, CreditRating current, CreditRating required)
|
||||
{
|
||||
if (current <= required) return 1;
|
||||
int missing = (int)current - (int)required;
|
||||
return DMath.Clamp(1 - missing / w.Data.Tiers.RatingProgressSteps, 0, 1);
|
||||
}
|
||||
|
||||
/// <summary>Stato patrimoniale dalle voci del motore: somma esattamente al patrimonio netto.</summary>
|
||||
public static BalanceSheet Balance(Company c)
|
||||
{
|
||||
var assets = new List<AssetLine>(AssetCategories.Count);
|
||||
for (int k = 0; k < AssetCategories.Count; k++) assets.Add(new AssetLine((AssetCategory)k, new Money(c.BookValues[k])));
|
||||
var cash = Money.Max(Money.Zero, c.Cash);
|
||||
var overdraft = Money.Max(Money.Zero, -c.Cash);
|
||||
var total = c.AssetBookValue + c.PortfolioValue + cash;
|
||||
var loans = c.Debt;
|
||||
double rate = 0;
|
||||
if (loans.Cents > 0)
|
||||
{
|
||||
double weighted = 0;
|
||||
foreach (var l in c.Loans) weighted += (double)l.Remaining.Cents * l.AnnualRate;
|
||||
rate = weighted / loans.Cents;
|
||||
}
|
||||
return new BalanceSheet
|
||||
{
|
||||
Assets = assets, Portfolio = c.PortfolioValue, Cash = cash, TotalAssets = total,
|
||||
Loans = loans, LoansRate = rate, Overdraft = overdraft, TotalLiabilities = loans + overdraft,
|
||||
NetWorth = total - loans - overdraft,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Conto economico dell'ultimo anno chiuso (o dell'anno in corso, per una compagnia fondata
|
||||
/// quest'anno): righe raggruppate dalle voci del registro; l'utile è <see cref="Company.OperatingProfit"/>.
|
||||
/// </summary>
|
||||
public static IncomeStatement Income(World w, Company c)
|
||||
{
|
||||
long yearStart = (long)(w.Clock.Year - w.Calendar.StartYear) * w.Calendar.DaysPerYear;
|
||||
bool closed = w.Clock.Year > w.Calendar.StartYear && c.FoundedDay < yearStart;
|
||||
var e = closed ? c.LastYearEntries : c.YearEntries;
|
||||
long Sum(params LedgerEntry[] keys)
|
||||
{
|
||||
long s = 0;
|
||||
foreach (var k in keys) s += e[(int)k];
|
||||
return s;
|
||||
}
|
||||
var lines = new List<IncomeLine>
|
||||
{
|
||||
new(IncomeLineKind.Fares, new Money(Sum(LedgerEntry.FreightRevenue, LedgerEntry.PassengerRevenue))),
|
||||
new(IncomeLineKind.OtherIncome, new Money(Sum(LedgerEntry.Trading, LedgerEntry.Contracts, LedgerEntry.Industries, LedgerEntry.Subsidiaries))),
|
||||
new(IncomeLineKind.OperatingCosts, new Money(Sum(LedgerEntry.RunningCosts, LedgerEntry.Wages, LedgerEntry.Penalties))),
|
||||
new(IncomeLineKind.Maintenance, new Money(Sum(LedgerEntry.TrackMaintenance, LedgerEntry.FleetMaintenance))),
|
||||
new(IncomeLineKind.Interest, new Money(Sum(LedgerEntry.Interest))),
|
||||
};
|
||||
return new IncomeStatement
|
||||
{
|
||||
Year = closed ? w.Clock.Year - 1 : w.Clock.Year,
|
||||
Partial = !closed,
|
||||
Lines = lines,
|
||||
Profit = new Money(Company.OperatingProfit(e)),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Patrimonio netto nel tempo: il capitale iniziale alla fondazione, la fotografia di fine anno
|
||||
/// dello storico (al primo giorno dell'anno dopo) e il valore di oggi. La fotografia del primo giorno
|
||||
/// dell'anno in corso lascia il posto a oggi: un punto per anno di calendario, come l'immagine 08.
|
||||
/// </summary>
|
||||
public static List<NetWorthPoint> History(World w, Company c)
|
||||
{
|
||||
var points = new List<NetWorthPoint> { new(c.FoundedDay, new Money(w.Difficulty.InitialCapital)) };
|
||||
long today = w.Clock.Day;
|
||||
long yearStart = (long)(w.Clock.Year - w.Calendar.StartYear) * w.Calendar.DaysPerYear;
|
||||
foreach (var y in c.History)
|
||||
{
|
||||
long day = (long)(y.Year + 1 - w.Calendar.StartYear) * w.Calendar.DaysPerYear;
|
||||
if (day <= points[^1].Day || day >= yearStart) continue;
|
||||
points.Add(new NetWorthPoint(day, new Money(y.NetWorthCents)));
|
||||
}
|
||||
if (today > points[^1].Day) points.Add(new NetWorthPoint(today, c.NetWorth));
|
||||
else points[^1] = new NetWorthPoint(points[^1].Day, c.NetWorth);
|
||||
return points;
|
||||
}
|
||||
}
|
||||
@@ -31,6 +31,26 @@ public enum LedgerEntry : byte
|
||||
Subsidiaries = 20,
|
||||
}
|
||||
|
||||
/// <summary>Voci dello stato patrimoniale per gli attivi non monetari (ADR 0018).</summary>
|
||||
public enum AssetCategory : byte
|
||||
{
|
||||
/// <summary>Binari e opere (ponti, gallerie), ammortizzati.</summary>
|
||||
Track = 0,
|
||||
/// <summary>Stazioni e depositi, al costo.</summary>
|
||||
Stations = 1,
|
||||
/// <summary>Veicoli, ammortizzati.</summary>
|
||||
Vehicles = 2,
|
||||
/// <summary>Industrie possedute: impianti e cassa dell'impresa.</summary>
|
||||
Industries = 3,
|
||||
/// <summary>Merce propria in magazzino e in viaggio, al prezzo globale.</summary>
|
||||
Goods = 4,
|
||||
}
|
||||
|
||||
public static class AssetCategories
|
||||
{
|
||||
public const int Count = 5;
|
||||
}
|
||||
|
||||
/// <summary>Prestito con rata costante (ammortamento alla francese).</summary>
|
||||
public sealed class Loan
|
||||
{
|
||||
@@ -77,8 +97,28 @@ public sealed class Company
|
||||
/// <summary>Movimenti dell'anno precedente per voce (per rating e borsa).</summary>
|
||||
public long[] LastYearEntries { get; } = new long[EntryCount];
|
||||
|
||||
/// <summary>Valore contabile degli attivi non monetari (binari, stazioni, veicoli), aggiornato mensilmente.</summary>
|
||||
public Money AssetBookValue { get; set; }
|
||||
/// <summary>
|
||||
/// Valore contabile degli attivi non monetari per voce (<see cref="AssetCategory"/>, centesimi),
|
||||
/// aggiornato ogni mese da <c>FinanceSystem.UpdateBookValues</c> (ADR 0018).
|
||||
/// </summary>
|
||||
public long[] BookValues { get; } = new long[AssetCategories.Count];
|
||||
|
||||
/// <summary>Valore contabile degli attivi non monetari: somma delle voci di <see cref="BookValues"/>.</summary>
|
||||
public Money AssetBookValue
|
||||
{
|
||||
get
|
||||
{
|
||||
long sum = 0;
|
||||
foreach (long v in BookValues) sum += v;
|
||||
return new Money(sum);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Giorno in cui la compagnia ha raggiunto ciascun livello (indice livello − 1; −1 se non
|
||||
/// raggiunto o sconosciuto). Il livello 1 non si annota: vale dalla fondazione (ADR 0018).
|
||||
/// </summary>
|
||||
public long[] TierReachedDay { get; } = [-1, -1, -1, -1, -1];
|
||||
|
||||
public Money Debt
|
||||
{
|
||||
|
||||
@@ -60,7 +60,7 @@ public sealed class TradingProgress
|
||||
public required bool Unlocked { get; init; }
|
||||
/// <summary>Livello che sblocca il commercio (0 se nessuno).</summary>
|
||||
public required int Level { get; init; }
|
||||
/// <summary>Minimo tra le frazioni dei requisiti numerici (patrimonio, città collegate), in [0, 1].</summary>
|
||||
/// <summary>Avanzamento verso il livello (media delle frazioni dei tre requisiti, ADR 0018), in [0, 1].</summary>
|
||||
public required double Fraction { get; init; }
|
||||
public required Money NetWorth { get; init; }
|
||||
public required Money NetWorthRequired { get; init; }
|
||||
@@ -413,24 +413,22 @@ public static class MarketOutlook
|
||||
Rating = c?.Rating ?? CreditRating.D, RatingRequired = r?.CreditRating ?? CreditRating.D, RatingMet = false,
|
||||
};
|
||||
}
|
||||
var req = target.Requirements;
|
||||
int towns = Tiers.ConnectedTowns(w, c.Id, req.ConnectedTownsOver.Population);
|
||||
double worth = req.NetWorth <= 0 ? 1 : DMath.Clamp((double)c.NetWorth.Cents / req.NetWorth, 0, 1);
|
||||
double townsFraction = req.ConnectedTownsOver.Count <= 0 ? 1 : DMath.Clamp((double)towns / req.ConnectedTownsOver.Count, 0, 1);
|
||||
// stessi requisiti e stesso avanzamento del pannello «La tua scalata» (ADR 0018)
|
||||
var progress = ClimbOutlook.Requirements(w, c, target);
|
||||
bool unlocked = Tiers.Unlocks(w, c).Trading;
|
||||
return new TradingProgress
|
||||
{
|
||||
Unlocked = unlocked,
|
||||
Level = target.Level,
|
||||
Fraction = unlocked ? 1 : Math.Min(worth, townsFraction),
|
||||
NetWorth = c.NetWorth,
|
||||
NetWorthRequired = new Money(req.NetWorth),
|
||||
TownsConnected = towns,
|
||||
TownsRequired = req.ConnectedTownsOver.Count,
|
||||
TownPopulation = req.ConnectedTownsOver.Population,
|
||||
Rating = c.Rating,
|
||||
RatingRequired = req.CreditRating,
|
||||
RatingMet = c.Rating <= req.CreditRating,
|
||||
Fraction = unlocked ? 1 : progress.Progress,
|
||||
NetWorth = progress.NetWorth,
|
||||
NetWorthRequired = progress.NetWorthRequired,
|
||||
TownsConnected = progress.Towns,
|
||||
TownsRequired = progress.TownsRequired,
|
||||
TownPopulation = progress.TownPopulation,
|
||||
Rating = progress.Rating,
|
||||
RatingRequired = progress.RatingRequired,
|
||||
RatingMet = progress.RatingMet,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
namespace RailEnterprise.Core.Persistence;
|
||||
|
||||
/// <summary>
|
||||
/// Stato patrimoniale delle compagnie (corpo del salvataggio dalla versione 6, ADR 0018): valore
|
||||
/// contabile degli attivi per voce (<see cref="AssetCategory"/>) e giorno in cui ogni livello è stato
|
||||
/// raggiunto. Entra nell'hash giornaliero con lo stato dinamico. Le versioni precedenti salvano solo
|
||||
/// il totale degli attivi: <see cref="Migrate"/> lo ripartisce senza cambiarlo.
|
||||
/// </summary>
|
||||
public static class BalanceSheetSerializer
|
||||
{
|
||||
public static void Write(World w, SaveWriter s)
|
||||
{
|
||||
s.Write(w.Companies.Count);
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
s.Write(c.BookValues);
|
||||
s.Write(c.TierReachedDay);
|
||||
}
|
||||
}
|
||||
|
||||
public static void Read(World w, SaveReader r)
|
||||
{
|
||||
int n = r.ReadInt32();
|
||||
if (n != w.Companies.Count) throw new InvalidDataException($"Stato patrimoniale di {n} compagnie su {w.Companies.Count}");
|
||||
foreach (var c in w.Companies)
|
||||
{
|
||||
CopyInto(r.ReadInt64Array(), c.BookValues);
|
||||
CopyInto(r.ReadInt64Array(), c.TierReachedDay);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Migrazione dalle versioni 1–5: il totale salvato (letto nella voce dei binari) si ripartisce in
|
||||
/// proporzione alla scomposizione calcolata al giorno del caricamento, con il resto dell'arrotondamento
|
||||
/// sulla voce più grande; il totale, e quindi il patrimonio netto, non cambia fino al ricalcolo del
|
||||
/// mese. I giorni dei livelli si ricostruiscono dai fatti salienti («diventa «nome»») e, in mancanza,
|
||||
/// dallo storico annuale (giorno della prima fotografia con il livello, tra fondazione e oggi).
|
||||
/// </summary>
|
||||
public static void Migrate(World w)
|
||||
{
|
||||
var live = FinanceSystem.BookValues(w);
|
||||
for (int i = 0; i < w.Companies.Count; i++)
|
||||
{
|
||||
var c = w.Companies[i];
|
||||
long total = c.AssetBookValue.Cents;
|
||||
Array.Clear(c.BookValues);
|
||||
long liveSum = 0;
|
||||
foreach (long v in live[i]) liveSum += v;
|
||||
if (total != 0 && liveSum > 0)
|
||||
{
|
||||
long assigned = 0;
|
||||
int largest = 0;
|
||||
for (int k = 0; k < AssetCategories.Count; k++)
|
||||
{
|
||||
c.BookValues[k] = (long)((Int128)total * live[i][k] / liveSum);
|
||||
assigned += c.BookValues[k];
|
||||
if (live[i][k] > live[i][largest]) largest = k;
|
||||
}
|
||||
c.BookValues[largest] += total - assigned;
|
||||
}
|
||||
else
|
||||
{
|
||||
c.BookValues[(int)AssetCategory.Track] = total;
|
||||
}
|
||||
RebuildTierDays(w, c);
|
||||
}
|
||||
}
|
||||
|
||||
private static void RebuildTierDays(World w, Company c)
|
||||
{
|
||||
Array.Fill(c.TierReachedDay, -1L);
|
||||
var tiers = w.Data.Tiers.Tiers;
|
||||
for (int level = 2; level <= Math.Min(c.Tier, c.TierReachedDay.Length); level++)
|
||||
{
|
||||
string text = $"diventa «{tiers[level - 1].NameIt}»";
|
||||
long day = c.Milestones.FirstOrDefault(m => m.Text == text, new CompanyMilestone(-1, "")).Day;
|
||||
if (day < 0)
|
||||
{
|
||||
// la fotografia dell'anno Y si scatta il primo giorno di Y+1, dopo la chiusura del mese che
|
||||
// può aver promosso la compagnia: il livello è certo solo da quel giorno (come ClimbOutlook.History)
|
||||
int year = c.History.FirstOrDefault(y => y.Tier >= level, new CompanyYear(int.MinValue, 0, 0, 0, 0, 0, 0, 0, 0)).Year;
|
||||
if (year != int.MinValue)
|
||||
day = Math.Clamp((long)(year + 1 - w.Calendar.StartYear) * w.Calendar.DaysPerYear, Math.Max(0, c.FoundedDay), Math.Max(c.FoundedDay, w.Clock.Day));
|
||||
}
|
||||
c.TierReachedDay[level - 1] = day;
|
||||
}
|
||||
}
|
||||
|
||||
private static void CopyInto(long[] source, long[] target) =>
|
||||
Array.Copy(source, target, Math.Min(source.Length, target.Length));
|
||||
}
|
||||
@@ -14,7 +14,7 @@ namespace RailEnterprise.Core.Persistence;
|
||||
public static class WorldSerializer
|
||||
{
|
||||
/// <summary>Versione del corpo del salvataggio (migrazioni in <see cref="Read"/>).</summary>
|
||||
public const int BodyVersion = 5;
|
||||
public const int BodyVersion = 6;
|
||||
|
||||
/// <summary>Scrive l'intero mondo (impostazioni, terreno, stato dinamico, eventi).</summary>
|
||||
public static void Write(World w, SaveWriter s) => Write(w, s, BodyVersion);
|
||||
@@ -247,6 +247,7 @@ public static class WorldSerializer
|
||||
if (version >= 3) CorporateSerializer.Write(w, s);
|
||||
if (version >= 4) TradingSerializer.Write(w, s);
|
||||
if (version >= 5) EventSerializer.Write(w, s);
|
||||
if (version >= 6) BalanceSheetSerializer.Write(w, s);
|
||||
}
|
||||
|
||||
private static void WriteRecipeStock(List<RecipeItemDef> items, int[] stock, SaveWriter s)
|
||||
@@ -641,7 +642,8 @@ public static class WorldSerializer
|
||||
CopyInto(r.ReadInt64Array(), c.MonthEntries);
|
||||
CopyInto(r.ReadInt64Array(), c.YearEntries);
|
||||
CopyInto(r.ReadInt64Array(), c.LastYearEntries);
|
||||
c.AssetBookValue = new Money(r.ReadInt64());
|
||||
// totale degli attivi: dalla versione 6 lo sostituisce la scomposizione per voce (BalanceSheetSerializer)
|
||||
c.BookValues[(int)AssetCategory.Track] = r.ReadInt64();
|
||||
int loans = r.ReadInt32();
|
||||
for (int k = 0; k < loans; k++)
|
||||
{
|
||||
@@ -707,6 +709,9 @@ public static class WorldSerializer
|
||||
else TradingSerializer.Migrate(w);
|
||||
// versione 5 (F6): eventi del mondo in corso; prima nessun evento attivo
|
||||
if (version >= 5) EventSerializer.Read(w, r);
|
||||
// versione 6 (F6): stato patrimoniale per voce e giorni dei livelli raggiunti
|
||||
if (version >= 6) BalanceSheetSerializer.Read(w, r);
|
||||
else BalanceSheetSerializer.Migrate(w);
|
||||
}
|
||||
|
||||
private static void ReadRecipeStock(List<RecipeItemDef> items, int[] stock, SaveReader r)
|
||||
|
||||
@@ -62,6 +62,14 @@ public static class CommandProcessor
|
||||
BuyGoodsCommand c => TradingCommandHandlers.Buy(w, company, c, Reply),
|
||||
SellGoodsCommand c => TradingCommandHandlers.Sell(w, company, c, Reply),
|
||||
ShipGoodsCommand c => TradingCommandHandlers.Ship(w, company, c, ctx, Reply),
|
||||
// le concessioni (F7) si rifiutano prima per il livello, poi perché non ancora disponibili; il testo
|
||||
// non promette che il livello basti
|
||||
BuyConcessionCommand when !Tiers.Unlocks(w, company).Concessions =>
|
||||
Result(CommandError.TierLocked, Tiers.ConcessionsAvailable
|
||||
? Tiers.LockedText(w, "Le concessioni", u => u.Concessions, plural: true)
|
||||
: Tiers.ConcessionsUnavailableText(w)),
|
||||
BuyConcessionCommand when !Tiers.ConcessionsAvailable =>
|
||||
Result(CommandError.NotImplemented, "Le concessioni non sono ancora disponibili"),
|
||||
_ => Result(CommandError.NotImplemented, $"Comando {command.Type} non ancora disponibile"),
|
||||
};
|
||||
}
|
||||
@@ -72,7 +80,7 @@ public static class CommandProcessor
|
||||
if (company.Receivership) return result(CommandError.NotAllowed, "In amministrazione controllata non si possono chiedere prestiti");
|
||||
var max = FinanceSystem.MaxLoan(w, company);
|
||||
if (company.Debt + c.Amount > max)
|
||||
return result(CommandError.CreditLimit, $"Fido insufficiente: disponibili {(max - company.Debt).ToString()}");
|
||||
return result(CommandError.CreditLimit, LoanLimitText(w, company, max));
|
||||
var fb = w.Data.Balance.Finance;
|
||||
var loan = new Loan
|
||||
{
|
||||
@@ -88,6 +96,18 @@ public static class CommandProcessor
|
||||
return result(CommandError.None, $"Prestito di {c.Amount} al {loan.AnnualRate * 100:F1}% per {loan.TermMonths / 12} anni");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rifiuto per fido insufficiente: quanto resta disponibile e, se un livello successivo alza il
|
||||
/// fattore del fido, quale livello serve e a quanto porta il fido (ADR 0018).
|
||||
/// </summary>
|
||||
public static string LoanLimitText(World w, Company company, Money max)
|
||||
{
|
||||
string text = $"Fido insufficiente: disponibili {Money.Max(Money.Zero, max - company.Debt)} su {max}";
|
||||
var current = Tiers.Def(w, company.Tier);
|
||||
var next = w.Data.Tiers.Tiers.FirstOrDefault(t => t.Level > current.Level && t.Unlocks.MaxLoanFactor > current.Unlocks.MaxLoanFactor);
|
||||
return next is null ? text : $"{text}; il livello {next.Level}, «{next.NameIt}», porta il fido a {Tiers.LoanLimit(company, next)}";
|
||||
}
|
||||
|
||||
private static CommandResult RepayLoan(World w, Company company, RepayLoanCommand c, Func<CommandError, string, CommandResult> result)
|
||||
{
|
||||
var loan = company.Loans.FirstOrDefault(l => l.Id == c.Loan);
|
||||
|
||||
@@ -16,7 +16,7 @@ public static class CorporateCommandHandlers
|
||||
{
|
||||
var sm = w.Data.Balance.StockMarket;
|
||||
if (company.IsPlayer && !company.Listed && !Tiers.Unlocks(w, company).Ipo)
|
||||
return reply(CommandError.TierLocked, "La quotazione si sblocca al livello «Grande compagnia»");
|
||||
return reply(CommandError.TierLocked, Tiers.LockedText(w, "La quotazione in borsa", u => u.Ipo));
|
||||
// prima quotazione fino a ipoMaxShare; per chi è già quotato un aumento di capitale fino al flottante massimo
|
||||
double limit = company.Listed ? sm.SecondaryMaxFloat - (double)company.Shares.Public / company.Shares.Total : sm.IpoMaxShare;
|
||||
if (!(c.FloatShare > 0) || c.FloatShare > limit + 1e-9)
|
||||
@@ -137,7 +137,7 @@ public static class CorporateCommandHandlers
|
||||
if (target.Defunct) return reply(CommandError.NotAllowed, $"{target.Name} non è più attiva");
|
||||
|
||||
if (company.IsPlayer && !Tiers.Unlocks(w, company).HostileTakeover)
|
||||
return reply(CommandError.TierLocked, "Le scalate ostili si sbloccano al livello «Impero ferroviario»");
|
||||
return reply(CommandError.TierLocked, Tiers.LockedText(w, "Le scalate ostili", u => u.HostileTakeover, plural: true));
|
||||
if (!target.Listed) return reply(CommandError.NotAllowed, $"{target.Name} non è quotata");
|
||||
if (target.IsPlayer && w.Difficulty.PlayerTakeover == TakeoverRule.Disabled)
|
||||
return reply(CommandError.NotAllowed, "Con questa difficoltà la compagnia del giocatore non è scalabile");
|
||||
|
||||
@@ -11,7 +11,7 @@ public static class IndustryCommandHandlers
|
||||
public static CommandResult BuyIndustry(World w, Company company, BuyIndustryCommand c, RailCommandHandlers.Reply reply)
|
||||
{
|
||||
if (!Tiers.Unlocks(w, company).BuyIndustry)
|
||||
return reply(CommandError.TierLocked, "L'acquisto di industrie si sblocca al livello «Compagnia nazionale»");
|
||||
return reply(CommandError.TierLocked, Tiers.LockedText(w, "L'acquisto di industrie", u => u.BuyIndustry));
|
||||
if (!TryIndustry(w, c.Industry, out var ind) || ind.Closed) return reply(CommandError.NotFound, "Industria inesistente");
|
||||
if (ind.Owner == company.Id) return reply(CommandError.NotAllowed, $"{ind.Name} è già della compagnia");
|
||||
if (ind.Owner.IsValid) return reply(CommandError.NotAllowed, $"{ind.Name} appartiene a {w.Company(ind.Owner).Name}");
|
||||
|
||||
@@ -23,11 +23,7 @@ public sealed class ConstructionSystem : ISimSystem
|
||||
}
|
||||
|
||||
/// <summary>Squadre disponibili per una compagnia secondo il livello.</summary>
|
||||
public static int Crews(World w, Company c)
|
||||
{
|
||||
var byTier = w.Data.Construction.Crews.CrewsByTier;
|
||||
return byTier[Math.Clamp(c.Tier, 1, byTier.Length) - 1];
|
||||
}
|
||||
public static int Crews(World w, Company c) => Tiers.Crews(w, c.Tier);
|
||||
|
||||
private static void Projects(WorldContext ctx, World w)
|
||||
{
|
||||
|
||||
@@ -85,46 +85,66 @@ public sealed class FinanceSystem : ISimSystem
|
||||
|
||||
/// <summary>
|
||||
/// Valore contabile degli attivi: binari e veicoli ammortizzati, stazioni e depositi al costo,
|
||||
/// merce della compagnia (magazzini e spedizioni in viaggio) al prezzo globale (ADR 0016).
|
||||
/// industrie possedute (impianti e cassa dell'impresa, ADR 0018), merce della compagnia
|
||||
/// (magazzini e spedizioni in viaggio) al prezzo globale (ADR 0016). Scrive le voci in
|
||||
/// <see cref="Company.BookValues"/>: il patrimonio netto le somma.
|
||||
/// </summary>
|
||||
public static void UpdateBookValues(World w)
|
||||
{
|
||||
var values = BookValues(w);
|
||||
for (int i = 0; i < w.Companies.Count; i++) Array.Copy(values[i], w.Companies[i].BookValues, AssetCategories.Count);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Stato patrimoniale degli attivi non monetari di ogni compagnia, per voce
|
||||
/// (<see cref="AssetCategory"/>), calcolato al giorno corrente. Unica fonte del valore contabile.
|
||||
/// </summary>
|
||||
public static long[][] BookValues(World w)
|
||||
{
|
||||
var fb = w.Data.Balance.Finance;
|
||||
var values = new long[w.Companies.Count];
|
||||
var values = new long[w.Companies.Count][];
|
||||
for (int i = 0; i < values.Length; i++) values[i] = new long[AssetCategories.Count];
|
||||
const int track = (int)AssetCategory.Track, stations = (int)AssetCategory.Stations, vehicles = (int)AssetCategory.Vehicles,
|
||||
industries = (int)AssetCategory.Industries, goods = (int)AssetCategory.Goods;
|
||||
double daysPerYear = w.Calendar.DaysPerYear;
|
||||
long today = w.Clock.Day;
|
||||
foreach (var e in w.Network.Edges)
|
||||
{
|
||||
if (e.State == Rail.EdgeState.Demolished) continue;
|
||||
double age = (today - e.BuiltDay) / daysPerYear;
|
||||
values[e.Owner.Value] += (long)(e.BuildCostCents * Math.Max(fb.BookValueFloor, 1 - age / fb.DepreciationYearsTrack));
|
||||
values[e.Owner.Value][track] += (long)(e.BuildCostCents * Math.Max(fb.BookValueFloor, 1 - age / fb.DepreciationYearsTrack));
|
||||
}
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (w.Network.Nodes[s.Node.Value].Station == s.Id) values[s.Owner.Value] += s.BuildCostCents;
|
||||
if (w.Network.Nodes[s.Node.Value].Station == s.Id) values[s.Owner.Value][stations] += s.BuildCostCents;
|
||||
}
|
||||
foreach (var d in w.Network.Depots)
|
||||
{
|
||||
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) values[d.Owner.Value] += d.BuildCostCents;
|
||||
if (w.Network.Nodes[d.Node.Value].Depot == d.Id) values[d.Owner.Value][stations] += d.BuildCostCents;
|
||||
}
|
||||
foreach (var v in w.Vehicles)
|
||||
{
|
||||
if (v.Sold) continue;
|
||||
double age = (today - v.BoughtDay) / daysPerYear;
|
||||
values[v.Owner.Value] += (long)(v.Def.Price * Math.Max(fb.BookValueFloor, 1 - age / v.Def.LifeYears));
|
||||
values[v.Owner.Value][vehicles] += (long)(v.Def.Price * Math.Max(fb.BookValueFloor, 1 - age / v.Def.LifeYears));
|
||||
}
|
||||
foreach (var ind in w.Industries)
|
||||
{
|
||||
if (ind.Closed || !ind.Owner.IsValid || ind.Owner.Value >= values.Length) continue;
|
||||
values[ind.Owner.Value][industries] += IndustryMath.BookValue(w, ind).Cents;
|
||||
}
|
||||
var prices = w.Market.GlobalPrice;
|
||||
foreach (var s in w.Network.Stations)
|
||||
{
|
||||
if (!s.Owner.IsValid || s.Owner.Value >= values.Length) continue;
|
||||
for (int g = 0; g < s.Stock.Length; g++) values[s.Owner.Value] += (long)(s.Stock[g] * prices[g]);
|
||||
values[s.Owner.Value] += OwnedGoodsValue(s.Waiting, prices);
|
||||
for (int g = 0; g < s.Stock.Length; g++) values[s.Owner.Value][goods] += (long)(s.Stock[g] * prices[g]);
|
||||
values[s.Owner.Value][goods] += OwnedGoodsValue(s.Waiting, prices);
|
||||
}
|
||||
foreach (var t in w.Trains)
|
||||
{
|
||||
if (!t.Removed && t.Owner.IsValid && t.Owner.Value < values.Length) values[t.Owner.Value] += OwnedGoodsValue(t.Cargo, prices);
|
||||
if (!t.Removed && t.Owner.IsValid && t.Owner.Value < values.Length) values[t.Owner.Value][goods] += OwnedGoodsValue(t.Cargo, prices);
|
||||
}
|
||||
for (int i = 0; i < w.Companies.Count; i++) w.Companies[i].AssetBookValue = new Money(values[i]);
|
||||
return values;
|
||||
}
|
||||
|
||||
private static long OwnedGoodsValue(List<Rail.Packet> packets, double[] prices)
|
||||
@@ -192,11 +212,7 @@ public sealed class FinanceSystem : ISimSystem
|
||||
}
|
||||
|
||||
/// <summary>Fido massimo della compagnia secondo il livello raggiunto.</summary>
|
||||
public static Money MaxLoan(World w, Company c)
|
||||
{
|
||||
var tier = w.Data.Tiers.Tiers[Math.Clamp(c.Tier, 1, w.Data.Tiers.Tiers.Count) - 1];
|
||||
return c.BaseCredit * tier.Unlocks.MaxLoanFactor;
|
||||
}
|
||||
public static Money MaxLoan(World w, Company c) => Tiers.LoanLimit(c, Tiers.Def(w, c.Tier));
|
||||
|
||||
/// <summary>Tasso annuo per un nuovo prestito: base della difficoltà + spread del rating.</summary>
|
||||
public static double LoanRate(World w, Company c) =>
|
||||
|
||||
@@ -92,8 +92,22 @@ public static class IndustryMath
|
||||
public static Common.Money Valuation(World w, Industry ind)
|
||||
{
|
||||
var p = w.Data.Balance.IndustryMaintenance.Purchase;
|
||||
double plant = ind.Def.UpgradeCost * Math.Max(1, ind.Level) * p.AssetShare * (1 - p.ConditionWeight + p.ConditionWeight * ind.Condition / 100);
|
||||
double earnings = Math.Max(0, AnnualProfit(w, ind)) * p.EarningsMultiple;
|
||||
return Common.Money.FromCentsRounded(plant + earnings + Math.Max(0, ind.Cash.Cents));
|
||||
return Common.Money.FromCentsRounded(PlantValue(w, ind, Math.Max(1, ind.Level)) + earnings + Math.Max(0, ind.Cash.Cents));
|
||||
}
|
||||
|
||||
/// <summary>Valore degli impianti: costo d'ammodernamento × livello × quota, secondo le condizioni.</summary>
|
||||
public static double PlantValue(World w, Industry ind, int level)
|
||||
{
|
||||
var p = w.Data.Balance.IndustryMaintenance.Purchase;
|
||||
return ind.Def.UpgradeCost * level * p.AssetShare * (1 - p.ConditionWeight + p.ConditionWeight * ind.Condition / 100);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Valore contabile di un'industria per il proprietario (ADR 0018): il prezzo d'acquisto senza
|
||||
/// l'avviamento (multiplo degli utili), cioè impianti più cassa dell'impresa. Gli impianti contano
|
||||
/// al livello attuale: un'industria inattiva (livello 0), che non si può vendere, vale solo la sua cassa.
|
||||
/// </summary>
|
||||
public static Common.Money BookValue(World w, Industry ind) =>
|
||||
Common.Money.FromCentsRounded(PlantValue(w, ind, ind.Level) + Math.Max(0, ind.Cash.Cents));
|
||||
}
|
||||
@@ -4,16 +4,36 @@ using RailEnterprise.Core.Economy;
|
||||
|
||||
namespace RailEnterprise.Core.Simulation.Systems;
|
||||
|
||||
/// <summary>Sblocco di un livello (ADR 0018): tipo e valore (fido in centesimi, numero di squadre).</summary>
|
||||
public enum UnlockKind : byte
|
||||
{
|
||||
/// <summary>Fido massimo (valore: centesimi per la compagnia).</summary>
|
||||
LoanLimit = 0,
|
||||
/// <summary>Squadre di cantiere (valore: numero).</summary>
|
||||
Crews = 1,
|
||||
Trading = 2,
|
||||
BuyIndustry = 3,
|
||||
Ipo = 4,
|
||||
HostileTakeover = 5,
|
||||
Concessions = 6,
|
||||
}
|
||||
|
||||
public readonly record struct TierUnlock(UnlockKind Kind, long Value);
|
||||
|
||||
/// <summary>
|
||||
/// Livelli della compagnia (tiers.json): ogni mese, dopo il rating, una compagnia che soddisfa i
|
||||
/// requisiti del livello successivo (patrimonio netto, città collegate sopra una popolazione,
|
||||
/// rating) sale di un livello. Il livello non scende: gli sblocchi restano acquisiti (ADR 0011).
|
||||
/// Al passaggio la notizia elenca gli sblocchi ottenuti (ADR 0018).
|
||||
/// </summary>
|
||||
public static class Tiers
|
||||
{
|
||||
/// <summary>Definizione del livello indicato (limitato tra 1 e l'ultimo).</summary>
|
||||
public static TierDef Def(World w, int level) =>
|
||||
w.Data.Tiers.Tiers[Math.Clamp(level, 1, w.Data.Tiers.Tiers.Count) - 1];
|
||||
|
||||
/// <summary>Sblocchi del livello attuale della compagnia.</summary>
|
||||
public static TierUnlocks Unlocks(World w, Company c) =>
|
||||
w.Data.Tiers.Tiers[Math.Clamp(c.Tier, 1, w.Data.Tiers.Tiers.Count) - 1].Unlocks;
|
||||
public static TierUnlocks Unlocks(World w, Company c) => Def(w, c.Tier).Unlocks;
|
||||
|
||||
/// <summary>Promuove la compagnia se soddisfa i requisiti del livello successivo.</summary>
|
||||
public static void Evaluate(WorldContext ctx, Company c)
|
||||
@@ -24,12 +44,102 @@ public static class Tiers
|
||||
{
|
||||
var next = tiers[c.Tier];
|
||||
c.Tier = next.Level;
|
||||
c.TierReachedDay[next.Level - 1] = ctx.Day;
|
||||
Corporate.Milestone(w, c, $"diventa «{next.NameIt}»");
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Opportunity,
|
||||
$"{c.Name} diventa «{next.NameIt}» (livello {next.Level})", EntityKind.Company, c.Id.Value, c.Id));
|
||||
ctx.Emit(new GameEvent(ctx.Day, EventKind.Company, EventSeverity.Opportunity, PromotionText(w, c, next.Level),
|
||||
EntityKind.Company, c.Id.Value, c.Id));
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Testo della notizia di promozione con gli sblocchi ottenuti.</summary>
|
||||
public static string PromotionText(World w, Company c, int level)
|
||||
{
|
||||
var def = Def(w, level);
|
||||
var unlocks = NewUnlocks(w, c, level);
|
||||
string text = $"{c.Name} diventa «{def.NameIt}» (livello {def.Level})";
|
||||
return unlocks.Count == 0 ? text : $"{text}: sblocca {string.Join(", ", unlocks.Select(UnlockLabel))}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sblocchi che il livello aggiunge al precedente, nell'ordine di <see cref="UnlockKind"/>: per il
|
||||
/// primo livello la dotazione di partenza (fido e squadre). Tutto viene da tiers.json e dalle
|
||||
/// squadre di construction.json; il fido è quello della compagnia (fido iniziale × fattore).
|
||||
/// </summary>
|
||||
public static List<TierUnlock> NewUnlocks(World w, Company c, int level)
|
||||
{
|
||||
var def = Def(w, level);
|
||||
var u = def.Unlocks;
|
||||
var prev = def.Level > 1 ? Def(w, def.Level - 1) : null;
|
||||
var p = prev?.Unlocks;
|
||||
var list = new List<TierUnlock>();
|
||||
if (p is null || u.MaxLoanFactor > p.MaxLoanFactor) list.Add(new TierUnlock(UnlockKind.LoanLimit, LoanLimit(c, def).Cents));
|
||||
int crews = Crews(w, def.Level);
|
||||
if (prev is null || crews > Crews(w, prev.Level)) list.Add(new TierUnlock(UnlockKind.Crews, crews));
|
||||
if (u.Trading && p?.Trading != true) list.Add(new TierUnlock(UnlockKind.Trading, 0));
|
||||
if (u.BuyIndustry && p?.BuyIndustry != true) list.Add(new TierUnlock(UnlockKind.BuyIndustry, 0));
|
||||
if (u.Ipo && p?.Ipo != true) list.Add(new TierUnlock(UnlockKind.Ipo, 0));
|
||||
if (u.HostileTakeover && p?.HostileTakeover != true) list.Add(new TierUnlock(UnlockKind.HostileTakeover, 0));
|
||||
// le concessioni non si annunciano finché il comando non esiste (F7): il livello le sblocca, ma non funzionerebbero
|
||||
if (ConcessionsAvailable && u.Concessions && p?.Concessions != true) list.Add(new TierUnlock(UnlockKind.Concessions, 0));
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Vero quando le concessioni (BuyConcession) saranno implementate: fino alla F7 il comando risponde
|
||||
/// «non ancora disponibili», quindi non compaiono tra gli sblocchi né nelle notizie.
|
||||
/// </summary>
|
||||
public static bool ConcessionsAvailable => false;
|
||||
|
||||
/// <summary>
|
||||
/// Rifiuto delle concessioni finché non sono implementate: prima del livello che le sblocca
|
||||
/// (TierLocked) dice anche quale livello servirà.
|
||||
/// </summary>
|
||||
public static string ConcessionsUnavailableText(World w)
|
||||
{
|
||||
const string text = "Le concessioni non sono ancora disponibili";
|
||||
var tier = FirstUnlocking(w, u => u.Concessions);
|
||||
return tier is null ? text : $"{text}: si sbloccheranno al livello {tier.Level}, «{tier.NameIt}»";
|
||||
}
|
||||
|
||||
/// <summary>Fido massimo della compagnia a un livello: fido iniziale × fattore del livello.</summary>
|
||||
public static Money LoanLimit(Company c, TierDef def) => c.BaseCredit * def.Unlocks.MaxLoanFactor;
|
||||
|
||||
/// <summary>Squadre di cantiere a un livello (construction.json, le stesse di ConstructionSystem).</summary>
|
||||
public static int Crews(World w, int level)
|
||||
{
|
||||
var byTier = w.Data.Construction.Crews.CrewsByTier;
|
||||
return byTier[Math.Clamp(level, 1, byTier.Length) - 1];
|
||||
}
|
||||
|
||||
/// <summary>Etichetta italiana di uno sblocco (per le notizie del motore).</summary>
|
||||
public static string UnlockLabel(TierUnlock u) => u.Kind switch
|
||||
{
|
||||
UnlockKind.LoanLimit => $"fido fino a {new Money(u.Value).ToString("short")}",
|
||||
UnlockKind.Crews => $"{u.Value} squadre di cantiere",
|
||||
UnlockKind.Trading => "compravendita in proprio",
|
||||
UnlockKind.BuyIndustry => "acquisto di industrie",
|
||||
UnlockKind.Ipo => "quotazione in borsa",
|
||||
UnlockKind.HostileTakeover => "scalate ostili",
|
||||
UnlockKind.Concessions => "concessioni",
|
||||
_ => u.Kind.ToString(),
|
||||
};
|
||||
|
||||
/// <summary>Primo livello di tiers.json che ha lo sblocco indicato (null se nessuno).</summary>
|
||||
public static TierDef? FirstUnlocking(World w, Func<TierUnlocks, bool> unlock) =>
|
||||
w.Data.Tiers.Tiers.FirstOrDefault(t => unlock(t.Unlocks));
|
||||
|
||||
/// <summary>
|
||||
/// Testo di rifiuto per una funzione bloccata dal livello: «{funzione} si sblocca al livello N,
|
||||
/// «nome»» dai dati, oppure «{funzione} non è disponibile» se nessun livello la sblocca.
|
||||
/// </summary>
|
||||
public static string LockedText(World w, string feature, Func<TierUnlocks, bool> unlock, bool plural = false)
|
||||
{
|
||||
var tier = FirstUnlocking(w, unlock);
|
||||
return tier is null
|
||||
? $"{feature} {(plural ? "non sono disponibili" : "non è disponibile")}"
|
||||
: $"{feature} {(plural ? "si sbloccano" : "si sblocca")} al livello {tier.Level}, «{tier.NameIt}»";
|
||||
}
|
||||
|
||||
/// <summary>Requisiti di un livello soddisfatti dalla compagnia.</summary>
|
||||
public static bool Meets(World w, Company c, TierRequirements req) =>
|
||||
c.NetWorth.Cents >= req.NetWorth
|
||||
|
||||
@@ -230,10 +230,7 @@ public static class TradingCommandHandlers
|
||||
s = null!;
|
||||
if (needsUnlock && !Tiers.Unlocks(w, company).Trading)
|
||||
{
|
||||
var tier = w.Data.Tiers.Tiers.FirstOrDefault(t => t.Unlocks.Trading);
|
||||
error = (CommandError.TierLocked, tier is null
|
||||
? "La compravendita in proprio non è disponibile"
|
||||
: $"La compravendita in proprio si sblocca al livello «{tier.NameIt}»");
|
||||
error = (CommandError.TierLocked, Tiers.LockedText(w, "La compravendita in proprio", u => u.Trading));
|
||||
return false;
|
||||
}
|
||||
if (!TryOwnStation(w, company, station, out s, out error)) return false;
|
||||
|
||||
@@ -50,6 +50,9 @@ public sealed class ClientWorld(GameData data)
|
||||
/// <summary>Quadro del mercato globale (F6), su richiesta.</summary>
|
||||
public MarketReport? Market { get; private set; }
|
||||
|
||||
/// <summary>Quadro della scalata (F6), su richiesta: lo usano il pannello «La tua scalata» e la barra superiore.</summary>
|
||||
public ClimbReport? Climb { get; private set; }
|
||||
|
||||
/// <summary>Contatore dei listini ricevuti (per aggiornare il pannello della borsa).</summary>
|
||||
public int TapeVersion { get; private set; }
|
||||
|
||||
@@ -134,6 +137,10 @@ public sealed class ClientWorld(GameData data)
|
||||
Market = m;
|
||||
DetailVersion++;
|
||||
return true;
|
||||
case ClimbReport m:
|
||||
Climb = m;
|
||||
DetailVersion++;
|
||||
return true;
|
||||
case MaintenanceAlert m:
|
||||
Alerts.Insert(0, m);
|
||||
if (Alerts.Count > AlertCapacity) Alerts.RemoveAt(Alerts.Count - 1);
|
||||
@@ -154,6 +161,7 @@ public sealed class ClientWorld(GameData data)
|
||||
IndustryCards.Clear();
|
||||
Chronicle = null;
|
||||
Market = null;
|
||||
Climb = null;
|
||||
Alerts.Clear();
|
||||
Summary = m.Summary;
|
||||
SessionId = m.SessionId;
|
||||
|
||||
@@ -43,6 +43,8 @@ public enum MessageId : ushort
|
||||
Notification = 131,
|
||||
Newspaper = 132,
|
||||
SaveList = 133,
|
||||
/// <summary>Quadro della scalata: livelli, sblocchi, requisiti, stato patrimoniale (F6).</summary>
|
||||
ClimbReport = 134,
|
||||
}
|
||||
|
||||
/// <summary>Messaggio del protocollo: si serializza a mano, campo per campo.</summary>
|
||||
|
||||
@@ -239,6 +239,8 @@ public enum DetailKind : byte
|
||||
Chronicle = 6,
|
||||
/// <summary>Quadro del mercato globale (risposta MarketReport, F6; Id ignorato).</summary>
|
||||
Market = 7,
|
||||
/// <summary>Quadro della scalata (risposta ClimbReport, F6; Id ignorato).</summary>
|
||||
Climb = 8,
|
||||
}
|
||||
|
||||
/// <summary>Chiede al server un dettaglio che non viaggia con le entità (aggiunto in F4).</summary>
|
||||
|
||||
@@ -0,0 +1,276 @@
|
||||
using RailEnterprise.Core.Common;
|
||||
|
||||
namespace RailEnterprise.Protocol.Messages;
|
||||
|
||||
// Messaggi della fase F6: pannello «La tua scalata» (immagine di riferimento 08). Il quadro arriva su
|
||||
// richiesta (RequestDetail con DetailKind.Climb) ed è calcolato dal server con ClimbOutlook (ADR 0018):
|
||||
// il client lo mostra com'è, senza logica di gioco.
|
||||
|
||||
/// <summary>Sblocco di un livello: Kind come UnlockKind del Core (0 fido, 1 squadre, 2 compravendita, 3 acquisto di industrie, 4 quotazione, 5 scalate ostili, 6 concessioni).</summary>
|
||||
public sealed class UnlockInfo
|
||||
{
|
||||
public const byte LoanLimit = 0, Crews = 1, Trading = 2, BuyIndustry = 3, Ipo = 4, HostileTakeover = 5, Concessions = 6;
|
||||
|
||||
public byte Kind { get; init; }
|
||||
/// <summary>Fido in centesimi (LoanLimit) o numero di squadre (Crews); 0 per gli altri.</summary>
|
||||
public long Value { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.U8(Kind); w.I64(Value);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static UnlockInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new UnlockInfo { Kind = r.U8(), Value = r.I64() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Livello di tiers.json visto dalla compagnia: requisiti, raggiunto e quando, sblocchi che aggiunge.</summary>
|
||||
public sealed class TierInfo
|
||||
{
|
||||
public byte Level { get; init; }
|
||||
public string NameIt { get; init; } = "";
|
||||
public string NameEn { get; init; } = "";
|
||||
public Money NetWorthRequired { get; init; }
|
||||
public int TownsRequired { get; init; }
|
||||
public int TownPopulation { get; init; }
|
||||
public string RatingRequired { get; init; } = "";
|
||||
public bool Reached { get; init; }
|
||||
/// <summary>Giorno in cui è stato raggiunto (fondazione per il livello 1; −1 se non raggiunto o sconosciuto).</summary>
|
||||
public long ReachedDay { get; init; } = -1;
|
||||
public List<UnlockInfo> Unlocks { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.U8(Level); w.String(NameIt); w.String(NameEn); w.Money(NetWorthRequired); w.I32(TownsRequired); w.I32(TownPopulation);
|
||||
w.String(RatingRequired); w.Bool(Reached); w.I64(ReachedDay);
|
||||
w.Count(Unlocks.Count);
|
||||
foreach (var u in Unlocks) u.Write(ref w);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static TierInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new TierInfo
|
||||
{
|
||||
Level = r.U8(), NameIt = r.String(), NameEn = r.String(), NetWorthRequired = r.Money(), TownsRequired = r.I32(), TownPopulation = r.I32(),
|
||||
RatingRequired = r.String(), Reached = r.Bool(), ReachedDay = r.I64(),
|
||||
};
|
||||
for (int n = r.Count(), i = 0; i < n; i++) m.Unlocks.Add(UnlockInfo.Read(ref r));
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Voce dello stato patrimoniale o del conto economico: Kind secondo la tabella del messaggio, valore con segno.</summary>
|
||||
public sealed class AmountInfo
|
||||
{
|
||||
public byte Kind { get; init; }
|
||||
public Money Value { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.U8(Kind); w.Money(Value);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static AmountInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new AmountInfo { Kind = r.U8(), Value = r.Money() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Prestito in corso: residuo, tasso annuo, mesi restanti.</summary>
|
||||
public sealed class LoanInfo
|
||||
{
|
||||
public int Loan { get; init; }
|
||||
public Money Remaining { get; init; }
|
||||
public float AnnualRate { get; init; }
|
||||
public int MonthsLeft { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I32(Loan); w.Money(Remaining); w.F32(AnnualRate); w.I32(MonthsLeft);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static LoanInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new LoanInfo { Loan = r.I32(), Remaining = r.Money(), AnnualRate = r.F32(), MonthsLeft = r.I32() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Patrimonio netto a un giorno della partita.</summary>
|
||||
public sealed class NetWorthPointInfo
|
||||
{
|
||||
public long Day { get; init; }
|
||||
public Money Value { get; init; }
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I64(Day); w.Money(Value);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static NetWorthPointInfo Read(ref SpanReader r)
|
||||
{
|
||||
var m = new NetWorthPointInfo { Day = r.I64(), Value = r.Money() };
|
||||
r.Flags();
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Quadro della scalata per la compagnia della sessione (F6, ADR 0018): livelli con requisiti e
|
||||
/// sblocchi, requisiti del prossimo livello con l'avanzamento, stato patrimoniale per voce (somma al
|
||||
/// patrimonio netto del motore), conto economico, prestiti e storico del patrimonio netto.
|
||||
/// </summary>
|
||||
public sealed class ClimbReport : IMessage
|
||||
{
|
||||
/// <summary>Voci degli attivi (Assets[].Kind), come AssetCategory del Core.</summary>
|
||||
public const byte AssetTrack = 0, AssetStations = 1, AssetVehicles = 2, AssetIndustries = 3, AssetGoods = 4;
|
||||
/// <summary>Righe del conto economico (Income[].Kind), come IncomeLineKind del Core.</summary>
|
||||
public const byte IncomeFares = 0, IncomeOther = 1, IncomeOperating = 2, IncomeMaintenance = 3, IncomeInterest = 4;
|
||||
|
||||
public MessageId Id => MessageId.ClimbReport;
|
||||
public long Day { get; init; }
|
||||
public int Company { get; init; }
|
||||
public long FoundedDay { get; init; }
|
||||
public Money InitialCapital { get; init; }
|
||||
public byte Tier { get; init; }
|
||||
/// <summary>Livello successivo (0 all'ultimo livello: i requisiti che seguono sono vuoti).</summary>
|
||||
public byte NextTier { get; init; }
|
||||
public List<TierInfo> Tiers { get; init; } = [];
|
||||
|
||||
/// <summary>Requisiti del livello successivo: valore attuale, soglia, frazione (0–1) e se è soddisfatto.</summary>
|
||||
public Money NetWorth { get; init; }
|
||||
public Money NetWorthRequired { get; init; }
|
||||
public float NetWorthFraction { get; init; }
|
||||
public bool NetWorthMet { get; init; }
|
||||
public int Towns { get; init; }
|
||||
public int TownsRequired { get; init; }
|
||||
public int TownPopulation { get; init; }
|
||||
public float TownsFraction { get; init; }
|
||||
public bool TownsMet { get; init; }
|
||||
public string Rating { get; init; } = "";
|
||||
public string RatingRequired { get; init; } = "";
|
||||
public float RatingFraction { get; init; }
|
||||
public bool RatingMet { get; init; }
|
||||
/// <summary>Avanzamento complessivo verso il livello successivo (media delle tre frazioni).</summary>
|
||||
public float Progress { get; init; }
|
||||
|
||||
/// <summary>Stato patrimoniale: attivi per voce, partecipazioni, cassa; prestiti (tasso medio), scoperto.</summary>
|
||||
public List<AmountInfo> Assets { get; init; } = [];
|
||||
public Money Portfolio { get; init; }
|
||||
public Money Cash { get; init; }
|
||||
public Money TotalAssets { get; init; }
|
||||
public Money Loans { get; init; }
|
||||
public float LoansRate { get; init; }
|
||||
public Money Overdraft { get; init; }
|
||||
public Money TotalLiabilities { get; init; }
|
||||
public Money BalanceNetWorth { get; init; }
|
||||
|
||||
/// <summary>Conto economico dell'anno indicato (Partial se è l'anno in corso fino a oggi).</summary>
|
||||
public int IncomeYear { get; init; }
|
||||
public bool IncomePartial { get; init; }
|
||||
public List<AmountInfo> Income { get; init; } = [];
|
||||
public Money Profit { get; init; }
|
||||
|
||||
public List<LoanInfo> LoanList { get; init; } = [];
|
||||
public Money MaxLoan { get; init; }
|
||||
public Money LoanAvailable { get; init; }
|
||||
public float NewLoanRate { get; init; }
|
||||
public bool LoansAllowed { get; init; } = true;
|
||||
|
||||
public List<NetWorthPointInfo> History { get; init; } = [];
|
||||
|
||||
public void Write(ref SpanWriter w)
|
||||
{
|
||||
w.I64(Day); w.I32(Company); w.I64(FoundedDay); w.Money(InitialCapital); w.U8(Tier); w.U8(NextTier);
|
||||
w.Count(Tiers.Count);
|
||||
foreach (var t in Tiers) t.Write(ref w);
|
||||
w.Money(NetWorth); w.Money(NetWorthRequired); w.F32(NetWorthFraction); w.Bool(NetWorthMet);
|
||||
w.I32(Towns); w.I32(TownsRequired); w.I32(TownPopulation); w.F32(TownsFraction); w.Bool(TownsMet);
|
||||
w.String(Rating); w.String(RatingRequired); w.F32(RatingFraction); w.Bool(RatingMet); w.F32(Progress);
|
||||
w.Count(Assets.Count);
|
||||
foreach (var a in Assets) a.Write(ref w);
|
||||
w.Money(Portfolio); w.Money(Cash); w.Money(TotalAssets); w.Money(Loans); w.F32(LoansRate); w.Money(Overdraft);
|
||||
w.Money(TotalLiabilities); w.Money(BalanceNetWorth);
|
||||
w.I32(IncomeYear); w.Bool(IncomePartial);
|
||||
w.Count(Income.Count);
|
||||
foreach (var i in Income) i.Write(ref w);
|
||||
w.Money(Profit);
|
||||
w.Count(LoanList.Count);
|
||||
foreach (var l in LoanList) l.Write(ref w);
|
||||
w.Money(MaxLoan); w.Money(LoanAvailable); w.F32(NewLoanRate); w.Bool(LoansAllowed);
|
||||
w.Count(History.Count);
|
||||
foreach (var p in History) p.Write(ref w);
|
||||
w.Flags(0);
|
||||
}
|
||||
|
||||
public static ClimbReport Read(ref SpanReader r)
|
||||
{
|
||||
long day = r.I64();
|
||||
int company = r.I32();
|
||||
long founded = r.I64();
|
||||
var capital = r.Money();
|
||||
byte tier = r.U8(), next = r.U8();
|
||||
var tiers = new List<TierInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) tiers.Add(TierInfo.Read(ref r));
|
||||
var worth = r.Money();
|
||||
var worthRequired = r.Money();
|
||||
float worthFraction = r.F32();
|
||||
bool worthMet = r.Bool();
|
||||
int towns = r.I32(), townsRequired = r.I32(), townPopulation = r.I32();
|
||||
float townsFraction = r.F32();
|
||||
bool townsMet = r.Bool();
|
||||
string rating = r.String(), ratingRequired = r.String();
|
||||
float ratingFraction = r.F32();
|
||||
bool ratingMet = r.Bool();
|
||||
float progress = r.F32();
|
||||
var assets = new List<AmountInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) assets.Add(AmountInfo.Read(ref r));
|
||||
var portfolio = r.Money();
|
||||
var cash = r.Money();
|
||||
var totalAssets = r.Money();
|
||||
var loans = r.Money();
|
||||
float loansRate = r.F32();
|
||||
var overdraft = r.Money();
|
||||
var totalLiabilities = r.Money();
|
||||
var balanceWorth = r.Money();
|
||||
int incomeYear = r.I32();
|
||||
bool partial = r.Bool();
|
||||
var income = new List<AmountInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) income.Add(AmountInfo.Read(ref r));
|
||||
var profit = r.Money();
|
||||
var loanList = new List<LoanInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) loanList.Add(LoanInfo.Read(ref r));
|
||||
var maxLoan = r.Money();
|
||||
var available = r.Money();
|
||||
float newRate = r.F32();
|
||||
bool allowed = r.Bool();
|
||||
var history = new List<NetWorthPointInfo>();
|
||||
for (int n = r.Count(), i = 0; i < n; i++) history.Add(NetWorthPointInfo.Read(ref r));
|
||||
r.Flags();
|
||||
return new ClimbReport
|
||||
{
|
||||
Day = day, Company = company, FoundedDay = founded, InitialCapital = capital, Tier = tier, NextTier = next, Tiers = tiers,
|
||||
NetWorth = worth, NetWorthRequired = worthRequired, NetWorthFraction = worthFraction, NetWorthMet = worthMet,
|
||||
Towns = towns, TownsRequired = townsRequired, TownPopulation = townPopulation, TownsFraction = townsFraction, TownsMet = townsMet,
|
||||
Rating = rating, RatingRequired = ratingRequired, RatingFraction = ratingFraction, RatingMet = ratingMet, Progress = progress,
|
||||
Assets = assets, Portfolio = portfolio, Cash = cash, TotalAssets = totalAssets, Loans = loans, LoansRate = loansRate,
|
||||
Overdraft = overdraft, TotalLiabilities = totalLiabilities, BalanceNetWorth = balanceWorth,
|
||||
IncomeYear = incomeYear, IncomePartial = partial, Income = income, Profit = profit,
|
||||
LoanList = loanList, MaxLoan = maxLoan, LoanAvailable = available, NewLoanRate = newRate, LoansAllowed = allowed,
|
||||
History = history,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -32,6 +32,7 @@ public static class MessageCodec
|
||||
MessageId.IndustryCard => IndustryCard.Read(ref r),
|
||||
MessageId.Chronicle => Chronicle.Read(ref r),
|
||||
MessageId.MarketReport => MarketReport.Read(ref r),
|
||||
MessageId.ClimbReport => ClimbReport.Read(ref r),
|
||||
MessageId.MarketTape => MarketTape.Read(ref r),
|
||||
MessageId.CommandResult => CommandResultMessage.Read(ref r),
|
||||
MessageId.Notification => Notification.Read(ref r),
|
||||
|
||||
@@ -661,6 +661,9 @@ public sealed class GameHost : IDisposable
|
||||
case DetailKind.Market:
|
||||
s.Send(Projection.Market(w, s.Company));
|
||||
break;
|
||||
case DetailKind.Climb:
|
||||
if (s.Company.IsValid && s.Company.Value < w.Companies.Count) s.Send(Projection.Climb(w, s.Company));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -553,6 +553,42 @@ public static class Projection
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Quadro della scalata per la compagnia della sessione (ClimbOutlook, ADR 0018).</summary>
|
||||
public static ClimbReport Climb(World w, CompanyId company)
|
||||
{
|
||||
var report = ClimbOutlook.Build(w, company);
|
||||
var next = report.Next;
|
||||
var balance = report.Balance;
|
||||
var income = report.Income;
|
||||
return new ClimbReport
|
||||
{
|
||||
Day = report.Day, Company = report.Company.Value, FoundedDay = report.FoundedDay, InitialCapital = report.InitialCapital,
|
||||
Tier = (byte)report.Tier, NextTier = (byte)report.NextTier,
|
||||
Tiers = report.Tiers.Select(t => new TierInfo
|
||||
{
|
||||
Level = (byte)t.Level, NameIt = t.NameIt, NameEn = t.NameEn, NetWorthRequired = new Money(t.Requirements.NetWorth),
|
||||
TownsRequired = t.Requirements.ConnectedTownsOver.Count, TownPopulation = t.Requirements.ConnectedTownsOver.Population,
|
||||
RatingRequired = t.Requirements.CreditRating.ToString(), Reached = t.Reached, ReachedDay = t.ReachedDay,
|
||||
Unlocks = t.Unlocks.Select(u => new UnlockInfo { Kind = (byte)u.Kind, Value = u.Value }).ToList(),
|
||||
}).ToList(),
|
||||
NetWorth = next?.NetWorth ?? w.Company(company).NetWorth, NetWorthRequired = next?.NetWorthRequired ?? Money.Zero,
|
||||
NetWorthFraction = (float)(next?.NetWorthFraction ?? 1), NetWorthMet = next?.NetWorthMet ?? true,
|
||||
Towns = next?.Towns ?? 0, TownsRequired = next?.TownsRequired ?? 0, TownPopulation = next?.TownPopulation ?? 0,
|
||||
TownsFraction = (float)(next?.TownsFraction ?? 1), TownsMet = next?.TownsMet ?? true,
|
||||
Rating = w.Company(company).Rating.ToString(), RatingRequired = next?.RatingRequired.ToString() ?? "",
|
||||
RatingFraction = (float)(next?.RatingFraction ?? 1), RatingMet = next?.RatingMet ?? true, Progress = (float)(next?.Progress ?? 1),
|
||||
Assets = balance.Assets.Select(a => new AmountInfo { Kind = (byte)a.Category, Value = a.Value }).ToList(),
|
||||
Portfolio = balance.Portfolio, Cash = balance.Cash, TotalAssets = balance.TotalAssets, Loans = balance.Loans,
|
||||
LoansRate = (float)balance.LoansRate, Overdraft = balance.Overdraft, TotalLiabilities = balance.TotalLiabilities,
|
||||
BalanceNetWorth = balance.NetWorth,
|
||||
IncomeYear = income.Year, IncomePartial = income.Partial,
|
||||
Income = income.Lines.Select(l => new AmountInfo { Kind = (byte)l.Kind, Value = l.Value }).ToList(), Profit = income.Profit,
|
||||
LoanList = report.Loans.Select(l => new LoanInfo { Loan = l.Id.Value, Remaining = l.Remaining, AnnualRate = (float)l.AnnualRate, MonthsLeft = l.MonthsLeft }).ToList(),
|
||||
MaxLoan = report.MaxLoan, LoanAvailable = report.LoanAvailable, NewLoanRate = (float)report.NewLoanRate, LoansAllowed = report.LoansAllowed,
|
||||
History = report.History.Select(p => new NetWorthPointInfo { Day = p.Day, Value = p.Value }).ToList(),
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Evento del mondo in corso → record del protocollo (ADR 0017).</summary>
|
||||
public static WorldEventInfo WorldEvent(ActiveWorldEvent e) => new()
|
||||
{
|
||||
|
||||
@@ -130,6 +130,20 @@ public static class DataTests
|
||||
Assert.True(errors.Any(e => e.Contains("failure.*Share", StringComparison.Ordinal)));
|
||||
}
|
||||
|
||||
[Test(Description = "Gli sblocchi non diminuiscono salendo di livello: fido e funzioni restano acquisiti (ADR 0011, 0018)")]
|
||||
public static void SemanticRejectsShrinkingUnlocks()
|
||||
{
|
||||
var errors = LoadErrors(files =>
|
||||
{
|
||||
var root = JsonNode.Parse(files["tiers.json"])!;
|
||||
root["tiers"]![4]!["unlocks"]!["ipo"] = false;
|
||||
root["tiers"]![2]!["unlocks"]!["maxLoanFactor"] = 1.0;
|
||||
files["tiers.json"] = root.ToJsonString();
|
||||
});
|
||||
Assert.True(errors.Any(e => e.Contains("unlocks.ipo", StringComparison.Ordinal)), string.Join("; ", errors));
|
||||
Assert.True(errors.Any(e => e.Contains("unlocks.maxLoanFactor", StringComparison.Ordinal)), string.Join("; ", errors));
|
||||
}
|
||||
|
||||
private static IReadOnlyList<string> LoadErrors(Action<Dictionary<string, string>> mutate)
|
||||
{
|
||||
var files = MemoryDataSource.Snapshot(TestData.Source);
|
||||
|
||||
@@ -0,0 +1,445 @@
|
||||
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]);
|
||||
}
|
||||
}
|
||||
@@ -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