F6: tutorial, correzioni della revisione
CI / Build e test (pull_request) Successful in 1m29s
CI / Immagine Docker (pull_request) Successful in 30s

Unisce origin/main (audio, ere e obsolescenza, scheda dell'industria e
schermata di connessione) e corregge i rilievi della revisione del
tutorial (ADR 0023 aggiornato).

- Chiave dell'avanzamento senza l'impronta del terreno, che il server
  ricalcola e che cambia giocando (città, industrie): origine della
  partita, seme, lato, anno d'inizio, regione e compagnia. Un tutorial
  ripreso dopo un anno di gioco ritrova la sua voce.
- «Tutorial» apre una partita locale di prova sempre nuova in
  user://tutorial-server invece di riprendere l'autosalvataggio del
  giocatore e rifare il tutorial lì dentro; con salvataggi locali già
  presenti la casella «Mostra il tutorial» parte spenta. Casella e
  pulsante passano nella nuova ConnectScreen (MenuScreen non c'è più).
- La casella spuntata vale anche su una voce chiusa o completata (stesso
  seme di una partita vecchia).
- Contorno ritagliato dai contenitori a scorrimento, con l'elemento
  portato in vista; del tutto nascosto si usa il ripiego.
- Pulsanti del riquadro senza fuoco: Invio e spazio restano alla
  partita (Costruisci, pausa) e non saltano il passo.
- La base di «increase» è presa al completamento del passo precedente e
  gli esiti dei comandi si valutano subito: un binario costruito appena
  dopo conta per il passo nuovo.
- Velocità contata solo dalle richieste di questo client.
- Copione mancante o non valido segnalato nella partita; validazione
  dei null ammessi dal JSON.
- Test: chiave stabile con impronta diversa, base al completamento,
  piano con la casella, null nel copione. 228 test (208 senza i lenti).

Refs #45.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-08 14:51:31 +01:00
commit 64209afd5f
75 files changed
+7612 -571

No files matched your search

@@ -1,23 +1,102 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Client.Panels;
using RailEnterprise.Client.Tutorial;
using RailEnterprise.Core.Data;
using RailEnterprise.Core.Simulation;
using RailEnterprise.Protocol;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Screens;
/// <summary>
/// Collegamento a un server (immagine 09 non fornita: palette e componenti dell'immagine 05).
/// Ricorda indirizzo e token in user://settings.cfg.
/// Schermata iniziale e di connessione (immagine di riferimento 09): a sinistra la mappa decorativa
/// con il titolo, a destra «Dove gira il motore di gioco?» con le due strade (server locale figlio
/// del gioco o server in rete), indirizzo e token, lo stato del server (versione e protocollo,
/// sistema, tempo di attività, tick al secondo, latenza, client collegati), le partite salvate sul
/// server e i pulsanti per riprendere o iniziare. All'apertura la schermata avvia il server locale o
/// verifica il server in rete ricordato, con una sessione di prova che legge lo stato e l'elenco dei
/// salvataggi; «Connetti e riprendi» la passa alla partita (e se non c'è ancora la apre). Nessuna
/// logica di gioco: carica, nuova partita ed elenco sono richieste al server (Load, NewGame,
/// ListSaves). Caricare o creare una partita sostituisce il mondo per tutti: si chiede conferma. Sotto i
/// pulsanti la casella «Mostra il tutorial» (attiva alla prima partita) vale per la partita che si apre, e
/// «Tutorial» apre una partita locale di prova sempre nuova, separata da quella del giocatore (ADR 0023).
/// </summary>
public partial class ConnectScreen : Control
{
private const string SettingsPath = "user://settings.cfg";
private readonly LineEdit _address = new() { PlaceholderText = "unraid.lan:7400" };
private readonly LineEdit _token = new() { Secret = true, PlaceholderText = T("Token del server") };
private readonly Label _status = UiTheme.Text("", 14, Palette.TextSecondary);
private readonly Button _connect = UiTheme.Primary(T("Collegati"));
private const double SavesRefreshS = 5;
private const double WelcomeTimeoutS = 30;
/// <summary>Metadato della riga «Partita in corso» nell'elenco dei salvataggi.</summary>
private const string CurrentGame = "";
private readonly GameData _data;
private readonly bool _remember, _autoStart;
private GameSession? _handover;
private readonly LineEdit _address = new() { PlaceholderText = "unraid.lan:7400", SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly LineEdit _token = new() { Secret = true, PlaceholderText = T("Token del server"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly CheckBox _rememberBox = new() { Text = T("Ricorda questo server"), ButtonPressed = true };
private readonly Button _probe = new() { Text = T("Verifica connessione"), CustomMinimumSize = new Vector2(0, 40) };
private readonly VBoxContainer _remoteFields = new();
private readonly Button _localCard = new() { ToggleMode = true, CustomMinimumSize = new Vector2(0, 112), SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly Button _remoteCard = new() { ToggleMode = true, CustomMinimumSize = new Vector2(0, 112), SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly ColorRect _dot = new() { CustomMinimumSize = new Vector2(12, 12), SizeFlagsVertical = SizeFlags.ShrinkCenter };
private readonly Label _stateTitle = UiTheme.Text("", 16, bold: true);
/// <summary>Stato del server in tre colonne per due righe, didascalia sopra il valore (immagine 09).</summary>
private readonly GridContainer _stateGrid = new() { Columns = 3 };
private readonly List<(Label Caption, Label Value)> _stateCells = [];
/// <summary>Partite salvate in tre colonne: nome, data di gioco, quanto tempo fa.</summary>
private readonly Tree _saves = new()
{
Columns = 3, HideRoot = true, SelectMode = Tree.SelectModeEnum.Row, CustomMinimumSize = new Vector2(0, 150), SizeFlagsVertical = SizeFlags.ExpandFill,
};
private readonly Button _resume = UiTheme.Primary(T("Connetti e riprendi"));
private readonly Button _newGame = new() { Text = T("Nuova partita sul server") };
private readonly CheckBox _showTutorial = new() { Text = T("Mostra il tutorial") };
private readonly Button _tutorial = new() { Text = T("Tutorial") };
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
private readonly ConfirmationDialog _confirm = new() { Title = T("Sostituire la partita?"), DialogAutowrap = true, MinSize = new Vector2I(520, 0) };
private Action? _onConfirm;
private GameSession? _session;
private bool _busy, _local, _closed, _resumeAfterConnect;
private double _sinceSaves = double.MaxValue;
private SaveList? _shownSaves;
/// <summary>Riga scelta nell'elenco, per id del salvataggio (CurrentGame per la partita in corso): l'elenco si riordina a ogni aggiornamento.</summary>
private string _selectedSave = CurrentGame;
private Action<IMessage>? _awaitingWelcome;
private double _waiting;
/// <summary>Stato del server mostrato e istante in cui è arrivato: il tempo di attività avanza da lì.</summary>
private ServerInfo? _infoSeen;
private double _infoAt;
public event Action<Uri, string, string>? ConnectRequested;
public event Action? Back;
/// <summary>La sessione di prova diventa la partita: la schermata non la chiude più.</summary>
public event Action<GameSession>? PlayRequested;
public event Action<string>? LanguageChanged;
/// <summary>Apre il pannello delle impostazioni audio.</summary>
public event Action? AudioRequested;
/// <summary>Pulsante «Tutorial»: Main apre la partita di prova del tutorial.</summary>
public event Action? TutorialRequested;
/// <summary>Casella «Mostra il tutorial» per la partita che si apre.</summary>
public bool ShowTutorial => _showTutorial.ButtonPressed;
/// <summary>Origine della partita per la voce del tutorial: il server locale o l'indirizzo del server in rete.</summary>
public string GameScope => _local ? "local" : "remote_" + _address.Text.Trim();
/// <param name="remember">Falso per l'anteprima del collaudo: non legge né scrive le impostazioni.</param>
/// <param name="autoStart">Avvia subito il server locale o verifica il server ricordato (falso nel collaudo).</param>
/// <param name="handover">Sessione di prova di una schermata precedente (cambio di lingua): la si riprende così com'è.</param>
public ConnectScreen(GameData data, bool remember = true, bool autoStart = true, GameSession? handover = null)
{
_data = data;
_remember = remember;
_autoStart = autoStart;
_handover = handover;
}
/// <summary>Stato e salvataggi sono arrivati dal server (serve al collaudo).</summary>
public bool Loaded => _session?.World.Server is not null && _shownSaves is not null;
public override void _Ready()
{
@@ -27,67 +106,710 @@ public partial class ConnectScreen : Control
var bg = new ColorRect { Color = Palette.AppBackground };
bg.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(bg);
var center = new CenterContainer();
center.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(center);
var panel = new PanelContainer { CustomMinimumSize = new Vector2(480, 0) };
center.AddChild(panel);
var col = new VBoxContainer();
col.AddThemeConstantOverride("separation", 12);
panel.AddChild(col);
col.AddChild(UiTheme.TitleLabel(T("Collegati a un server"), 40));
col.AddChild(UiTheme.Text(T("Indirizzo (host:porta)"), 13, Palette.TextSecondary));
col.AddChild(_address);
col.AddChild(UiTheme.Text(T("Token"), 13, Palette.TextSecondary));
col.AddChild(_token);
var row = new HBoxContainer();
row.AddThemeConstantOverride("separation", 10);
_connect.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_connect.Pressed += Submit;
row.AddChild(_connect);
var back = new Button { Text = T("Indietro") };
back.Pressed += () => Back?.Invoke();
row.AddChild(back);
col.AddChild(row);
var split = new HBoxContainer();
split.SetAnchorsPreset(LayoutPreset.FullRect);
split.AddThemeConstantOverride("separation", 0);
AddChild(split);
// sinistra: mappa decorativa con il titolo
var left = new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = 1.1f, ClipContents = true };
var backdrop = new ConnectBackdrop();
backdrop.SetAnchorsPreset(LayoutPreset.FullRect);
left.AddChild(backdrop);
// titolo in basso a sinistra, sopra il velo della mappa
var brand = new VBoxContainer { Alignment = BoxContainer.AlignmentMode.End };
brand.AnchorLeft = 0;
brand.AnchorRight = 1;
brand.AnchorTop = 1;
brand.AnchorBottom = 1;
brand.OffsetLeft = 56;
brand.OffsetRight = -56;
brand.OffsetTop = -280;
brand.OffsetBottom = -56;
brand.AddThemeConstantOverride("separation", 6);
brand.AddChild(UiTheme.TitleLabel("RAIL ENTERPRISE", 76, Palette.AmberLight));
brand.AddChild(UiTheme.Text(T("Gestionale ferroviario dall'alto"), 20, Palette.Text));
brand.AddChild(UiTheme.Text($"{T("Versione del gioco")} {ClientVersion}", 13, Palette.TextSecondary));
left.AddChild(brand);
split.AddChild(left);
// destra: dove gira il motore
var right = new PanelContainer { SizeFlagsHorizontal = SizeFlags.ExpandFill, SizeFlagsStretchRatio = 0.9f };
right.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 40));
split.AddChild(right);
var scroll = new ScrollContainer { HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled };
right.AddChild(scroll);
var col = PanelKit.Column(14);
col.SizeFlagsHorizontal = SizeFlags.ExpandFill;
col.SizeFlagsVertical = SizeFlags.ExpandFill;
scroll.AddChild(col);
col.AddChild(UiTheme.TitleLabel(T("Dove gira il motore di gioco?"), 38));
var lead = UiTheme.Text(T("Il mondo vive sempre in un server: sul tuo computer, avviato insieme al gioco, oppure in rete, dove la partita continua anche a gioco chiuso."), 14, Palette.TextSecondary);
lead.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(lead);
var modes = PanelKit.Row(12);
var group = new ButtonGroup();
ModeCard(_localCard, group, T("Gioca in locale"), T("Server su questo computer, avviato e chiuso con il gioco. Le partite restano qui."));
ModeCard(_remoteCard, group, T("Connetti a un server"), T("Server dedicato in rete, per esempio in Docker su un NAS. Più giocatori, partita sempre accesa."));
_localCard.Pressed += () => SetMode(local: true, start: true);
_remoteCard.Pressed += () => SetMode(local: false, start: true);
modes.AddChild(_localCard);
modes.AddChild(_remoteCard);
col.AddChild(modes);
// indirizzo e token del server in rete
_remoteFields.AddThemeConstantOverride("separation", 8);
var fields = PanelKit.Row(10);
var addressCol = PanelKit.Column(4);
addressCol.SizeFlagsHorizontal = SizeFlags.ExpandFill;
addressCol.AddChild(UiTheme.Text(T("Indirizzo (host:porta)"), 13, Palette.TextSecondary));
addressCol.AddChild(_address);
var tokenCol = PanelKit.Column(4);
tokenCol.SizeFlagsHorizontal = SizeFlags.ExpandFill;
tokenCol.AddChild(UiTheme.Text(T("Token"), 13, Palette.TextSecondary));
tokenCol.AddChild(_token);
fields.AddChild(addressCol);
fields.AddChild(tokenCol);
_remoteFields.AddChild(fields);
var probeRow = PanelKit.Row(10);
_rememberBox.SizeFlagsHorizontal = SizeFlags.ExpandFill;
probeRow.AddChild(_rememberBox);
_probe.Pressed += SubmitRemote;
probeRow.AddChild(_probe);
_remoteFields.AddChild(probeRow);
_token.TextSubmitted += _ => SubmitRemote();
col.AddChild(_remoteFields);
// stato del server
var state = new PanelContainer();
state.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 10, 18));
var stateCol = PanelKit.Column(12);
var stateHead = PanelKit.Row(10);
stateHead.AddChild(_dot);
stateHead.AddChild(_stateTitle);
stateCol.AddChild(stateHead);
_stateGrid.AddThemeConstantOverride("h_separation", 24);
_stateGrid.AddThemeConstantOverride("v_separation", 12);
for (int i = 0; i < 6; i++)
{
var cell = PanelKit.Column(2);
cell.SizeFlagsHorizontal = SizeFlags.ExpandFill;
var caption = UiTheme.Text("", 12, Palette.TextSecondary);
var value = UiTheme.Text("", 14, bold: true);
value.AutowrapMode = TextServer.AutowrapMode.WordSmart;
cell.AddChild(caption);
cell.AddChild(value);
_stateGrid.AddChild(cell);
_stateCells.Add((caption, value));
}
stateCol.AddChild(_stateGrid);
state.AddChild(stateCol);
col.AddChild(state);
// partite salvate sul server: nome, data di gioco, quanto tempo fa
col.AddChild(UiTheme.Text(T("Partite salvate sul server"), 17, bold: true));
_saves.SetColumnExpand(0, true);
_saves.SetColumnExpandRatio(0, 3);
_saves.SetColumnExpand(1, true);
_saves.SetColumnExpandRatio(1, 2);
_saves.SetColumnExpand(2, true);
_saves.SetColumnExpandRatio(2, 1);
_saves.ItemSelected += () =>
{
if (_saves.GetSelected() is { } item) _selectedSave = item.GetMetadata(0).AsString();
};
_saves.ItemActivated += Resume;
col.AddChild(_saves);
var actions = PanelKit.Row(10);
_resume.CustomMinimumSize = new Vector2(0, 48);
_resume.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_resume.Pressed += Resume;
actions.AddChild(_resume);
_newGame.CustomMinimumSize = new Vector2(0, 48);
_newGame.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_newGame.Pressed += NewGameOnServer;
actions.AddChild(_newGame);
col.AddChild(actions);
var tutorialRow = PanelKit.Row(10);
_showTutorial.ButtonPressed = !TutorialSettings.Played;
_showTutorial.TooltipText = T("Guida passo per passo alla prima linea: si chiude quando vuoi e si riapre con F1");
_showTutorial.SizeFlagsHorizontal = SizeFlags.ExpandFill;
tutorialRow.AddChild(_showTutorial);
_tutorial.TooltipText = T("Nuova partita locale di prova con il tutorial dal primo passo: la tua partita locale resta com'è");
_tutorial.CustomMinimumSize = new Vector2(160, 40);
_tutorial.Pressed += () =>
{
if (_busy) return;
// da qui la schermata non avvia né riprende altro: Main apre la partita di prova
_busy = true;
_tutorial.Disabled = true;
TutorialRequested?.Invoke();
};
tutorialRow.AddChild(_tutorial);
col.AddChild(tutorialRow);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(_status);
col.AddChild(UiTheme.Notice(T("La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://).")));
var cfg = new ConfigFile();
if (cfg.Load(SettingsPath) == Error.Ok)
// piede: lingua, audio, uscita, avviso sulla cifratura
var foot = PanelKit.Row(8);
foreach (var (code, label) in new[] { ("it", "Italiano"), ("en", "English") })
{
_address.Text = (string)cfg.GetValue("server", "address", "");
_token.Text = (string)cfg.GetValue("server", "token", "");
var b = new Button { Text = label, ToggleMode = true, ButtonPressed = TranslationServer.GetLocale().StartsWith(code) };
b.Pressed += () => LanguageChanged?.Invoke(code);
foot.AddChild(b);
}
_token.TextSubmitted += _ => Submit();
var audio = new Button { Text = T("Audio") };
audio.Pressed += () => AudioRequested?.Invoke();
foot.AddChild(audio);
foot.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
var quit = new Button { Text = T("Esci"), CustomMinimumSize = new Vector2(100, 0) };
quit.Pressed += () => GetTree().Quit();
foot.AddChild(quit);
col.AddChild(foot);
var notice = UiTheme.Text(T("La connessione non è cifrata: per Internet usa un reverse proxy con TLS (wss://)."), 12, Palette.TextSecondary);
notice.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(notice);
// conferma prima di sostituire la partita sul server
_confirm.OkButtonText = T("Sostituisci la partita");
_confirm.CancelButtonText = T("Annulla");
_confirm.Confirmed += () =>
{
var action = _onConfirm;
_onConfirm = null;
action?.Invoke();
};
_confirm.Canceled += () => _onConfirm = null;
AddChild(_confirm);
bool remote = false;
if (_remember)
{
var cfg = new ConfigFile();
if (cfg.Load(SettingsPath) == Error.Ok)
{
_address.Text = (string)cfg.GetValue("server", "address", "");
_token.Text = (string)cfg.GetValue("server", "token", "");
remote = (string)cfg.GetValue("server", "mode", "local") == "remote";
}
}
if (_handover is not null)
{
// cambio di lingua: la sessione di prova (e il suo server locale) passa a questa schermata
var session = _handover;
_handover = null;
SetMode(local: session.LocalServer is not null, start: false);
Attach(session);
}
else
{
// all'apertura si avvia la strada scelta l'ultima volta, come nell'immagine 09
SetMode(local: !remote, start: _autoStart);
}
ShowState();
}
public void SetStatus(string text, bool busy)
private static void ModeCard(Button card, ButtonGroup group, string title, string text)
{
_status.Text = text;
_connect.Disabled = busy;
card.ButtonGroup = group;
card.AddThemeStyleboxOverride("normal", UiTheme.Box(Palette.Inner, Palette.Border, 10, 0));
card.AddThemeStyleboxOverride("hover", UiTheme.Box(Palette.Inner, Palette.AmberDark, 10, 0));
card.AddThemeStyleboxOverride("pressed", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 0));
card.AddThemeStyleboxOverride("hover_pressed", UiTheme.Box(Palette.AmberDark, Palette.Amber, 10, 0));
card.AddThemeStyleboxOverride("disabled", UiTheme.Box(Palette.Inner, Palette.Border, 10, 0));
var margin = new MarginContainer { MouseFilter = MouseFilterEnum.Ignore };
margin.SetAnchorsPreset(LayoutPreset.FullRect);
foreach (var side in new[] { "left", "right", "top", "bottom" }) margin.AddThemeConstantOverride("margin_" + side, 16);
var col = PanelKit.Column(6);
col.MouseFilter = MouseFilterEnum.Ignore;
var t = UiTheme.Text(title, 17, Palette.AmberLight, bold: true);
var d = UiTheme.Text(text, 12, Palette.TextSecondary);
d.AutowrapMode = TextServer.AutowrapMode.WordSmart;
t.MouseFilter = d.MouseFilter = MouseFilterEnum.Ignore;
col.AddChild(t);
col.AddChild(d);
margin.AddChild(col);
card.AddChild(margin);
}
private void Submit()
private static string ClientVersion =>
typeof(ConnectScreen).Assembly.GetName().Version?.ToString(3) ?? "0.0.0";
// ------------------------------------------------------------------ modalità e sessione di prova
/// <summary>La sessione di prova è della strada scelta: server locale figlio del gioco o server in rete.</summary>
private bool SessionMatchesMode => _session is not null && (_session.LocalServer is not null) == _local;
/// <summary>
/// Cambia strada. La sessione dell'altra strada si chiude (e con lei il server locale), così
/// «Connetti e riprendi» non apre mai la partita della strada non scelta. Con start si avvia il
/// server locale o si verifica il server in rete indicato.
/// </summary>
private void SetMode(bool local, bool start)
{
_local = local;
_localCard.SetPressedNoSignal(local);
_remoteCard.SetPressedNoSignal(!local);
_remoteFields.Visible = !local;
if (_session is not null && !SessionMatchesMode)
{
_ = Release();
SetStatus("");
}
if (_remember)
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("server", "mode", local ? "local" : "remote");
cfg.Save(SettingsPath);
}
if (start && _session is null && !_busy)
{
if (local) _ = StartLocal();
else if (_address.Text.Trim().Length > 0) SubmitRemote();
}
ShowState();
}
/// <summary>Avvia il server locale figlio del gioco e apre la sessione di prova.</summary>
private async Task StartLocal()
{
if (_busy) return;
string? server = LocalServerLauncher.FindServer();
if (server is null)
{
_resumeAfterConnect = false;
SetStatus(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."), error: true);
return;
}
await Release();
_busy = true;
SetStatus(T("Avvio del server locale…"));
ShowState();
var launcher = new LocalServerLauncher();
try
{
int port = await launcher.StartAsync(server, ProjectSettings.GlobalizePath("user://server"), TimeSpan.FromSeconds(60));
var session = await GameSession.ConnectAsync(_data, new Uri($"ws://127.0.0.1:{port}/ws"), launcher.Token, T("Partita locale"));
session.LocalServer = launcher;
_busy = false;
if (!Adopt(session, local: true)) return;
SetStatus("");
}
catch (Exception e)
{
launcher.Dispose();
_busy = false;
_resumeAfterConnect = false;
if (!_closed) SetStatus($"{T("Partita locale non avviata")}: {e.Message}", error: true);
}
if (!_closed) ShowState();
}
private void SubmitRemote()
{
string address = _address.Text.Trim();
if (address.Length == 0)
{
SetStatus(T("Indica l'indirizzo del server"), false);
_resumeAfterConnect = false;
SetStatus(T("Indica l'indirizzo del server"), error: true);
return;
}
string url = address.Contains("://") ? address : $"ws://{address}";
if (!url.EndsWith("/ws", StringComparison.Ordinal)) url = url.TrimEnd('/') + "/ws";
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
{
SetStatus(T("Indirizzo non valido"), false);
_resumeAfterConnect = false;
SetStatus(T("Indirizzo non valido"), error: true);
return;
}
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("server", "address", address);
cfg.SetValue("server", "token", _token.Text);
cfg.Save(SettingsPath);
ConnectRequested?.Invoke(uri, _token.Text, uri.Host);
if (_remember)
{
var cfg = new ConfigFile();
cfg.Load(SettingsPath);
cfg.SetValue("server", "address", _rememberBox.ButtonPressed ? address : "");
cfg.SetValue("server", "token", _rememberBox.ButtonPressed ? _token.Text : "");
cfg.Save(SettingsPath);
}
_ = ProbeRemote(uri, _token.Text);
}
/// <summary>Collega la sessione di prova a un server in rete (dal pulsante o dal collaudo).</summary>
public async Task ProbeRemote(Uri uri, string token)
{
if (_busy) return;
SetMode(local: false, start: false);
await Release();
_busy = true;
SetStatus(T("Collegamento in corso…"));
ShowState();
try
{
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
var session = await GameSession.ConnectAsync(_data, uri, token, uri.Host, cts.Token);
_busy = false;
if (!Adopt(session, local: false)) return;
SetStatus("");
}
catch (Exception e)
{
_busy = false;
_resumeAfterConnect = false;
if (!_closed) SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", error: true);
}
if (!_closed) ShowState();
}
/// <summary>
/// Prende la sessione appena aperta, se la schermata è ancora aperta e sulla stessa strada;
/// altrimenti la chiude (con il suo server locale). Con «Connetti e riprendi» in attesa si entra
/// subito in partita.
/// </summary>
private bool Adopt(GameSession session, bool local)
{
if (_closed || _local != local)
{
_resumeAfterConnect = false;
_ = session.DisposeAsync();
return false;
}
Attach(session);
if (_resumeAfterConnect)
{
_resumeAfterConnect = false;
Play();
return false;
}
return true;
}
private void Attach(GameSession session)
{
_session = session;
_shownSaves = null;
_sinceSaves = double.MaxValue;
_session.MessageApplied += OnMessage;
}
/// <summary>Chiude la sessione di prova (e il server locale, se è suo).</summary>
private async Task Release()
{
var s = _session;
_session = null;
_shownSaves = null;
_awaitingWelcome = null;
if (s is null) return;
s.MessageApplied -= OnMessage;
await s.DisposeAsync();
}
/// <summary>Consegna la sessione di prova a chi la chiede (Main: partita, cambio di lingua, chiusura del gioco).</summary>
public GameSession? TakeSession()
{
var s = _session;
if (s is not null) s.MessageApplied -= OnMessage;
_session = null;
_awaitingWelcome = null;
return s;
}
public override void _ExitTree()
{
// una connessione ancora in corso si chiude da sola quando arriva (Adopt)
_closed = true;
if (_session is not null) _ = Release();
}
private void OnMessage(IMessage m) => _awaitingWelcome?.Invoke(m);
public override void _Process(double delta)
{
if (_session is null) return;
_session.Poll();
if (_session is null) return; // Play durante Poll: la sessione è passata alla partita
if (!_session.IsOpen)
{
SetStatus(T("Il server ha chiuso la connessione"), error: true);
_ = Release();
ShowState();
return;
}
_sinceSaves += delta;
if (_awaitingWelcome is not null && (_waiting += delta) > WelcomeTimeoutS)
{
_awaitingWelcome = null;
SetStatus(T("Il server non ha risposto"), error: true);
}
if (_sinceSaves >= SavesRefreshS && _awaitingWelcome is null)
{
_sinceSaves = 0;
_session.Send(new ListSaves());
}
if (!ReferenceEquals(_session.World.Saves, _shownSaves)) ShowSaves();
ShowState();
}
// ------------------------------------------------------------------ azioni
private void Resume()
{
if (_busy || _awaitingWelcome is not null) return;
if (_session is null)
{
// nessuna sessione ancora: «Connetti e riprendi» apre la strada scelta ed entra in partita
_resumeAfterConnect = true;
if (_local) _ = StartLocal();
else SubmitRemote();
return;
}
if (!SessionMatchesMode) return;
string id = _selectedSave;
var save = _shownSaves?.Saves.FirstOrDefault(s => s.SaveId == id);
if (id == CurrentGame || save is null)
{
Play();
return;
}
Confirm(string.Format(T("Il server sostituirà la partita in corso ({0}) con il salvataggio «{1}» per tutti i client collegati ({2}). Quello che non è stato salvato andrà perso."),
CurrentGameText(), save.Name, ConnectedText()), () =>
{
if (_session is null || _awaitingWelcome is not null) return;
SetStatus($"{T("Caricamento di")} {save.Name}…");
AwaitWelcome();
_session.Send(new Load { SaveId = id });
});
}
private void NewGameOnServer()
{
if (_session is null || _awaitingWelcome is not null || !SessionMatchesMode) return;
Confirm(string.Format(T("Il server sostituirà la partita in corso ({0}) con una partita nuova per tutti i client collegati ({1}). Quello che non è stato salvato andrà perso."),
CurrentGameText(), ConnectedText()), () =>
{
if (_session is null || _awaitingWelcome is not null) return;
var summary = _session.World.Summary;
SetStatus(T("Creazione della nuova partita sul server…"));
AwaitWelcome();
// il seme lo sceglie il client: la generazione resta deterministica sul server
_session.Send(new NewGame { Seed = (ulong)Time.GetUnixTimeFromSystem() ^ (summary?.Seed ?? 0), SizeKm = summary?.SizeKm ?? 0, DifficultyPreset = _session.Difficulty });
});
}
private void Confirm(string text, Action action)
{
_onConfirm = action;
_confirm.DialogText = text;
_confirm.PopupCentered();
}
private string CurrentGameText()
{
var summary = _session?.World.Summary;
return summary is null ? "—" : $"{summary.CompanyName}, {summary.Date}";
}
private string ConnectedText()
{
var info = _session?.World.Server;
return info is null ? "?" : info.Sessions.ToString();
}
/// <summary>Dopo Load o NewGame il server rimanda il Welcome a tutti: allora si entra in partita.</summary>
private void AwaitWelcome()
{
_awaitingWelcome = m =>
{
if (m is Welcome)
{
_awaitingWelcome = null;
Play();
}
else if (m is Notification { Event.Day: < 0 } note)
{
// caricamento o creazione rifiutati: l'avviso del server ha il giorno −1; gli eventi
// del mondo (giorno della partita) arrivano anche qui e non interrompono l'attesa
_awaitingWelcome = null;
SetStatus(note.Event.Text, error: true);
}
};
_waiting = 0;
}
private void Play()
{
var s = TakeSession();
if (s is not null) PlayRequested?.Invoke(s);
}
// ------------------------------------------------------------------ stato
public void SetStatus(string text, bool error = false)
{
_status.Text = text;
_status.AddThemeColorOverride("font_color", error ? Palette.Danger : Palette.TextSecondary);
}
private void ShowState()
{
var info = _session?.World.Server;
var summary = _session?.World.Summary;
double now = Time.GetTicksMsec() / 1000.0;
if (!ReferenceEquals(info, _infoSeen))
{
_infoSeen = info;
_infoAt = now;
}
string title;
Color dot;
if (_busy)
{
title = _local ? T("Avvio del server locale…") : T("Collegamento in corso…");
dot = Palette.Amber;
}
else if (_session is not null)
{
title = $"{T("Server raggiungibile")} · {_session.ServerLabel}";
dot = Palette.Ok;
}
else
{
title = _local ? T("Server locale spento: «Connetti e riprendi» lo avvia") : T("Non collegato");
dot = Palette.TextSecondary;
}
_stateTitle.Text = title;
_dot.Color = dot;
var cells = new (string, string)[]
{
(T("Versione"), info is null ? "—" : $"{info.Version}, {T("protocollo")} {Frame.ProtocolVersion}"),
(T("Sistema"), info is null ? "—" : info.Os + (info.Container ? " · Docker" : "") + (info.Local ? " · " + T("locale") : "")),
(T("Attivo da"), info is null ? "—" : Uptime(info.UptimeSeconds + (long)(now - _infoAt))),
(T("Simulazione"), info is null || info.TickMs <= 0 ? "—" : $"{Fmt.Number(1000 / info.TickMs, 0)} {T("tick al secondo")}" + (summary is null ? "" : $" · {summary.Date}")),
(T("Latenza"), _session is null || _session.LatencyMs <= 0 ? "—" : $"{Fmt.Number(_session.LatencyMs, 0)} ms"),
(T("Client collegati"), info is null ? "—" : $"{info.Sessions} / {info.MaxSessions}"),
};
for (int i = 0; i < cells.Length && i < _stateCells.Count; i++)
{
_stateCells[i].Caption.Text = cells[i].Item1;
_stateCells[i].Value.Text = cells[i].Item2;
}
bool ready = SessionMatchesMode && !_busy && _awaitingWelcome is null;
// senza sessione «Connetti e riprendi» apre la connessione; «Nuova partita» vuole il server collegato
_resume.Disabled = _busy || _awaitingWelcome is not null || (_session is not null && !ready);
_newGame.Disabled = !ready;
_probe.Disabled = _busy;
_tutorial.Disabled = _busy;
_localCard.Disabled = _busy;
_remoteCard.Disabled = _busy;
}
/// <summary>Elenco ricostruito a ogni aggiornamento: la riga scelta si ritrova per id, non per posizione.</summary>
private void ShowSaves()
{
var w = _session!.World;
_shownSaves = w.Saves;
_saves.Clear();
var root = _saves.CreateItem();
var current = _saves.CreateItem(root);
current.SetText(0, $"{T("Partita in corso")} · {w.Summary?.CompanyName ?? ""}");
current.SetText(1, w.Summary?.Date ?? "");
current.SetText(2, T("in corso"));
current.SetMetadata(0, CurrentGame);
current.SetCustomColor(2, Palette.Ok);
TreeItem selected = current;
double now = Time.GetUnixTimeFromSystem();
foreach (var s in (_shownSaves?.Saves ?? []).OrderByDescending(s => s.SavedUnixMs).ThenBy(s => s.SaveId, StringComparer.Ordinal))
{
var item = _saves.CreateItem(root);
item.SetText(0, s.Autosave ? $"{s.Name} ({T("automatico")})" : s.Name);
item.SetText(1, s.GameDate);
item.SetText(2, Ago(now - s.SavedUnixMs / 1000.0));
item.SetMetadata(0, s.SaveId);
for (int c = 1; c < 3; c++) item.SetCustomColor(c, Palette.TextSecondary);
if (s.SaveId == _selectedSave) selected = item;
}
// salvataggio scelto sparito dall'elenco: si torna alla partita in corso
_selectedSave = selected.GetMetadata(0).AsString();
selected.Select(0);
}
private static string Uptime(long seconds)
{
if (seconds < 3600) return $"{Math.Max(1, seconds / 60)} min";
if (seconds < 86_400) return $"{seconds / 3600} h {seconds % 3600 / 60} min";
return $"{seconds / 86_400} {T("giorni")} {seconds % 86_400 / 3600} h";
}
private static string Ago(double seconds)
{
if (seconds < 90) return T("adesso");
if (seconds < 3600) return $"{(int)(seconds / 60)} {T("minuti fa")}";
if (seconds < 86_400) return $"{(int)(seconds / 3600)} {T("ore fa")}";
return $"{(int)(seconds / 86_400)} {T("giorni fa")}";
}
}
/// <summary>
/// Mappa decorativa della schermata iniziale: pianura, un fiume, una linea a doppio binario con
/// stazioni e i tetti dei paesi, disegnati in codice con la palette della mappa (immagine 05) e
/// velati verso il basso per il titolo. Solo grafica: nessun dato di gioco.
/// </summary>
public partial class ConnectBackdrop : Control
{
public override void _Draw()
{
var size = Size;
DrawRect(new Rect2(Vector2.Zero, size), Palette.Plain);
// colline e boschi a macchie, posizioni fisse in frazioni della superficie
foreach (var (x, y, r, c) in new[] { (0.15f, 0.2f, 0.16f, Palette.Hill), (0.7f, 0.15f, 0.2f, Palette.Highland), (0.85f, 0.55f, 0.14f, Palette.Undergrowth),
(0.3f, 0.6f, 0.12f, Palette.Undergrowth), (0.55f, 0.35f, 0.07f, Palette.Canopy), (0.1f, 0.45f, 0.06f, Palette.Canopy), (0.62f, 0.72f, 0.05f, Palette.Canopy) })
DrawCircle(new Vector2(x * size.X, y * size.Y), r * Math.Max(size.X, size.Y), c);
// fiume
var river = new Vector2[] { new(0.62f, 0f), new(0.58f, 0.18f), new(0.66f, 0.36f), new(0.6f, 0.55f), new(0.7f, 0.78f), new(0.66f, 1f) };
DrawPolyline(river.Select(p => p * size).ToArray(), Palette.Banks, 30, true);
DrawPolyline(river.Select(p => p * size).ToArray(), Palette.Water, 20, true);
// linea ferroviaria: massicciata, traversine, rotaie
var rail = new Vector2[] { new(-0.05f, 0.42f), new(0.25f, 0.38f), new(0.48f, 0.44f), new(0.75f, 0.4f), new(1.05f, 0.3f) };
var pts = rail.Select(p => p * size).ToArray();
DrawPolyline(pts, Palette.Ballast, 16, true);
for (int i = 0; i < pts.Length - 1; i++)
{
var a = pts[i];
var b = pts[i + 1];
var dir = (b - a).Normalized();
var n = new Vector2(-dir.Y, dir.X) * 7;
for (float t = 0; t < a.DistanceTo(b); t += 9)
{
var p = a + dir * t;
DrawLine(p - n, p + n, Palette.Sleepers, 3);
}
}
foreach (float off in new[] { -3.5f, 3.5f })
DrawPolyline(pts.Select((p, i) => p + Normal(pts, i) * off).ToArray(), Palette.Rails, 1.5f, true);
// stazioni e paesi
foreach (var (x, y) in new[] { (0.25f, 0.38f), (0.75f, 0.4f) })
{
var c = new Vector2(x * size.X, y * size.Y);
DrawRect(new Rect2(c - new Vector2(22, 26), new Vector2(44, 14)), Palette.Panel);
for (int k = 0; k < 9; k++)
{
var roof = c + new Vector2((k % 3 - 1) * 26 + (k * 7 % 5), 28 + k / 3 * 20);
DrawRect(new Rect2(roof, new Vector2(16, 12)), k % 4 == 0 ? Palette.IndustrialRoof : Palette.TileRoof);
}
}
// velo verso il basso per leggere il titolo
var veil = new Color[] { Palette.WithAlpha(Palette.AppBackground, 0.15f), Palette.WithAlpha(Palette.AppBackground, 0.15f), Palette.WithAlpha(Palette.AppBackground, 0.92f), Palette.WithAlpha(Palette.AppBackground, 0.92f) };
DrawPolygon([new Vector2(0, size.Y * 0.35f), new Vector2(size.X, size.Y * 0.35f), new Vector2(size.X, size.Y), new Vector2(0, size.Y)], veil);
}
private static Vector2 Normal(Vector2[] pts, int i)
{
var dir = (pts[Math.Min(i + 1, pts.Length - 1)] - pts[Math.Max(i - 1, 0)]).Normalized();
return new Vector2(-dir.Y, dir.X);
}
public override void _Notification(int what)
{
if (what == NotificationResized) QueueRedraw();
}
}
@@ -1,5 +1,6 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Audio;
using RailEnterprise.Client.Hud;
using RailEnterprise.Client.Map;
using RailEnterprise.Client.Net;
@@ -105,7 +106,7 @@ public partial class GameScreen : Node
_maintenance?.SelectDepot(depot);
}
/// <summary>Apre il pannello Industrie sull'industria indicata (scheda del proprietario).</summary>
/// <summary>Apre la scheda dell'industria a tutto schermo (immagine 07) sull'industria indicata.</summary>
public void OpenIndustry(int industry)
{
if (_tool != Tool.Industries) _toolbar.Select(Tool.Industries);
@@ -132,6 +133,9 @@ public partial class GameScreen : Node
if (_tool != Tool.Climb) _toolbar.Select(Tool.Climb);
}
/// <summary>Chiude lo strumento o la schermata a tutto schermo aperta e torna alla mappa.</summary>
public void CloseTools() => _toolbar.Select(Tool.None);
/// <summary>Apre le «Finanze» a tutto schermo: conto economico, rating e prestiti.</summary>
public void OpenFinance()
{
@@ -149,6 +153,17 @@ public partial class GameScreen : Node
}
}
/// <summary>Dalla scheda dell'industria: strumento binari con la mappa centrata sull'industria da collegare.</summary>
private void PlanLineToIndustry(int industry)
{
_toolbar.Select(Tool.Track);
if (_session.World.Industries.TryGetValue(industry, out var ind))
{
_map.CenterOn(MapScale.V(ind.Position));
_map.SetZoom(0.3f);
}
}
/// <summary>Chiede al server la Cronaca (provvisoria a partita in corso) e la mostra all'arrivo.</summary>
public void OpenChronicle()
{
@@ -168,6 +183,11 @@ public partial class GameScreen : Node
/// <summary>Scorre il pannello laterale (0 = in cima, 1 = in fondo).</summary>
public void ScrollPanel(double fraction)
{
if (_industryPanel is not null)
{
_industryPanel.ScrollTo(fraction);
return;
}
var bar = _scroll.GetVScrollBar();
_scroll.ScrollVertical = (int)Math.Round((bar.MaxValue - bar.Page) * Math.Clamp(fraction, 0, 1));
}
@@ -201,12 +221,7 @@ public partial class GameScreen : Node
var mapArea = new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, MouseFilter = Control.MouseFilterEnum.Ignore };
middle.AddChild(mapArea);
_mapArea = mapArea;
_toasts.SetAnchorsPreset(Control.LayoutPreset.TopWide);
_toasts.OffsetLeft = 16;
_toasts.OffsetRight = -16;
_toasts.OffsetTop = 12;
_toasts.MouseFilter = Control.MouseFilterEnum.Ignore;
mapArea.AddChild(_toasts);
var side = new PanelContainer { CustomMinimumSize = new Vector2(440, 0) };
side.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 18));
middle.AddChild(side);
@@ -232,6 +247,9 @@ public partial class GameScreen : Node
sideCol.AddChild(miniHeader);
sideCol.AddChild(_minimap);
root.AddChild(_ticker);
// avvisi sopra tutta l'interfaccia, in alto sull'area visibile: la mappa o la schermata a
// tutto schermo (con la mappa nascosta un avviso dentro di lei non si vedrebbe)
hud.AddChild(_toasts);
BuildDisconnectedOverlay(hud);
AddChild(_overlay);
@@ -247,13 +265,18 @@ public partial class GameScreen : Node
_session.MessageApplied += OnMessage;
_session.Notified += e => _ticker.Add(e);
_session.CommandFailed += r => Toast(r.Message, error: true);
AudioManager.Instance?.Bind(_session, _map);
SelectTool(Tool.None);
SendViewport(force: true);
// il Registro degli impieghi alimenta anche le schede di industrie e città
_session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 });
}
public override void _ExitTree() => _session.MessageApplied -= OnMessage;
public override void _ExitTree()
{
_session.MessageApplied -= OnMessage;
AudioManager.Instance?.Unbind(_session);
}
/// <summary>Codice di EventKind.World nel protocollo (notizie degli eventi del mondo, ADR 0017).</summary>
private const byte WorldEventKind = 10;
@@ -341,6 +364,7 @@ public partial class GameScreen : Node
public override void _Process(double delta)
{
PlaceToasts();
_session.Poll();
_disconnected.Visible = !_session.IsOpen;
UpdateChronicle();
@@ -419,7 +443,7 @@ public partial class GameScreen : Node
_finance = null;
_trainsPanel = null;
foreach (var c in _full.GetChildren()) c.QueueFree();
bool full = tool is Tool.Companies or Tool.Market or Tool.Climb or Tool.Finance;
bool full = tool is Tool.Companies or Tool.Market or Tool.Climb or Tool.Finance or Tool.Industries;
_full.Visible = full;
if (_mapArea is not null) _mapArea.Visible = !full;
if (_side is not null) _side.Visible = !full;
@@ -473,7 +497,11 @@ public partial class GameScreen : Node
panel = new EmploymentPanel(_session);
break;
case Tool.Industries:
panel = _industryPanel = new IndustryPanel(_session);
_industryPanel = new IndustryPanel(_session);
_industryPanel.CloseRequested += () => _toolbar.Select(Tool.None);
_industryPanel.PlanLineRequested += PlanLineToIndustry;
_full.AddChild(_industryPanel);
panel = NewInfoPanel();
break;
case Tool.Companies:
_companies = new CompaniesPanel(_session);
@@ -831,7 +859,8 @@ public partial class GameScreen : Node
_chronicleScreen = screen;
}
private void CloseChronicle()
/// <summary>Chiude la Cronaca se è aperta.</summary>
public void CloseChronicle()
{
_chronicleScreen?.QueueFree();
_chronicleScreen = null;
@@ -856,8 +885,19 @@ public partial class GameScreen : Node
Toast($"{T("Nuova partita+ in preparazione")}: {(TranslationServer.GetLocale().StartsWith("en") ? next.NameEn : next.NameIt)}");
}
/// <summary>Messaggio temporaneo in alto sulla mappa.</summary>
private void Toast(string text, bool error = false)
/// <summary>Allinea gli avvisi in cima all'area visibile: la mappa o la schermata a tutto schermo.</summary>
private void PlaceToasts()
{
if (_toasts.GetChildCount() == 0) return;
Control? area = _full.Visible ? _full : _mapArea;
if (area is null) return;
var rect = area.GetGlobalRect();
_toasts.Position = rect.Position + new Vector2(16, 12);
_toasts.Size = new Vector2(Math.Max(0, rect.Size.X - 32), 0);
}
/// <summary>Messaggio temporaneo in alto sull'area visibile (mappa o schermata a tutto schermo); lo usa anche il tutorial.</summary>
public void Toast(string text, bool error = false)
{
var notice = UiTheme.Notice(text);
if (error) notice.AddThemeStyleboxOverride("panel", UiTheme.Box(new Color("3a1c16"), Palette.Danger, 8, 12));
@@ -867,5 +907,6 @@ public partial class GameScreen : Node
if (IsInstanceValid(notice)) notice.QueueFree();
};
while (_toasts.GetChildCount() > 4) _toasts.GetChild(0).QueueFree();
PlaceToasts();
}
}
@@ -1,73 +0,0 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Tutorial;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Screens;
/// <summary>
/// Menu iniziale: partita locale (server figlio), collegamento a un server, tutorial, lingua, uscita. La
/// casella «Mostra il tutorial» è attiva alla prima partita; «Tutorial» apre la partita locale con il
/// tutorial dal primo passo.
/// </summary>
public partial class MenuScreen : Control
{
public event Action? LocalGame;
public event Action? ConnectToServer;
public event Action<string>? LanguageChanged;
public event Action? TutorialRequested;
private readonly CheckBox _showTutorial = new() { Text = T("Mostra il tutorial") };
/// <summary>Casella «Mostra il tutorial» per la partita che si apre.</summary>
public bool ShowTutorial => _showTutorial.ButtonPressed;
private readonly Label _status = UiTheme.Text("", 14, Palette.TextSecondary);
public override void _Ready()
{
// già nell'albero: ancore e margini insieme, altrimenti la schermata resterebbe grande zero
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
UiTheme.Apply(this);
var bg = new ColorRect { Color = Palette.AppBackground };
bg.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(bg);
var center = new CenterContainer();
center.SetAnchorsPreset(LayoutPreset.FullRect);
AddChild(center);
var col = new VBoxContainer { CustomMinimumSize = new Vector2(440, 0) };
col.AddThemeConstantOverride("separation", 14);
center.AddChild(col);
col.AddChild(UiTheme.TitleLabel("Rail Enterprise", 96));
col.AddChild(UiTheme.Text(T("Gestionale ferroviario dall'alto"), 18, Palette.TextSecondary));
col.AddChild(new Control { CustomMinimumSize = new Vector2(0, 20) });
var local = UiTheme.Primary(T("Partita locale"));
local.CustomMinimumSize = new Vector2(0, 48);
local.Pressed += () => LocalGame?.Invoke();
col.AddChild(local);
_showTutorial.ButtonPressed = !TutorialSettings.Played;
_showTutorial.TooltipText = T("Guida passo per passo alla prima linea: si chiude quando vuoi e si riapre con F1");
col.AddChild(_showTutorial);
var remote = new Button { Text = T("Collegati a un server"), CustomMinimumSize = new Vector2(0, 48) };
remote.Pressed += () => ConnectToServer?.Invoke();
col.AddChild(remote);
var tutorial = new Button { Text = T("Tutorial"), CustomMinimumSize = new Vector2(0, 40) };
tutorial.TooltipText = T("Partita locale con il tutorial dal primo passo");
tutorial.Pressed += () => TutorialRequested?.Invoke();
col.AddChild(tutorial);
var lang = new HBoxContainer();
lang.AddThemeConstantOverride("separation", 8);
foreach (var (code, label) in new[] { ("it", "Italiano"), ("en", "English") })
{
var b = new Button { Text = label, ToggleMode = true, ButtonPressed = TranslationServer.GetLocale().StartsWith(code) };
b.Pressed += () => LanguageChanged?.Invoke(code);
lang.AddChild(b);
}
col.AddChild(lang);
var quit = new Button { Text = T("Esci"), CustomMinimumSize = new Vector2(0, 40) };
quit.Pressed += () => GetTree().Quit();
col.AddChild(quit);
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
col.AddChild(_status);
}
public void SetStatus(string text) => _status.Text = text;
}
@@ -1 +0,0 @@
uid://b5eyw35w2vo7l