F6: scheda industria e connessione, correzioni della revisione
Correzioni dalla revisione della scheda industria e della schermata di
connessione.
- Dati di altre compagnie: la forza lavoro della scheda mostra solo i
contratti a piedi, quelli della compagnia della sessione e, se
l'industria è sua, quelli di tutti i vettori, come il Registro degli
impieghi. Lo stesso filtro vale per provenienze, conteggio e viaggio
medio.
- Prezzo: «prezzo medio realizzato» mescolava una media mobile dei
ricavi con i totali del trimestre in corso. Al suo posto c'è il prezzo
di vendita, cioè il prezzo globale del giorno (SalePrice).
- Avvisi del server: hanno il giorno −1, così il rifiuto di Load o
NewGame non si confonde più con gli eventi del mondo che arrivano
mentre si aspetta il Welcome.
- Schermata di connessione:
- all'apertura avvia la strada scelta l'ultima volta;
- cambiando strada chiude la sessione dell'altra;
- senza sessione «Connetti e riprendi» la apre;
- il cambio di lingua passa la sessione alla schermata nuova;
- la scelta del salvataggio si tiene per id;
- Load e nuova partita chiedono conferma;
- stato del server su 3×2 con la versione del protocollo, salvataggi
su tre colonne, «Attivo da» che avanza.
- Scheda dell'industria:
- collegamenti e nodi non collegati sono leggibili;
- testo per l'industria inattiva;
- revisione e ammodernamento disabilitati, con il motivo, quando il
server li rifiuterebbe;
- l'esito dell'acquisto compare accanto al pulsante;
- le righe lunghe vanno a capo;
- «in sede» al posto di «al lavoro ora».
- Gli avvisi dei comandi compaiono anche sulle schermate a tutto
schermo.
- Pilota automatico:
- la schermata 20 sta su un suo CanvasLayer sopra l'interfaccia;
- 12 e 12b sono ora la scheda a tutto schermo.
- Test: pendolari di altri vettori nascosti, Load rifiutato via
WebSocket, Welcome senza ServerInfo. 202 test, 183 senza i lenti.
Refs #42.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
45462bf9ec
commit
0667a4a544
17 files changed
+514
-156
No files matched your search
@@ -7,7 +7,6 @@ Aderisci con le tue azioni,,Tender your shares
|
||||
adesso,,just now
|
||||
Aggiorna,,Refresh
|
||||
al giorno,,per day
|
||||
al lavoro ora,,at work now
|
||||
Alto,,High
|
||||
Ambra,,Amber
|
||||
Amministrazione controllata,,Receivership
|
||||
@@ -345,7 +344,6 @@ carica,,load
|
||||
cavaliere bianco,,white knight
|
||||
città senza servizi per il personale,,towns without services for staff
|
||||
Client collegati,,Connected clients
|
||||
Collegato a,,Connected to
|
||||
Collo di bottiglia,,Bottleneck
|
||||
Condizione degli impianti,,Plant condition
|
||||
Connetti a un server,,Connect to a server
|
||||
@@ -358,7 +356,6 @@ Copertura degli ingressi,,Input coverage
|
||||
Crea una linea verso questa industria,,Build a line to this industry
|
||||
Creazione della nuova partita sul server…,,Creating the new game on the server…
|
||||
da,,from
|
||||
dati compatibili,,compatible data
|
||||
degli utili come dividendo e non puoi chiedere prestiti.,,of profits as dividends and cannot take new loans.
|
||||
dei ricavi,,of revenue
|
||||
del capitale,,of the capital
|
||||
@@ -588,7 +585,6 @@ Scegli un'industria nell'elenco in alto.,,Choose an industry from the list above
|
||||
Scheda dell'industria,,Industry sheet
|
||||
scorta,,stock
|
||||
serve,,needs
|
||||
Server locale spento: scegli «Gioca in locale» per avviarlo,,Local server off: choose «Play locally» to start it
|
||||
"Server su questo computer, avviato e chiuso con il gioco. Le partite restano qui.",,"Server on this computer, started and stopped with the game. Games stay here."
|
||||
servita dalla stazione,,served by station
|
||||
servita dalla tua linea,,served by your line
|
||||
@@ -663,7 +659,6 @@ città oltre,,towns over
|
||||
collegata su,,connected out of
|
||||
collegate su,,connected out of
|
||||
merci su linea,,goods on a line
|
||||
Prezzo medio realizzato,,Average realised price
|
||||
Rating creditizio,,Credit rating
|
||||
attuale,,current
|
||||
Binari e opere,,Track and structures
|
||||
@@ -782,3 +777,16 @@ Verifica connessione,,Test connection
|
||||
Versione,,Version
|
||||
Versione del gioco,,Game version
|
||||
viaggio medio,,average trip
|
||||
Sostituire la partita?,,Replace the game?
|
||||
Sostituisci la partita,,Replace the game
|
||||
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.,,The server will replace the current game ({0}) with the save «{1}» for every connected client ({2}). Anything not saved will be lost.
|
||||
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.,,The server will replace the current game ({0}) with a new game for every connected client ({1}). Anything not saved will be lost.
|
||||
Server raggiungibile,,Server reachable
|
||||
Server locale spento: «Connetti e riprendi» lo avvia,,Local server off: «Connect and resume» starts it
|
||||
protocollo,,protocol
|
||||
in sede,,on site
|
||||
Prezzo di vendita,,Selling price
|
||||
Offerta inviata…,,Offer sent…
|
||||
Industria inattiva: non è in vendita finché non riprende a produrre.,,Inactive industry: not for sale until it starts producing again.
|
||||
L'industria è ferma: riprova a fermo finito.,,The industry is stopped: try again when the stop is over.
|
||||
C'è già un lavoro in programma.,,Work is already scheduled.
|
||||
|
@@ -209,13 +209,14 @@ public partial class AutoPilot : Node
|
||||
var anchor = MapScale.V(near);
|
||||
var industry = World.Industries.Values.Where(i => !i.Closed && i.Owner < 0 && i.Level > 0)
|
||||
.OrderBy(i => MapScale.V(i.Position).DistanceTo(anchor)).ThenBy(i => i.Id).First();
|
||||
// dalla F6 la scheda dell'industria è a tutto schermo (immagine 07): 12 è la scheda di
|
||||
// un'industria dei privati con l'avviso dell'acquisto rifiutato, 12b la stessa scheda in fondo
|
||||
// (impianti, crescita, storico dei fermi). La mappa non si vede: niente centratura né zoom
|
||||
_game.OpenIndustry(industry.Id);
|
||||
await Until(() => World.IndustryCards.ContainsKey(industry.Id), "scheda dell'industria", 30);
|
||||
// al livello iniziale il server rifiuta l'acquisto: il messaggio compare sulla mappa
|
||||
// al livello iniziale il server rifiuta l'acquisto: l'avviso compare in alto sopra la scheda
|
||||
var buy = await Do(new BuyIndustryCommand(new IndustryId(industry.Id), World.IndustryCards[industry.Id].Valuation));
|
||||
GD.Print($"autopilot: acquisto di {industry.Name}: {buy.Message}");
|
||||
_game.Map.CenterOn(MapScale.V(industry.Position));
|
||||
_game.Map.SetZoom(0.3f);
|
||||
await Shot("12_industria", 40);
|
||||
_game.ScrollPanel(1);
|
||||
await Shot("12b_industria_scorte", 20);
|
||||
@@ -270,12 +271,17 @@ public partial class AutoPilot : Node
|
||||
// locale con il suo stato e l'elenco dei salvataggi (uno appena fatto)
|
||||
Session.Send(new Save { Name = "Collaudo" });
|
||||
var launcher = Session.LocalServer ?? throw new InvalidOperationException("collaudo senza server locale");
|
||||
var connect = new ConnectScreen(World.Data, remember: false);
|
||||
_game.AddChild(connect);
|
||||
// livello proprio sopra l'interfaccia della partita (CanvasLayer 1–3): sul livello 0 la
|
||||
// schermata finirebbe sotto la scheda a tutto schermo e trasformata dalla camera della mappa
|
||||
_game.CloseTools();
|
||||
var layer = new CanvasLayer { Layer = 10 };
|
||||
_game.AddChild(layer);
|
||||
var connect = new ConnectScreen(World.Data, remember: false, autoStart: false);
|
||||
layer.AddChild(connect);
|
||||
await Frame();
|
||||
await connect.ProbeRemote(new Uri($"ws://127.0.0.1:{launcher.Port}/ws"), launcher.Token);
|
||||
await Until(() => connect.Loaded, "stato del server e salvataggi", 30);
|
||||
await Shot("20_connessione", 30);
|
||||
connect.QueueFree();
|
||||
layer.QueueFree();
|
||||
}
|
||||
}
|
||||
@@ -35,13 +35,15 @@ public partial class Main : Node
|
||||
{
|
||||
GD.PrintErr($"Dati del gioco non validi: {e.Message}");
|
||||
}
|
||||
ShowMenu(_data is null ? T("Dati del gioco non trovati o non validi.") : "");
|
||||
var args = OS.GetCmdlineUserArgs();
|
||||
int i = Array.IndexOf(args, "--autopilot");
|
||||
if (i >= 0 && _data is not null)
|
||||
_autopilot = i + 1 < args.Length ? args[i + 1] : ProjectSettings.GlobalizePath("user://autopilot");
|
||||
// nel collaudo la schermata di connessione non avvia un suo server: lo avvia StartLocal qui sotto
|
||||
ShowMenu(_data is null ? T("Dati del gioco non trovati o non validi.") : "", autoStart: _autopilot is null);
|
||||
if (_autopilot is not null)
|
||||
{
|
||||
// collaudo: mappa piccola e seme fisso per il server locale
|
||||
_autopilot = i + 1 < args.Length ? args[i + 1] : ProjectSettings.GlobalizePath("user://autopilot");
|
||||
System.Environment.SetEnvironmentVariable("RE_MAP_SIZE", "64");
|
||||
System.Environment.SetEnvironmentVariable("RE_SEED", "3");
|
||||
System.Environment.SetEnvironmentVariable("RE_AUTOSAVE_MIN", "0");
|
||||
@@ -57,7 +59,9 @@ public partial class Main : Node
|
||||
}
|
||||
|
||||
/// <summary>Schermata iniziale e di connessione (immagine 09): server locale o in rete, stato, salvataggi.</summary>
|
||||
private void ShowMenu(string status = "")
|
||||
/// <param name="autoStart">Avvia subito la strada scelta l'ultima volta (server locale o in rete).</param>
|
||||
/// <param name="handover">Sessione di prova della schermata precedente, ripresa così com'è (cambio di lingua).</param>
|
||||
private void ShowMenu(string status = "", bool autoStart = true, GameSession? handover = null)
|
||||
{
|
||||
if (_data is null)
|
||||
{
|
||||
@@ -67,7 +71,7 @@ public partial class Main : Node
|
||||
Swap(label);
|
||||
return;
|
||||
}
|
||||
var screen = new ConnectScreen(_data);
|
||||
var screen = new ConnectScreen(_data, autoStart: autoStart, handover: handover);
|
||||
screen.PlayRequested += ShowGame;
|
||||
screen.LanguageChanged += code =>
|
||||
{
|
||||
@@ -76,7 +80,8 @@ public partial class Main : Node
|
||||
cfg.SetValue("ui", "locale", code);
|
||||
cfg.Save(SettingsPath);
|
||||
TranslationServer.SetLocale(code);
|
||||
ShowMenu();
|
||||
// la schermata si ricrea con i testi nuovi: la sessione di prova (e il server locale) passa a lei
|
||||
ShowMenu(handover: screen.TakeSession());
|
||||
};
|
||||
Swap(screen);
|
||||
if (status.Length > 0) screen.SetStatus(status, error: true);
|
||||
@@ -89,7 +94,7 @@ public partial class Main : Node
|
||||
string? server = LocalServerLauncher.FindServer();
|
||||
if (server is null)
|
||||
{
|
||||
ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."));
|
||||
ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."), autoStart: false);
|
||||
return;
|
||||
}
|
||||
var launcher = new LocalServerLauncher();
|
||||
@@ -105,7 +110,7 @@ public partial class Main : Node
|
||||
catch (Exception e)
|
||||
{
|
||||
launcher.Dispose();
|
||||
ShowMenu($"{T("Partita locale non avviata")}: {e.Message}");
|
||||
ShowMenu($"{T("Partita locale non avviata")}: {e.Message}", autoStart: false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,10 +120,12 @@ public partial class Main : Node
|
||||
var game = new GameScreen(session);
|
||||
game.Exit += async () =>
|
||||
{
|
||||
// prima si chiude la partita (e il server locale), poi la schermata di connessione ne
|
||||
// avvia uno nuovo: due server sulla stessa cartella dei salvataggi non convivono
|
||||
var s = _session;
|
||||
_session = null;
|
||||
ShowMenu();
|
||||
if (s is not null) await s.DisposeAsync();
|
||||
ShowMenu();
|
||||
};
|
||||
Swap(game);
|
||||
if (_autopilot is not null) game.AddChild(new AutoPilot(game, _autopilot));
|
||||
|
||||
@@ -41,6 +41,9 @@ public partial class IndustryPanel : VBoxContainer
|
||||
private readonly VBoxContainer _controls = PanelKit.Column(8);
|
||||
private readonly VBoxContainer _history = PanelKit.Column(4);
|
||||
private readonly Label _status = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
/// <summary>Esito dell'offerta di acquisto, accanto al pulsante (la scheda è a tutto schermo e la mappa è nascosta).</summary>
|
||||
private readonly Label _buyStatus = UiTheme.Text("", 13, Palette.TextSecondary);
|
||||
private Button? _overhaul, _upgrade;
|
||||
private readonly List<Button> _budgetButtons = [];
|
||||
private SpinBox? _partsOrder;
|
||||
private int _industry = -1;
|
||||
@@ -123,6 +126,8 @@ public partial class IndustryPanel : VBoxContainer
|
||||
_graph.IndustryClicked += Select;
|
||||
chain.AddChild(_graph);
|
||||
chain.AddChild(_chainFooter);
|
||||
_buyStatus.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
chain.AddChild(_buyStatus);
|
||||
lower.AddChild(Card(T("Catena produttiva"), chain, 1.6f));
|
||||
var plants = PanelKit.Column(10);
|
||||
plants.AddChild(_plants);
|
||||
@@ -156,6 +161,7 @@ public partial class IndustryPanel : VBoxContainer
|
||||
if (id == _industry) return;
|
||||
_industry = id;
|
||||
_status.Text = "";
|
||||
_buyStatus.Text = "";
|
||||
_scroll.ScrollVertical = 0;
|
||||
SyncSelection();
|
||||
Request();
|
||||
@@ -188,10 +194,12 @@ public partial class IndustryPanel : VBoxContainer
|
||||
if ((w.EntityVersion != _entityVersion || w.DetailVersion != _detailVersion) && _sinceRefresh >= 0.25) Refresh();
|
||||
}
|
||||
|
||||
private void Result(CommandResultMessage r)
|
||||
private void Result(CommandResultMessage r) => Show(_status, r);
|
||||
|
||||
private void Show(Label label, CommandResultMessage r)
|
||||
{
|
||||
_status.Text = r.Message;
|
||||
_status.AddThemeColorOverride("font_color", r.Ok ? Palette.TextSecondary : Palette.Danger);
|
||||
label.Text = r.Message;
|
||||
label.AddThemeColorOverride("font_color", r.Ok ? Palette.TextSecondary : Palette.Danger);
|
||||
Request();
|
||||
}
|
||||
|
||||
@@ -327,7 +335,7 @@ public partial class IndustryPanel : VBoxContainer
|
||||
_inputs.AddChild(FlowHeader(GoodName(w, f.Good), $"{Fmt.Number(f.CurrentMonth, 0)} / {Fmt.Number(f.FullMonth, 0)} {unit} {T("al mese")}"));
|
||||
_inputs.AddChild(Bar(f.FullMonth <= 0 ? 0 : f.CurrentMonth / f.FullMonth, f.Limiting ? Palette.Danger : Palette.Amber));
|
||||
string days = f.Days < 0 ? "" : $" · {T("bastano per")} {Fmt.Number(f.Days, 0)} {T("giorni")}";
|
||||
_inputs.AddChild(UiTheme.Text($"{T("scorta")} {f.Stock} / {f.Storage} {unit}{days}", 12, f.Limiting ? Palette.Danger : Palette.TextSecondary));
|
||||
_inputs.AddChild(Wrapped($"{T("scorta")} {f.Stock} / {f.Storage} {unit}{days}", 12, f.Limiting ? Palette.Danger : Palette.TextSecondary));
|
||||
foreach (var p in f.Partners) _inputs.AddChild(PartnerLine(w, p, unit, supplier: true));
|
||||
if (f.Partners.Count == 0) _inputs.AddChild(UiTheme.Text(T("Nessun fornitore nella regione"), 12, Palette.TextSecondary));
|
||||
_inputs.AddChild(PanelKit.Separator());
|
||||
@@ -361,7 +369,8 @@ public partial class IndustryPanel : VBoxContainer
|
||||
_workforce.AddChild(FlowHeader(staff ? T("Personale qualificato") : T("Lavoratori"), $"{Fmt.Number(f.Present, 0)} / {f.Jobs} {T("presenti")}", color));
|
||||
_workforce.AddChild(Bar(f.Jobs <= 0 ? 0 : f.Present / f.Jobs, color));
|
||||
string minutes = f.AverageMinutes < 0 ? "" : $" · {T("viaggio medio")} {Fmt.Number(f.AverageMinutes, 0)} min";
|
||||
_workforce.AddChild(UiTheme.Text($"{T("copertura")} {window} {T("giorni")} {Fmt.Pct(coverage30, 0)} · {T("al lavoro ora")} {Fmt.Number(f.OnSite, 0)}{minutes}", 12, Palette.TextSecondary));
|
||||
// OnSite sono i posti coperti da chi vive negli alloggi dell'industria, non i presenti
|
||||
_workforce.AddChild(Wrapped($"{T("copertura")} {window} {T("giorni")} {Fmt.Pct(coverage30, 0)} · {T("in sede")} {Fmt.Number(f.OnSite, 0)}{minutes}", 12, Palette.TextSecondary));
|
||||
if (f.Missing > 0)
|
||||
{
|
||||
string reason = EmploymentPanel.ReasonText(w, f.Reason, f.ReasonLine, staff);
|
||||
@@ -375,7 +384,7 @@ public partial class IndustryPanel : VBoxContainer
|
||||
_workforce.AddChild(Wrapped($"• {src.Headcount} {T("da")} {town} · {via}{time} · {Fmt.Pct(src.Coverage, 0)}", 12, color));
|
||||
}
|
||||
if (f.SourceCount > f.Sources.Count)
|
||||
_workforce.AddChild(UiTheme.Text($"{T("e altre")} {f.SourceCount - f.Sources.Count} {T("provenienze")}", 12, Palette.TextSecondary));
|
||||
_workforce.AddChild(Wrapped($"{T("e altre")} {f.SourceCount - f.Sources.Count} {T("provenienze")}", 12, Palette.TextSecondary));
|
||||
}
|
||||
|
||||
private void BuildProduction(ClientWorld w, IndustryCard card, IndustrySheetInfo s)
|
||||
@@ -386,14 +395,14 @@ public partial class IndustryPanel : VBoxContainer
|
||||
_production.AddChild(FlowHeader(GoodName(w, f.Good), $"{Fmt.Number(f.CurrentMonth, 0)} / {Fmt.Number(f.FullMonth, 0)} {unit} {T("al mese")}"));
|
||||
_production.AddChild(Bar(f.FullMonth <= 0 ? 0 : f.CurrentMonth / f.FullMonth, Palette.Amber));
|
||||
string full = f.Days < 0 ? "" : f.Days <= 0 ? " · " + T("magazzino pieno") : $" · {T("pieno tra")} {Fmt.Number(f.Days, 0)} {T("giorni")}";
|
||||
_production.AddChild(UiTheme.Text($"{T("magazzino")} {f.Stock} / {f.Storage} {unit}{full}", 12, f.Days == 0 ? Palette.Danger : Palette.TextSecondary));
|
||||
_production.AddChild(Wrapped($"{T("magazzino")} {f.Stock} / {f.Storage} {unit}{full}", 12, f.Days == 0 ? Palette.Danger : Palette.TextSecondary));
|
||||
foreach (var p in f.Partners) _production.AddChild(PartnerLine(w, p, unit, supplier: false));
|
||||
if (f.Partners.Count == 0) _production.AddChild(UiTheme.Text(T("Nessun cliente nella regione"), 12, Palette.TextSecondary));
|
||||
_production.AddChild(PanelKit.Separator());
|
||||
}
|
||||
if (s.Outputs.Count == 0) _production.AddChild(UiTheme.Text(T("Nessuna produzione"), 13, Palette.TextSecondary));
|
||||
_production.AddChild(PanelKit.Pair(T("Magazzino"), PanelKit.Value($"{s.StorageDays} {T("giorni di produzione")}")));
|
||||
_production.AddChild(PanelKit.Pair(T("Prezzo medio realizzato"), PanelKit.Value(s.AveragePrice < 0 ? "—" : Fmt.PricePrecise(s.AveragePrice))));
|
||||
_production.AddChild(PanelKit.Pair(T("Prezzo di vendita"), PanelKit.Value(s.SalePrice < 0 ? "—" : Fmt.PricePrecise(s.SalePrice))));
|
||||
_production.AddChild(PanelKit.Pair(T("Utile annuo stimato"), ColoredValue(s.AnnualProfit.ToString(), s.AnnualProfit.Cents < 0 ? Palette.Danger : Palette.Text)));
|
||||
_production.AddChild(PanelKit.Pair(T("Margine"), ColoredValue(Fmt.Pct(card.Margin, 0), card.Margin < 0 ? Palette.Danger : Palette.Text)));
|
||||
}
|
||||
@@ -430,12 +439,19 @@ public partial class IndustryPanel : VBoxContainer
|
||||
{
|
||||
var buy = new Button { Text = T("Fai un'offerta di acquisto"), CustomMinimumSize = new Vector2(0, 44) };
|
||||
buy.Disabled = !(s.ForSale && s.BuyUnlocked);
|
||||
buy.Pressed += () => _session.Command(new BuyIndustryCommand(new IndustryId(id), card.Valuation), Result);
|
||||
buy.Pressed += () =>
|
||||
{
|
||||
_buyStatus.Text = T("Offerta inviata…");
|
||||
_buyStatus.AddThemeColorOverride("font_color", Palette.TextSecondary);
|
||||
_session.Command(new BuyIndustryCommand(new IndustryId(id), card.Valuation), r => Show(_buyStatus, r));
|
||||
};
|
||||
actions.AddChild(buy);
|
||||
}
|
||||
_chainFooter.AddChild(actions);
|
||||
if (ind.Owner == me)
|
||||
_chainFooter.AddChild(UiTheme.Text(T("L'industria è tua: gli utili entrano nel conto economico della compagnia."), 12, Palette.TextSecondary));
|
||||
_chainFooter.AddChild(Wrapped(T("L'industria è tua: gli utili entrano nel conto economico della compagnia."), 12, Palette.TextSecondary));
|
||||
else if (ind.Owner < 0 && !s.ForSale)
|
||||
_chainFooter.AddChild(Wrapped(T("Industria inattiva: non è in vendita finché non riprende a produrre."), 12, Palette.TextSecondary));
|
||||
else if (!s.ForSale)
|
||||
_chainFooter.AddChild(UiTheme.Text($"{T("Appartiene a")} {Fmt.Company(w, ind.Owner)}: {T("non è in vendita.")}", 12, Palette.TextSecondary));
|
||||
else if (!s.BuyUnlocked)
|
||||
@@ -452,7 +468,7 @@ public partial class IndustryPanel : VBoxContainer
|
||||
_plants.AddChild(PanelKit.Pair(T("Condizione degli impianti"), ColoredValue($"{Fmt.Number(ind.Condition, 0)}%", condColor)));
|
||||
_plants.AddChild(Bar(ind.Condition / 100f, condColor));
|
||||
_plants.AddChild(PanelKit.Pair(T("Moltiplicatore di resa"), PanelKit.Value("×" + Fmt.Number(card.ConditionMultiplier, 2))));
|
||||
_plants.AddChild(UiTheme.Text($"{T("usura")} −{Fmt.Number(card.WearPerDay, 3)} · {T("recupero")} +{Fmt.Number(card.RecoveryPerDay, 3)} {T("al giorno")}", 12, Palette.TextSecondary));
|
||||
_plants.AddChild(Wrapped($"{T("usura")} −{Fmt.Number(card.WearPerDay, 3)} · {T("recupero")} +{Fmt.Number(card.RecoveryPerDay, 3)} {T("al giorno")}", 12, Palette.TextSecondary));
|
||||
_plants.AddChild(PanelKit.Pair(T("Rischio di fermo in un anno"), ColoredValue(Fmt.Pct(card.BreakdownChancePerYear, 0),
|
||||
card.BreakdownChancePerYear > 0.5f ? Palette.Danger : card.BreakdownChancePerYear > 0.1f ? Palette.Amber : Palette.Text)));
|
||||
if (s.ProfitFactor < 1) _plants.AddChild(PanelKit.Pair(T("Fattore di redditività"), PanelKit.Value("×" + Fmt.Number(s.ProfitFactor, 2))));
|
||||
@@ -466,9 +482,9 @@ public partial class IndustryPanel : VBoxContainer
|
||||
var bar = new ScoreBar();
|
||||
bar.Set(s.Score, s.LastScore, s.DowngradeThreshold, s.UpgradeThreshold);
|
||||
_plants.AddChild(bar);
|
||||
_plants.AddChild(UiTheme.Text($"{T("sotto")} {Fmt.Number(s.DowngradeThreshold, 2)} {T("perde un livello")} · {T("sopra")} {Fmt.Number(s.UpgradeThreshold, 2)} {T("per")} {s.UpgradeQuarters} {T("trimestri sale")} ({s.QuartersAbove}/{s.UpgradeQuarters})", 12, Palette.TextSecondary));
|
||||
_plants.AddChild(Wrapped($"{T("sotto")} {Fmt.Number(s.DowngradeThreshold, 2)} {T("perde un livello")} · {T("sopra")} {Fmt.Number(s.UpgradeThreshold, 2)} {T("per")} {s.UpgradeQuarters} {T("trimestri sale")} ({s.QuartersAbove}/{s.UpgradeQuarters})", 12, Palette.TextSecondary));
|
||||
var g = w.Data.Balance.Growth;
|
||||
_plants.AddChild(UiTheme.Text($"{T("spedito")} {Fmt.Pct(s.Shipped, 0)} ×{Fmt.Number(g.WeightShipped, 1)} · {T("copertura")} {Fmt.Pct(s.Coverage, 0)} ×{Fmt.Number(g.WeightCoverage, 1)} · {T("utile")} {Fmt.Pct(s.Profit, 0)} ×{Fmt.Number(g.WeightProfit, 1)}", 12, Palette.TextSecondary));
|
||||
_plants.AddChild(Wrapped($"{T("spedito")} {Fmt.Pct(s.Shipped, 0)} ×{Fmt.Number(g.WeightShipped, 1)} · {T("copertura")} {Fmt.Pct(s.Coverage, 0)} ×{Fmt.Number(g.WeightCoverage, 1)} · {T("utile")} {Fmt.Pct(s.Profit, 0)} ×{Fmt.Number(g.WeightProfit, 1)}", 12, Palette.TextSecondary));
|
||||
if (s.LastScore >= 0) _plants.AddChild(UiTheme.Text($"{T("ultimo trimestre")} {Fmt.Number(s.LastScore, 2)}", 12, Palette.TextSecondary));
|
||||
if (!s.Served)
|
||||
_plants.AddChild(Wrapped(T("Nessun vettore la serve: il livello resta fermo finché una linea non la collega."), 12, Palette.Amber));
|
||||
@@ -484,7 +500,7 @@ public partial class IndustryPanel : VBoxContainer
|
||||
_plants.AddChild(PanelKit.Pair(T("Cassa dell'industria"), PanelKit.Value(card.Cash.ToString())));
|
||||
_plants.AddChild(PanelKit.Pair(T("Costo dell'ammodernamento"), PanelKit.Value(card.UpgradeCost.ToString())));
|
||||
_plants.AddChild(StockRow(T("Ricambi"), ind.SpareParts, card.PartsTarget + card.PartsOrdered, ind.PartsShort ? Palette.Danger : Palette.Amber));
|
||||
_plants.AddChild(UiTheme.Text($"{T("scorta della politica")} {card.PartsTarget} · {T("ordinati in più")} {card.PartsOrdered} · {T("consumo")} {card.PartsPerMonth} {T("al mese")}", 12, Palette.TextSecondary));
|
||||
_plants.AddChild(Wrapped($"{T("scorta della politica")} {card.PartsTarget} · {T("ordinati in più")} {card.PartsOrdered} · {T("consumo")} {card.PartsPerMonth} {T("al mese")}", 12, Palette.TextSecondary));
|
||||
_plants.AddChild(StockRow(T("Macchinari"), ind.Machinery, card.MachineryRequired, Palette.Workers));
|
||||
}
|
||||
|
||||
@@ -505,6 +521,7 @@ public partial class IndustryPanel : VBoxContainer
|
||||
foreach (var c in _controls.GetChildren()) c.QueueFree();
|
||||
_budgetButtons.Clear();
|
||||
_partsOrder = null;
|
||||
_overhaul = _upgrade = null;
|
||||
if (ind is null || ind.Owner != me) return;
|
||||
var w = _session.World;
|
||||
int id = ind.Id;
|
||||
@@ -540,12 +557,16 @@ public partial class IndustryPanel : VBoxContainer
|
||||
var overhaul = new Button { Text = T("Fermo programmato"), SizeFlagsHorizontal = SizeFlags.ExpandFill };
|
||||
overhaul.TooltipText = $"{T("Revisione")}: {m.OverhaulDays} {T("giorni di fermo")}, {m.OverhaulMachineryPerLevel} {T("macchinari per livello")}, {T("personale almeno al")} {Fmt.Pct(m.OverhaulMinStaffCoverage, 0)}; {T("riporta la condizione a 100.")}";
|
||||
overhaul.Pressed += () => _session.Command(new OverhaulIndustryCommand(new IndustryId(id)), Result);
|
||||
overhaul.SetMeta(BaseTooltip, overhaul.TooltipText);
|
||||
actions.AddChild(overhaul);
|
||||
_overhaul = overhaul;
|
||||
var upgrade = UiTheme.Primary(T("Ammoderna"));
|
||||
upgrade.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
upgrade.TooltipText = $"{T("Ammodernamento di livello")}: {m.UpgradeDays} {T("giorni di fermo")}, {m.UpgradeMachineryPerLevel} {T("macchinari per livello")}";
|
||||
upgrade.Pressed += () => _session.Command(new UpgradeIndustryCommand(new IndustryId(id)), Result);
|
||||
upgrade.SetMeta(BaseTooltip, upgrade.TooltipText);
|
||||
actions.AddChild(upgrade);
|
||||
_upgrade = upgrade;
|
||||
_controls.AddChild(actions);
|
||||
}
|
||||
|
||||
@@ -553,6 +574,26 @@ public partial class IndustryPanel : VBoxContainer
|
||||
{
|
||||
for (int i = 0; i < _budgetButtons.Count; i++) _budgetButtons[i].SetPressedNoSignal(i == ind.Budget);
|
||||
if (_partsOrder is not null && card is not null && !_partsOrder.GetLineEdit().HasFocus()) _partsOrder.SetValueNoSignal(card.PartsOrdered);
|
||||
|
||||
// revisione e ammodernamento: il server li rifiuta durante un fermo, con un lavoro già in
|
||||
// programma o (l'ammodernamento) al livello massimo; il pulsante lo dice prima
|
||||
string busy = ind.StoppedUntilDay >= Fmt.Today(_session.World) ? T("L'industria è ferma: riprova a fermo finito.")
|
||||
: ind.PendingWork != 0 ? T("C'è già un lavoro in programma.") : "";
|
||||
var sheet = card?.Sheet;
|
||||
string top = sheet is not null && sheet.Level >= sheet.MaxLevel ? T("Livello massimo raggiunto") : "";
|
||||
Gate(_overhaul, busy);
|
||||
Gate(_upgrade, busy.Length > 0 ? busy : top);
|
||||
}
|
||||
|
||||
private const string BaseTooltip = "base_tooltip";
|
||||
|
||||
/// <summary>Abilita il pulsante, o lo disabilita con il motivo in testa al suggerimento.</summary>
|
||||
private static void Gate(Button? button, string reason)
|
||||
{
|
||||
if (button is null) return;
|
||||
button.Disabled = reason.Length > 0;
|
||||
string tip = button.GetMeta(BaseTooltip, "").AsString();
|
||||
button.TooltipText = reason.Length > 0 ? reason + "\n" + tip : tip;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ pezzi
|
||||
|
||||
@@ -148,21 +148,25 @@ public partial class ChainGraph : Control
|
||||
DrawDashedLine(from, to, Palette.Staff, 2.5f, 3);
|
||||
break;
|
||||
default:
|
||||
DrawDashedLine(from, to, Palette.Border, 2, 8);
|
||||
// grigio leggibile sul fondo della scheda (il bordo dei pannelli sparirebbe)
|
||||
DrawDashedLine(from, to, Palette.TextSecondary, 2, 8);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void Node(Rect2 rect, ChainNode node, bool center)
|
||||
{
|
||||
bool unlinked = !center && node.Edge == ChainEdge.Unlinked;
|
||||
var border = center ? Palette.Amber : node.Edge switch
|
||||
{
|
||||
ChainEdge.Goods => Palette.AmberDark,
|
||||
ChainEdge.Workers => Palette.Workers,
|
||||
ChainEdge.Staff => Palette.Staff,
|
||||
_ => Palette.Border,
|
||||
_ => Palette.Inner,
|
||||
};
|
||||
DrawStyleBox(UiTheme.Box(center ? Palette.AmberDark : Palette.Inner, border, 8, 0), rect);
|
||||
// partner non collegato: bordo tratteggiato grigio, come «Opportunità non collegata» nell'immagine 07
|
||||
if (unlinked) DashedRect(rect.Grow(-1), Palette.TextSecondary);
|
||||
var font = UiTheme.BodyBold;
|
||||
float width = rect.Size.X - 16;
|
||||
DrawString(font, rect.Position + new Vector2(8, center ? 26 : 20), node.Title, HorizontalAlignment.Left, width, center ? 16 : 14,
|
||||
@@ -171,6 +175,15 @@ public partial class ChainGraph : Control
|
||||
if (node.Industry >= 0) _hits.Add((rect, node));
|
||||
}
|
||||
|
||||
private void DashedRect(Rect2 r, Color color)
|
||||
{
|
||||
var (a, b, c, d) = (r.Position, new Vector2(r.End.X, r.Position.Y), r.End, new Vector2(r.Position.X, r.End.Y));
|
||||
DrawDashedLine(a, b, color, 1.5f, 6);
|
||||
DrawDashedLine(b, c, color, 1.5f, 6);
|
||||
DrawDashedLine(c, d, color, 1.5f, 6);
|
||||
DrawDashedLine(d, a, color, 1.5f, 6);
|
||||
}
|
||||
|
||||
public override void _GuiInput(InputEvent e)
|
||||
{
|
||||
if (e is not InputEventMouseButton { Pressed: true, ButtonIndex: MouseButton.Left } click) return;
|
||||
|
||||
@@ -13,19 +13,24 @@ namespace RailEnterprise.Client.Screens;
|
||||
/// <summary>
|
||||
/// 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, sistema, tempo di
|
||||
/// attività, tick al secondo, latenza, client collegati), le partite salvate sul server e i
|
||||
/// pulsanti per riprendere o iniziare. La schermata apre una sessione di prova per leggere lo stato
|
||||
/// e l'elenco dei salvataggi; «Connetti e riprendi» la passa alla partita. Nessuna logica di gioco:
|
||||
/// carica, nuova partita ed elenco sono richieste al server (Load, NewGame, ListSaves).
|
||||
/// 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.
|
||||
/// </summary>
|
||||
public partial class ConnectScreen : Control
|
||||
{
|
||||
private const string SettingsPath = "user://settings.cfg";
|
||||
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;
|
||||
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 };
|
||||
@@ -35,28 +40,44 @@ public partial class ConnectScreen : Control
|
||||
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);
|
||||
private readonly GridContainer _stateRows = new() { Columns = 2 };
|
||||
private readonly ItemList _saves = new() { CustomMinimumSize = new Vector2(0, 150), SizeFlagsVertical = SizeFlags.ExpandFill };
|
||||
private readonly List<string> _saveIds = [];
|
||||
/// <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 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;
|
||||
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;
|
||||
|
||||
/// <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;
|
||||
|
||||
/// <param name="remember">Falso per l'anteprima del collaudo: non legge né scrive le impostazioni.</param>
|
||||
public ConnectScreen(GameData data, bool remember = true)
|
||||
/// <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>
|
||||
@@ -117,7 +138,7 @@ public partial class ConnectScreen : Control
|
||||
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: false);
|
||||
_remoteCard.Pressed += () => SetMode(local: false, start: true);
|
||||
modes.AddChild(_localCard);
|
||||
modes.AddChild(_remoteCard);
|
||||
col.AddChild(modes);
|
||||
@@ -148,20 +169,42 @@ public partial class ConnectScreen : Control
|
||||
// stato del server
|
||||
var state = new PanelContainer();
|
||||
state.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Inner, Palette.Border, 10, 18));
|
||||
var stateCol = PanelKit.Column(10);
|
||||
var stateCol = PanelKit.Column(12);
|
||||
var stateHead = PanelKit.Row(10);
|
||||
stateHead.AddChild(_dot);
|
||||
stateHead.AddChild(_stateTitle);
|
||||
stateCol.AddChild(stateHead);
|
||||
_stateRows.AddThemeConstantOverride("h_separation", 24);
|
||||
_stateRows.AddThemeConstantOverride("v_separation", 6);
|
||||
stateCol.AddChild(_stateRows);
|
||||
_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
|
||||
// partite salvate sul server: nome, data di gioco, quanto tempo fa
|
||||
col.AddChild(UiTheme.Text(T("Partite salvate sul server"), 17, bold: true));
|
||||
_saves.ItemActivated += _ => Resume();
|
||||
_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);
|
||||
@@ -193,6 +236,18 @@ public partial class ConnectScreen : Control
|
||||
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)
|
||||
{
|
||||
@@ -204,7 +259,19 @@ public partial class ConnectScreen : Control
|
||||
remote = (string)cfg.GetValue("server", "mode", "local") == "remote";
|
||||
}
|
||||
}
|
||||
SetMode(local: !remote, start: false);
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -215,6 +282,7 @@ public partial class ConnectScreen : Control
|
||||
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);
|
||||
@@ -235,13 +303,25 @@ public partial class ConnectScreen : Control
|
||||
|
||||
// ------------------------------------------------------------------ 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 (start && local && (_session is null || _session.LocalServer is null)) _ = StartLocal();
|
||||
if (_session is not null && !SessionMatchesMode)
|
||||
{
|
||||
_ = Release();
|
||||
SetStatus("");
|
||||
}
|
||||
if (_remember)
|
||||
{
|
||||
var cfg = new ConfigFile();
|
||||
@@ -249,6 +329,11 @@ public partial class ConnectScreen : Control
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -259,6 +344,7 @@ public partial class ConnectScreen : Control
|
||||
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;
|
||||
}
|
||||
@@ -272,15 +358,18 @@ public partial class ConnectScreen : Control
|
||||
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;
|
||||
Attach(session);
|
||||
_busy = false;
|
||||
if (!Adopt(session, local: true)) return;
|
||||
SetStatus("");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
launcher.Dispose();
|
||||
SetStatus($"{T("Partita locale non avviata")}: {e.Message}", error: true);
|
||||
_busy = false;
|
||||
_resumeAfterConnect = false;
|
||||
if (!_closed) SetStatus($"{T("Partita locale non avviata")}: {e.Message}", error: true);
|
||||
}
|
||||
_busy = false;
|
||||
ShowState();
|
||||
if (!_closed) ShowState();
|
||||
}
|
||||
|
||||
private void SubmitRemote()
|
||||
@@ -288,6 +377,7 @@ public partial class ConnectScreen : Control
|
||||
string address = _address.Text.Trim();
|
||||
if (address.Length == 0)
|
||||
{
|
||||
_resumeAfterConnect = false;
|
||||
SetStatus(T("Indica l'indirizzo del server"), error: true);
|
||||
return;
|
||||
}
|
||||
@@ -295,6 +385,7 @@ public partial class ConnectScreen : Control
|
||||
if (!url.EndsWith("/ws", StringComparison.Ordinal)) url = url.TrimEnd('/') + "/ws";
|
||||
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri))
|
||||
{
|
||||
_resumeAfterConnect = false;
|
||||
SetStatus(T("Indirizzo non valido"), error: true);
|
||||
return;
|
||||
}
|
||||
@@ -321,15 +412,41 @@ public partial class ConnectScreen : Control
|
||||
try
|
||||
{
|
||||
using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));
|
||||
Attach(await GameSession.ConnectAsync(_data, uri, token, uri.Host, cts.Token));
|
||||
var session = await GameSession.ConnectAsync(_data, uri, token, uri.Host, cts.Token);
|
||||
_busy = false;
|
||||
if (!Adopt(session, local: false)) return;
|
||||
SetStatus("");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", error: true);
|
||||
_busy = false;
|
||||
_resumeAfterConnect = false;
|
||||
if (!_closed) SetStatus($"{T("Collegamento non riuscito")}: {e.Message}", error: true);
|
||||
}
|
||||
_busy = false;
|
||||
ShowState();
|
||||
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)
|
||||
@@ -352,17 +469,20 @@ public partial class ConnectScreen : Control
|
||||
await s.DisposeAsync();
|
||||
}
|
||||
|
||||
/// <summary>Consegna la sessione di prova a chi la chiede (Main, alla chiusura del gioco).</summary>
|
||||
/// <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();
|
||||
}
|
||||
|
||||
@@ -372,6 +492,7 @@ public partial class ConnectScreen : Control
|
||||
{
|
||||
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);
|
||||
@@ -398,27 +519,65 @@ public partial class ConnectScreen : Control
|
||||
|
||||
private void Resume()
|
||||
{
|
||||
if (_session is null || _awaitingWelcome is not null) return;
|
||||
int index = _saves.GetSelectedItems() is { Length: > 0 } sel ? sel[0] : 0;
|
||||
if (index <= 0 || index > _saveIds.Count)
|
||||
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;
|
||||
}
|
||||
string id = _saveIds[index - 1];
|
||||
SetStatus($"{T("Caricamento di")} {_saves.GetItemText(index)}…");
|
||||
AwaitWelcome();
|
||||
_session.Send(new Load { SaveId = id });
|
||||
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) 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 });
|
||||
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>
|
||||
@@ -431,9 +590,10 @@ public partial class ConnectScreen : Control
|
||||
_awaitingWelcome = null;
|
||||
Play();
|
||||
}
|
||||
else if (m is Notification { Event.Severity: >= (byte)EventSeverity.Warning } note)
|
||||
else if (m is Notification { Event.Day: < 0 } note)
|
||||
{
|
||||
// caricamento o creazione rifiutati: il server risponde con un avviso
|
||||
// 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);
|
||||
}
|
||||
@@ -459,6 +619,12 @@ public partial class ConnectScreen : Control
|
||||
{
|
||||
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)
|
||||
@@ -468,62 +634,67 @@ public partial class ConnectScreen : Control
|
||||
}
|
||||
else if (_session is not null)
|
||||
{
|
||||
title = $"{T("Collegato a")} {_session.ServerLabel}";
|
||||
title = $"{T("Server raggiungibile")} · {_session.ServerLabel}";
|
||||
dot = Palette.Ok;
|
||||
}
|
||||
else
|
||||
{
|
||||
title = _local ? T("Server locale spento: scegli «Gioca in locale» per avviarlo") : T("Non collegato");
|
||||
title = _local ? T("Server locale spento: «Connetti e riprendi» lo avvia") : T("Non collegato");
|
||||
dot = Palette.TextSecondary;
|
||||
}
|
||||
_stateTitle.Text = title;
|
||||
_dot.Color = dot;
|
||||
var rows = new List<(string, string)>
|
||||
var cells = new (string, string)[]
|
||||
{
|
||||
(T("Versione"), info is null ? "—" : $"{info.Version} · {T("dati compatibili")}"),
|
||||
(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)),
|
||||
(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}"),
|
||||
};
|
||||
if (_stateRows.GetChildCount() != rows.Count * 2)
|
||||
for (int i = 0; i < cells.Length && i < _stateCells.Count; i++)
|
||||
{
|
||||
foreach (var c in _stateRows.GetChildren()) c.QueueFree();
|
||||
foreach (var (caption, _) in rows)
|
||||
{
|
||||
_stateRows.AddChild(UiTheme.Text(caption, 13, Palette.TextSecondary));
|
||||
_stateRows.AddChild(UiTheme.Text("", 13, bold: true));
|
||||
}
|
||||
_stateCells[i].Caption.Text = cells[i].Item1;
|
||||
_stateCells[i].Value.Text = cells[i].Item2;
|
||||
}
|
||||
for (int i = 0; i < rows.Count; i++)
|
||||
{
|
||||
((Label)_stateRows.GetChild(i * 2)).Text = rows[i].Item1;
|
||||
((Label)_stateRows.GetChild(i * 2 + 1)).Text = rows[i].Item2;
|
||||
}
|
||||
bool ready = _session is not null && !_busy && _awaitingWelcome is null;
|
||||
_resume.Disabled = !ready;
|
||||
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;
|
||||
_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;
|
||||
int selected = _saves.GetSelectedItems() is { Length: > 0 } sel ? sel[0] : 0;
|
||||
_saves.Clear();
|
||||
_saveIds.Clear();
|
||||
string company = w.Summary?.CompanyName ?? "";
|
||||
_saves.AddItem($"{T("Partita in corso")} · {company} · {w.Summary?.Date ?? ""}");
|
||||
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))
|
||||
foreach (var s in (_shownSaves?.Saves ?? []).OrderByDescending(s => s.SavedUnixMs).ThenBy(s => s.SaveId, StringComparer.Ordinal))
|
||||
{
|
||||
_saveIds.Add(s.SaveId);
|
||||
string kind = s.Autosave ? $" ({T("automatico")})" : "";
|
||||
_saves.AddItem($"{s.Name}{kind} · {s.GameDate} · {Ago(now - s.SavedUnixMs / 1000.0)}");
|
||||
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;
|
||||
}
|
||||
_saves.Select(Math.Clamp(selected, 0, _saves.ItemCount - 1));
|
||||
// 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)
|
||||
|
||||
@@ -125,6 +125,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()
|
||||
{
|
||||
@@ -210,12 +213,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);
|
||||
@@ -241,6 +239,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);
|
||||
@@ -350,6 +351,7 @@ public partial class GameScreen : Node
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
PlaceToasts();
|
||||
_session.Poll();
|
||||
_disconnected.Visible = !_session.IsOpen;
|
||||
UpdateChronicle();
|
||||
@@ -837,7 +839,18 @@ 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>
|
||||
/// <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).</summary>
|
||||
private void Toast(string text, bool error = false)
|
||||
{
|
||||
var notice = UiTheme.Notice(text);
|
||||
@@ -848,5 +861,6 @@ public partial class GameScreen : Node
|
||||
if (IsInstanceValid(notice)) notice.QueueFree();
|
||||
};
|
||||
while (_toasts.GetChildCount() > 4) _toasts.GetChild(0).QueueFree();
|
||||
PlaceToasts();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user