Merge remote-tracking branch 'origin/main' into claude/f6-tooltip
# Conflicts: # client/RailEnterprise.Client/scripts/Hud/TopBar.cs # docs/STATE.md
This commit is contained in:
commit
69416e7db8
22 files changed
+1750
-14
No files matched your search
@@ -48,6 +48,9 @@ public partial class Toolbar : PanelContainer
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Pulsante di uno strumento (per l'evidenziazione del tutorial).</summary>
|
||||
public Control? ButtonFor(Tool tool) => _buttons.GetValueOrDefault(tool);
|
||||
|
||||
public void Select(Tool tool)
|
||||
{
|
||||
Current = tool;
|
||||
|
||||
@@ -28,6 +28,14 @@ public partial class TopBar : PanelContainer
|
||||
private readonly Label _server = UiTheme.Text("", 14);
|
||||
private readonly ColorRect _serverDot = new() { CustomMinimumSize = new Vector2(10, 10) };
|
||||
private readonly List<Button> _speeds = [];
|
||||
private VBoxContainer? _tierBox;
|
||||
private HBoxContainer? _speedBox;
|
||||
|
||||
/// <summary>Pulsanti della velocità (per l'evidenziazione del tutorial).</summary>
|
||||
public Control? SpeedBox => _speedBox;
|
||||
|
||||
/// <summary>Livello e avanzamento (per l'evidenziazione del tutorial).</summary>
|
||||
public Control? TierBox => _tierBox;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
@@ -66,6 +74,7 @@ public partial class TopBar : PanelContainer
|
||||
speeds.AddChild(b);
|
||||
}
|
||||
row.AddChild(speeds);
|
||||
_speedBox = speeds;
|
||||
row.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
|
||||
row.AddChild(Stat(T("Cassa"), _cash));
|
||||
row.AddChild(Stat(T("Patrimonio netto"), _worth));
|
||||
|
||||
@@ -3,6 +3,7 @@ using RailEnterprise.Client.App;
|
||||
using RailEnterprise.Client.Audio;
|
||||
using RailEnterprise.Client.Net;
|
||||
using RailEnterprise.Client.Screens;
|
||||
using RailEnterprise.Client.Tutorial;
|
||||
using RailEnterprise.Core.Data;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
@@ -15,10 +16,17 @@ namespace RailEnterprise.Client;
|
||||
public partial class Main : Node
|
||||
{
|
||||
private const string SettingsPath = "user://settings.cfg";
|
||||
// cartelle del server locale: la partita del giocatore (la apre la schermata di connessione), la
|
||||
// partita di prova del tutorial e quella del collaudo (queste due ripartono sempre da una partita nuova)
|
||||
private const string LocalDataDir = "user://server";
|
||||
private const string TutorialDataDir = "user://tutorial-server";
|
||||
private const string AutopilotDataDir = "user://autopilot-server";
|
||||
private GameData? _data;
|
||||
private Node? _screen;
|
||||
private GameSession? _session;
|
||||
private string? _autopilot;
|
||||
// tutorial della partita che si apre: casella «Mostra il tutorial» e pulsante «Tutorial» (dal primo passo)
|
||||
private bool _tutorialRequested, _tutorialRestart;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
@@ -76,8 +84,22 @@ public partial class Main : Node
|
||||
Swap(label);
|
||||
return;
|
||||
}
|
||||
// chi aggiorna con una partita locale già salvata non è alla prima partita: casella spenta
|
||||
if (!TutorialSettings.Played && HasLocalSaves()) TutorialSettings.Played = true;
|
||||
var screen = new ConnectScreen(_data, autoStart: autoStart, handover: handover);
|
||||
screen.PlayRequested += ShowGame;
|
||||
screen.PlayRequested += session =>
|
||||
{
|
||||
SetTutorial(screen.ShowTutorial, restart: false);
|
||||
ShowGame(session, screen.GameScope);
|
||||
};
|
||||
screen.TutorialRequested += async () =>
|
||||
{
|
||||
// la partita di prova ha un suo server: quello della sessione di prova della schermata si chiude
|
||||
var trial = screen.TakeSession();
|
||||
if (trial is not null) await trial.DisposeAsync();
|
||||
SetTutorial(true, restart: true);
|
||||
StartLocal(tutorial: true);
|
||||
};
|
||||
screen.AudioRequested += () => AudioManager.Instance?.ShowSettings();
|
||||
screen.LanguageChanged += code =>
|
||||
{
|
||||
@@ -93,8 +115,32 @@ public partial class Main : Node
|
||||
if (status.Length > 0) screen.SetStatus(status, error: true);
|
||||
}
|
||||
|
||||
/// <summary>Collaudo: server locale da zero e subito in partita, senza la schermata di connessione.</summary>
|
||||
private async void StartLocal()
|
||||
private void SetTutorial(bool requested, bool restart)
|
||||
{
|
||||
_tutorialRequested = requested;
|
||||
_tutorialRestart = restart;
|
||||
}
|
||||
|
||||
/// <summary>Vero se la partita locale del giocatore ha già dei salvataggi (file <c>.vfsave</c> del server).</summary>
|
||||
private static bool HasLocalSaves()
|
||||
{
|
||||
try
|
||||
{
|
||||
string saves = System.IO.Path.Combine(ProjectSettings.GlobalizePath(LocalDataDir), "saves");
|
||||
return Directory.Exists(saves) && Directory.EnumerateFiles(saves, "*.vfsave").Any();
|
||||
}
|
||||
catch (IOException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Server locale da zero e subito in partita, senza la schermata di connessione: il collaudo e la partita
|
||||
/// di prova del tutorial, ciascuno nella sua cartella; la partita del giocatore non si tocca.
|
||||
/// </summary>
|
||||
/// <param name="tutorial">pulsante «Tutorial»: partita di prova nuova, con il tutorial dal primo passo</param>
|
||||
private async void StartLocal(bool tutorial = false)
|
||||
{
|
||||
if (_data is null) return;
|
||||
string? server = LocalServerLauncher.FindServer();
|
||||
@@ -103,15 +149,16 @@ public partial class Main : Node
|
||||
ShowMenu(T("Server locale non trovato: compila src/RailEnterprise.Server o imposta RE_SERVER_PATH."), autoStart: false);
|
||||
return;
|
||||
}
|
||||
if (tutorial && _screen is ConnectScreen connect) connect.SetStatus(T("Avvio della partita di prova del tutorial…"));
|
||||
var launcher = new LocalServerLauncher();
|
||||
try
|
||||
{
|
||||
string dataDir = ProjectSettings.GlobalizePath("user://autopilot-server");
|
||||
string dataDir = ProjectSettings.GlobalizePath(tutorial ? TutorialDataDir : AutopilotDataDir);
|
||||
if (Directory.Exists(dataDir)) Directory.Delete(dataDir, true);
|
||||
int port = await launcher.StartAsync(server, dataDir, 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;
|
||||
ShowGame(session);
|
||||
ShowGame(session, tutorial ? "tutorial" : "autopilot");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -120,7 +167,8 @@ public partial class Main : Node
|
||||
}
|
||||
}
|
||||
|
||||
private void ShowGame(GameSession session)
|
||||
/// <param name="scope">origine della partita (locale, tutorial, server in rete) per la voce del tutorial</param>
|
||||
private void ShowGame(GameSession session, string scope)
|
||||
{
|
||||
_session = session;
|
||||
var game = new GameScreen(session);
|
||||
@@ -134,7 +182,14 @@ public partial class Main : Node
|
||||
ShowMenu();
|
||||
};
|
||||
Swap(game);
|
||||
// il pilota automatico non mostra il tutorial: le sue schermate di partita restano quelle di sempre
|
||||
if (_autopilot is not null) game.AddChild(new AutoPilot(game, _autopilot));
|
||||
else
|
||||
{
|
||||
game.AddChild(new TutorialController(game, scope, _tutorialRequested, _tutorialRestart));
|
||||
TutorialSettings.Played = true;
|
||||
_tutorialRestart = false;
|
||||
}
|
||||
}
|
||||
|
||||
public override void _Notification(int what)
|
||||
|
||||
@@ -134,9 +134,13 @@ public sealed class GameSession : IAsyncDisposable
|
||||
/// <summary>Ultima velocità chiesta da questo client (mostrata finché il resoconto non la conferma).</summary>
|
||||
public byte? RequestedSpeed { get; private set; }
|
||||
|
||||
/// <summary>Velocità chieste finora da questo client (il tutorial non conta i cambi fatti da altri giocatori).</summary>
|
||||
public int SpeedRequests { get; private set; }
|
||||
|
||||
public void SetSpeed(byte speed)
|
||||
{
|
||||
RequestedSpeed = speed;
|
||||
SpeedRequests++;
|
||||
Send(new SetSpeed { Speed = speed });
|
||||
}
|
||||
|
||||
|
||||
@@ -29,6 +29,9 @@ public partial class LinesPanel : VBoxContainer
|
||||
|
||||
public event Action? StopsChanged;
|
||||
|
||||
/// <summary>Pulsante «Crea linea» (per l'evidenziazione del tutorial).</summary>
|
||||
public Control? CreateButton { get; }
|
||||
|
||||
public LinesPanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
@@ -54,6 +57,7 @@ public partial class LinesPanel : VBoxContainer
|
||||
RefreshStops();
|
||||
};
|
||||
row.AddChild(create);
|
||||
CreateButton = create;
|
||||
row.AddChild(clear);
|
||||
AddChild(row);
|
||||
_status.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
|
||||
@@ -27,6 +27,9 @@ public partial class TrackPanel : VBoxContainer
|
||||
public Button Build { get; } = UiTheme.Primary(T("Costruisci"));
|
||||
public Button Cancel { get; } = new() { Text = T("Annulla") };
|
||||
|
||||
/// <summary>Grafico del profilo (per l'evidenziazione del tutorial).</summary>
|
||||
public Control Chart => _chart;
|
||||
|
||||
public event Action? OptionsChanged;
|
||||
|
||||
public TrackPanel(ClientWorld world)
|
||||
|
||||
@@ -44,6 +44,11 @@ public partial class TrainsPanel : VBoxContainer
|
||||
|
||||
public event Action<int>? TrainSelected;
|
||||
|
||||
/// <summary>Pulsanti di acquisto, composizione e assegnazione (per l'evidenziazione del tutorial).</summary>
|
||||
public Control? BuyButton { get; }
|
||||
public Control? ComposeButton { get; }
|
||||
public Control? AssignButton { get; }
|
||||
|
||||
public TrainsPanel(GameSession session)
|
||||
{
|
||||
_session = session;
|
||||
@@ -61,6 +66,7 @@ public partial class TrainsPanel : VBoxContainer
|
||||
var buyButton = UiTheme.Primary(T("Compra veicoli"));
|
||||
buyButton.Pressed += Buy;
|
||||
AddChild(buyButton);
|
||||
BuyButton = buyButton;
|
||||
AddChild(UiTheme.Text(T("Veicoli liberi nel deposito (selezione multipla, in ordine)"), 13, Palette.TextSecondary));
|
||||
AddChild(_inDepot);
|
||||
// «perché»: valore del veicolo sotto il puntatore (residuo, valore contabile, rivendita)
|
||||
@@ -73,6 +79,7 @@ public partial class TrainsPanel : VBoxContainer
|
||||
var composeButton = new Button { Text = T("Componi") };
|
||||
composeButton.Pressed += Compose;
|
||||
compose.AddChild(composeButton);
|
||||
ComposeButton = composeButton;
|
||||
var sellButton = new Button { Text = T("Vendi") };
|
||||
sellButton.Pressed += Sell;
|
||||
compose.AddChild(sellButton);
|
||||
@@ -89,6 +96,7 @@ public partial class TrainsPanel : VBoxContainer
|
||||
var assignButton = new Button { Text = T("Assegna") };
|
||||
assignButton.Pressed += Assign;
|
||||
assign.AddChild(assignButton);
|
||||
AssignButton = assignButton;
|
||||
AddChild(assign);
|
||||
var home = new Button { Text = T("Manda al deposito") };
|
||||
home.Pressed += SendHome;
|
||||
|
||||
@@ -2,6 +2,7 @@ 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;
|
||||
@@ -19,7 +20,9 @@ namespace RailEnterprise.Client.Screens;
|
||||
/// 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.
|
||||
/// 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
|
||||
{
|
||||
@@ -50,6 +53,8 @@ public partial class ConnectScreen : Control
|
||||
};
|
||||
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;
|
||||
@@ -70,6 +75,14 @@ public partial class ConnectScreen : Control
|
||||
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>
|
||||
@@ -218,6 +231,23 @@ public partial class ConnectScreen : Control
|
||||
_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);
|
||||
|
||||
@@ -668,6 +698,7 @@ public partial class ConnectScreen : Control
|
||||
_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;
|
||||
}
|
||||
|
||||
@@ -46,6 +46,7 @@ public partial class GameScreen : Node
|
||||
private MarketPanel? _market;
|
||||
private ClimbPanel? _climb;
|
||||
private FinancePanel? _finance;
|
||||
private TrainsPanel? _trainsPanel;
|
||||
// pannelli a tutto schermo (Compagnie e borsa, Mercato globale): coprono mappa e pannello destro, la barra resta
|
||||
private readonly PanelContainer _full = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, Visible = false };
|
||||
private Control? _mapArea;
|
||||
@@ -72,6 +73,12 @@ public partial class GameScreen : Node
|
||||
public GameSession Session => _session;
|
||||
public MapView Map => _map;
|
||||
|
||||
/// <summary>Strumento o pannello aperto dalla barra.</summary>
|
||||
public Tool CurrentTool => _tool;
|
||||
|
||||
/// <summary>Anteprime del tracciato mostrate finora (il tutorial le usa per «guarda il profilo»).</summary>
|
||||
public int TrackPreviews { get; private set; }
|
||||
|
||||
/// <summary>Seleziona uno strumento come dalla barra (anche per il pilota automatico).</summary>
|
||||
public void UseTool(Tool tool) => _toolbar.Select(tool);
|
||||
|
||||
@@ -440,6 +447,7 @@ public partial class GameScreen : Node
|
||||
_market = null;
|
||||
_climb = null;
|
||||
_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 or Tool.Industries;
|
||||
_full.Visible = full;
|
||||
@@ -468,7 +476,7 @@ public partial class GameScreen : Node
|
||||
panel = new HelpPanel(T("Demolisci"), T("Clic su una stazione, un deposito o un binario libero per demolirlo; si recupera una parte del costo."));
|
||||
break;
|
||||
case Tool.Trains:
|
||||
var trains = new TrainsPanel(_session);
|
||||
var trains = _trainsPanel = new TrainsPanel(_session);
|
||||
trains.TrainSelected += id =>
|
||||
{
|
||||
_map.Trains.SelectedTrain = id;
|
||||
@@ -627,6 +635,7 @@ public partial class GameScreen : Node
|
||||
try
|
||||
{
|
||||
_plan = _session.World.PreviewTrack(TrackCommand(pts, 0));
|
||||
TrackPreviews++;
|
||||
_trackPanel.Show(_plan);
|
||||
_trackPanel.SetStatus("");
|
||||
}
|
||||
@@ -794,6 +803,37 @@ public partial class GameScreen : Node
|
||||
return null;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ tutorial
|
||||
|
||||
/// <summary>
|
||||
/// Controllo dell'interfaccia che corrisponde a un elemento del tutorial (vedi
|
||||
/// <c>TutorialScript.KnownTargets</c>); null se in questo momento non c'è (pannello chiuso).
|
||||
/// </summary>
|
||||
public Control? TutorialTarget(string id) => id switch
|
||||
{
|
||||
"map" => _mapArea,
|
||||
"side" => _side,
|
||||
"full" => _full,
|
||||
"topbar:speed" => _top.SpeedBox,
|
||||
"topbar:tier" => _top.TierBox,
|
||||
"track:profile" => _trackPanel?.Chart,
|
||||
"track:build" => _trackPanel?.Build,
|
||||
"trains:buy" => _trainsPanel?.BuyButton,
|
||||
"trains:compose" => _trainsPanel?.ComposeButton,
|
||||
"trains:assign" => _trainsPanel?.AssignButton,
|
||||
"lines:create" => _linesPanel?.CreateButton,
|
||||
_ when id.StartsWith("toolbar:", StringComparison.Ordinal)
|
||||
&& Enum.TryParse<Tool>(id["toolbar:".Length..], ignoreCase: true, out var tool) => _toolbar.ButtonFor(tool),
|
||||
_ => null,
|
||||
};
|
||||
|
||||
/// <summary>Area libera per il riquadro del tutorial: la mappa, o il pannello a tutto schermo se aperto.</summary>
|
||||
public Rect2 TutorialArea()
|
||||
{
|
||||
if (_mapArea is { } map && map.IsVisibleInTree()) return map.GetGlobalRect();
|
||||
return _full.Visible ? _full.GetGlobalRect() : new Rect2();
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ Cronaca finale e osservatore
|
||||
|
||||
/// <summary>Mostra la Cronaca quando arriva: subito se la partita è finita, oppure se l'ha chiesta il giocatore.</summary>
|
||||
@@ -862,8 +902,8 @@ public partial class GameScreen : Node
|
||||
_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)
|
||||
/// <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));
|
||||
|
||||
@@ -0,0 +1,181 @@
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
|
||||
namespace RailEnterprise.Client.Tutorial;
|
||||
|
||||
/// <summary>Stato del tutorial di una partita.</summary>
|
||||
public enum TutorialStatus
|
||||
{
|
||||
/// <summary>In corso su un passo.</summary>
|
||||
Active,
|
||||
/// <summary>Tutti i passi completati o saltati.</summary>
|
||||
Completed,
|
||||
/// <summary>Chiuso dal giocatore prima della fine.</summary>
|
||||
Closed,
|
||||
}
|
||||
|
||||
/// <summary>Cosa fare all'apertura di una partita (vedi <see cref="TutorialMachine.Plan"/>).</summary>
|
||||
public enum TutorialLaunch
|
||||
{
|
||||
/// <summary>Nessun tutorial.</summary>
|
||||
Hidden,
|
||||
/// <summary>Dal primo passo.</summary>
|
||||
StartFresh,
|
||||
/// <summary>Dal passo salvato.</summary>
|
||||
Resume,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Avanzamento salvato nelle impostazioni del client (una voce per partita): passo corrente e stato.
|
||||
/// Il testo è <c>active:<id></c>, <c>completed</c> o <c>closed</c>.
|
||||
/// </summary>
|
||||
public readonly record struct TutorialProgress(string? StepId, TutorialStatus Status)
|
||||
{
|
||||
public string Encode() => Status switch
|
||||
{
|
||||
TutorialStatus.Active => "active:" + (StepId ?? ""),
|
||||
TutorialStatus.Completed => "completed",
|
||||
_ => "closed",
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Chiave della partita nelle impostazioni: origine (<paramref name="scope"/>: partita locale, partita di
|
||||
/// prova del tutorial, server remoto) e i dati del Welcome che non cambiano durante una partita (seme,
|
||||
/// lato della mappa, anno d'inizio, regione, compagnia del giocatore). Non usa l'impronta del terreno né
|
||||
/// la data: cambiano giocando (città che crescono, industrie che aprono e chiudono), e la stessa partita
|
||||
/// ricaricata non ritroverebbe la sua voce. Solo lettere minuscole, cifre e trattini bassi.
|
||||
/// </summary>
|
||||
public static string GameKey(string scope, ulong seed, int sizeKm, int startYear, string regionId, int companyId) =>
|
||||
Clean($"g_{scope}_{seed:x16}_{sizeKm}_{startYear}_{regionId}_{companyId}");
|
||||
|
||||
/// <summary>Chiave della partita dal riepilogo del Welcome (vedi l'altra forma).</summary>
|
||||
public static string GameKey(string scope, WorldSummary s) => GameKey(scope, s.Seed, s.SizeKm, s.StartYear, s.RegionId, s.CompanyId);
|
||||
|
||||
private static string Clean(string text) =>
|
||||
string.Create(text.Length, text, (span, t) =>
|
||||
{
|
||||
for (int i = 0; i < t.Length; i++) span[i] = char.IsAsciiLetterOrDigit(t[i]) ? char.ToLowerInvariant(t[i]) : '_';
|
||||
});
|
||||
|
||||
/// <summary>Legge una voce salvata; null se vuota o non riconosciuta.</summary>
|
||||
public static TutorialProgress? Decode(string? text)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(text)) return null;
|
||||
text = text.Trim();
|
||||
if (text == "completed") return new TutorialProgress(null, TutorialStatus.Completed);
|
||||
if (text == "closed") return new TutorialProgress(null, TutorialStatus.Closed);
|
||||
if (text.StartsWith("active:", StringComparison.Ordinal))
|
||||
{
|
||||
string id = text["active:".Length..];
|
||||
return new TutorialProgress(id.Length > 0 ? id : null, TutorialStatus.Active);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Macchina a stati dei passi: un passo alla volta, completato quando la sua condizione è vera sui fatti
|
||||
/// osservati (<see cref="Update"/>), oppure con Avanti (passi informativi), Salta passo o Chiudi. I contatori
|
||||
/// con <c>increase</c> si confrontano con i fatti di quando il passo precedente si è completato da sé (così
|
||||
/// un'azione arrivata subito dopo conta per il passo nuovo), oppure, dopo Avanti, Salta, una ripresa o una
|
||||
/// ripartenza, con i fatti al primo aggiornamento del passo. Non decide regole di gioco: guarda soltanto ciò
|
||||
/// che il client ha già ricevuto.
|
||||
/// </summary>
|
||||
public sealed class TutorialMachine
|
||||
{
|
||||
private TutorialFacts? _baseline;
|
||||
|
||||
public TutorialMachine(TutorialScript script)
|
||||
{
|
||||
if (script.Steps.Count == 0) throw new ArgumentException("Copione del tutorial senza passi", nameof(script));
|
||||
Script = script;
|
||||
}
|
||||
|
||||
public TutorialScript Script { get; }
|
||||
|
||||
/// <summary>Indice del passo corrente (uguale al numero di passi a tutorial completato).</summary>
|
||||
public int Index { get; private set; }
|
||||
|
||||
public TutorialStatus Status { get; private set; } = TutorialStatus.Active;
|
||||
|
||||
public TutorialStep? Current => Status == TutorialStatus.Active && Index < Script.Steps.Count ? Script.Steps[Index] : null;
|
||||
|
||||
public bool IsLast => Index == Script.Steps.Count - 1;
|
||||
|
||||
/// <summary>Avanzamento da salvare.</summary>
|
||||
public TutorialProgress Progress => new(Current?.Id, Status);
|
||||
|
||||
/// <summary>
|
||||
/// Decide se mostrare il tutorial all'apertura di una partita. <paramref name="restart"/> (pulsante «Tutorial»
|
||||
/// della schermata di connessione) riparte sempre dal primo passo; un tutorial in corso in quella partita si riprende; uno
|
||||
/// completato o chiuso resta nascosto, a meno che il giocatore l'abbia chiesto con la casella «Mostra il
|
||||
/// tutorial» (attiva da sé solo alla prima partita: spuntarla dopo è una richiesta esplicita, e una
|
||||
/// partita nuova con lo stesso seme ha la stessa chiave di una vecchia); senza voce salvata si mostra solo
|
||||
/// se chiesto.
|
||||
/// </summary>
|
||||
public static TutorialLaunch Plan(bool requested, bool restart, TutorialProgress? saved)
|
||||
{
|
||||
if (restart) return TutorialLaunch.StartFresh;
|
||||
if (saved is { Status: TutorialStatus.Active }) return TutorialLaunch.Resume;
|
||||
return requested ? TutorialLaunch.StartFresh : TutorialLaunch.Hidden;
|
||||
}
|
||||
|
||||
/// <summary>Riparte dal primo passo.</summary>
|
||||
public void Restart() => GoTo(0);
|
||||
|
||||
/// <summary>Riprende da un avanzamento salvato; un passo che non c'è più fa ripartire dall'inizio.</summary>
|
||||
public void Restore(TutorialProgress progress)
|
||||
{
|
||||
switch (progress.Status)
|
||||
{
|
||||
case TutorialStatus.Active:
|
||||
GoTo(Math.Max(0, Script.IndexOf(progress.StepId)));
|
||||
break;
|
||||
case TutorialStatus.Completed:
|
||||
Index = Script.Steps.Count;
|
||||
Status = TutorialStatus.Completed;
|
||||
break;
|
||||
default:
|
||||
Status = TutorialStatus.Closed;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Valuta il passo corrente sui fatti; se la condizione è vera passa al successivo e restituisce true.</summary>
|
||||
public bool Update(TutorialFacts facts)
|
||||
{
|
||||
if (Current is not { } step) return false;
|
||||
_baseline ??= facts.Clone();
|
||||
if (step.Done is null || !step.Done.IsMet(facts, _baseline)) return false;
|
||||
Advance();
|
||||
// la base del passo nuovo sono i fatti di adesso, non quelli del suo primo aggiornamento: un comando
|
||||
// riuscito arrivato prima di quell'aggiornamento conta per il passo nuovo
|
||||
if (Status == TutorialStatus.Active) _baseline = facts.Clone();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Avanti: chiude un passo informativo (sugli altri equivale a <see cref="Skip"/>).</summary>
|
||||
public void Next() => Advance();
|
||||
|
||||
/// <summary>Salta il passo corrente.</summary>
|
||||
public void Skip() => Advance();
|
||||
|
||||
/// <summary>Chiude il tutorial; si potrà riaprire con F1 o dalla schermata iniziale.</summary>
|
||||
public void Close()
|
||||
{
|
||||
if (Status == TutorialStatus.Active) Status = TutorialStatus.Closed;
|
||||
_baseline = null;
|
||||
}
|
||||
|
||||
private void Advance()
|
||||
{
|
||||
if (Status != TutorialStatus.Active) return;
|
||||
GoTo(Index + 1);
|
||||
}
|
||||
|
||||
private void GoTo(int index)
|
||||
{
|
||||
_baseline = null;
|
||||
Index = Math.Clamp(index, 0, Script.Steps.Count);
|
||||
Status = Index >= Script.Steps.Count ? TutorialStatus.Completed : TutorialStatus.Active;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
using RailEnterprise.Core.Commands;
|
||||
|
||||
namespace RailEnterprise.Client.Tutorial;
|
||||
|
||||
/// <summary>
|
||||
/// Copione del tutorial guidato (<c>assets/tutorial/tutorial.json</c>, ADR 0023): l'elenco ordinato dei
|
||||
/// passi. È un file dati del client, non del motore: non cambia regole né salvataggi. Questa classe e le
|
||||
/// altre di <c>Tutorial/Logic</c> non dipendono da Godot e si provano nel harness dei test.
|
||||
/// </summary>
|
||||
public sealed class TutorialScript
|
||||
{
|
||||
/// <summary>Versione del formato del file (oggi 1).</summary>
|
||||
public int Version { get; init; } = 1;
|
||||
|
||||
public List<TutorialStep> Steps { get; init; } = [];
|
||||
|
||||
/// <summary>Indice del passo con l'id indicato, -1 se non c'è.</summary>
|
||||
public int IndexOf(string? id) => id is null ? -1 : Steps.FindIndex(s => s?.Id == id);
|
||||
|
||||
/// <summary>Legge il copione dal testo JSON (commenti e virgole finali ammessi, campi sconosciuti rifiutati).</summary>
|
||||
public static TutorialScript Parse(string json) =>
|
||||
JsonSerializer.Deserialize(json, TutorialJsonContext.Default.TutorialScript)
|
||||
?? throw new JsonException("Copione del tutorial vuoto");
|
||||
|
||||
/// <summary>
|
||||
/// Elementi dell'interfaccia che un passo può evidenziare. Il client li risolve nei controlli
|
||||
/// (<c>GameScreen.TutorialTarget</c>); se un elemento non è visibile in quel momento si usa il
|
||||
/// ripiego del passo, altrimenti non si evidenzia nulla.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<string> KnownTargets = BuildTargets();
|
||||
|
||||
private static List<string> BuildTargets()
|
||||
{
|
||||
var list = new List<string> { "map", "side", "full", "topbar:speed", "topbar:tier", "track:profile", "track:build", "trains:buy", "trains:compose", "trains:assign", "lines:create" };
|
||||
foreach (string panel in TutorialFacts.KnownPanels)
|
||||
{
|
||||
if (panel != TutorialFacts.NoPanel) list.Add("toolbar:" + panel);
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Controlla il copione: elenco e passi presenti (il JSON ammette <c>null</c>), id unici, testi presenti,
|
||||
/// elementi, contatori e pannelli noti. Restituisce gli errori in italiano.
|
||||
/// </summary>
|
||||
public List<string> Validate()
|
||||
{
|
||||
var errors = new List<string>();
|
||||
if (Version != 1) errors.Add($"versione {Version} non supportata");
|
||||
if (Steps is null)
|
||||
{
|
||||
errors.Add("elenco dei passi mancante");
|
||||
return errors;
|
||||
}
|
||||
if (Steps.Count == 0) errors.Add("nessun passo");
|
||||
var ids = new HashSet<string>(StringComparer.Ordinal);
|
||||
for (int i = 0; i < Steps.Count; i++)
|
||||
{
|
||||
var step = Steps[i];
|
||||
if (step is null)
|
||||
{
|
||||
errors.Add($"passo n. {i + 1} nullo");
|
||||
continue;
|
||||
}
|
||||
string where = $"passo «{step.Id}»";
|
||||
if (string.IsNullOrWhiteSpace(step.Id)) errors.Add("passo senza id");
|
||||
else if (!ids.Add(step.Id)) errors.Add($"{where}: id ripetuto");
|
||||
if (string.IsNullOrWhiteSpace(step.Title)) errors.Add($"{where}: titolo vuoto");
|
||||
if (string.IsNullOrWhiteSpace(step.Text)) errors.Add($"{where}: testo vuoto");
|
||||
if (step.Highlight is { } h && !KnownTargets.Contains(h)) errors.Add($"{where}: elemento da evidenziare sconosciuto «{h}»");
|
||||
if (step.Fallback is { } f && !KnownTargets.Contains(f)) errors.Add($"{where}: ripiego sconosciuto «{f}»");
|
||||
if (step.Fallback is not null && step.Highlight is null) errors.Add($"{where}: ripiego senza elemento principale");
|
||||
step.Done?.Validate(where, errors);
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Passo del tutorial: testi (chiavi di traduzione), elemento da evidenziare, condizione di completamento.</summary>
|
||||
public sealed class TutorialStep
|
||||
{
|
||||
public required string Id { get; init; }
|
||||
|
||||
/// <summary>Chiave del titolo per <c>T()</c> (testo italiano).</summary>
|
||||
public required string Title { get; init; }
|
||||
|
||||
/// <summary>Chiave del testo per <c>T()</c> (testo italiano).</summary>
|
||||
public required string Text { get; init; }
|
||||
|
||||
/// <summary>Elemento dell'interfaccia da evidenziare (vedi <see cref="TutorialScript.KnownTargets"/>), facoltativo.</summary>
|
||||
public string? Highlight { get; init; }
|
||||
|
||||
/// <summary>Elemento da evidenziare quando il principale non è visibile (per esempio il pulsante che apre il pannello).</summary>
|
||||
public string? Fallback { get; init; }
|
||||
|
||||
/// <summary>Condizione osservabile che completa il passo; senza condizione il passo è informativo (pulsante Avanti).</summary>
|
||||
public TutorialCondition? Done { get; init; }
|
||||
|
||||
[JsonIgnore]
|
||||
public bool IsInformative => Done is null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Condizione di completamento, valutata su fatti semplici che il client osserva (<see cref="TutorialFacts"/>).
|
||||
/// Ha una sola forma tra: contatore (<c>counter</c> con <c>atLeast</c>, <c>atMost</c> e/o <c>increase</c>),
|
||||
/// pannello aperto (<c>panel</c>), tutte (<c>all</c>) o almeno una (<c>any</c>) di altre condizioni.
|
||||
/// <c>increase</c> confronta il contatore con il suo valore all'inizio del passo.
|
||||
/// </summary>
|
||||
public sealed class TutorialCondition
|
||||
{
|
||||
public string? Counter { get; init; }
|
||||
public double? AtLeast { get; init; }
|
||||
public double? AtMost { get; init; }
|
||||
public double? Increase { get; init; }
|
||||
public string? Panel { get; init; }
|
||||
public List<TutorialCondition>? All { get; init; }
|
||||
public List<TutorialCondition>? Any { get; init; }
|
||||
|
||||
/// <summary>Vera se i fatti di adesso soddisfano la condizione; <paramref name="baseline"/> sono i fatti all'inizio del passo.</summary>
|
||||
public bool IsMet(TutorialFacts now, TutorialFacts baseline)
|
||||
{
|
||||
if (All is not null) return All.TrueForAll(c => c.IsMet(now, baseline));
|
||||
if (Any is not null) return Any.Exists(c => c.IsMet(now, baseline));
|
||||
if (Panel is not null) return now.Panel == Panel;
|
||||
if (Counter is null) return false;
|
||||
double value = now.Get(Counter);
|
||||
if (AtLeast is { } min && value < min) return false;
|
||||
if (AtMost is { } max && value > max) return false;
|
||||
if (Increase is { } inc && value - baseline.Get(Counter) < inc) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
internal void Validate(string where, List<string> errors)
|
||||
{
|
||||
int forms = (Counter is not null ? 1 : 0) + (Panel is not null ? 1 : 0) + (All is not null ? 1 : 0) + (Any is not null ? 1 : 0);
|
||||
if (forms != 1)
|
||||
{
|
||||
errors.Add($"{where}: la condizione deve avere una sola forma tra counter, panel, all e any");
|
||||
return;
|
||||
}
|
||||
if (Counter is not null)
|
||||
{
|
||||
if (AtLeast is null && AtMost is null && Increase is null) errors.Add($"{where}: contatore «{Counter}» senza atLeast, atMost o increase");
|
||||
if (!TutorialFacts.IsKnownCounter(Counter)) errors.Add($"{where}: contatore sconosciuto «{Counter}»");
|
||||
}
|
||||
else if (AtLeast is not null || AtMost is not null || Increase is not null)
|
||||
{
|
||||
errors.Add($"{where}: atLeast, atMost e increase valgono solo con counter");
|
||||
}
|
||||
if (Panel is not null && !TutorialFacts.KnownPanels.Contains(Panel)) errors.Add($"{where}: pannello sconosciuto «{Panel}»");
|
||||
foreach (var list in new[] { All, Any })
|
||||
{
|
||||
if (list is null) continue;
|
||||
if (list.Count == 0) errors.Add($"{where}: elenco di condizioni vuoto");
|
||||
foreach (var c in list)
|
||||
{
|
||||
if (c is null) errors.Add($"{where}: condizione nulla");
|
||||
else c.Validate(where, errors);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Fatti osservati dal client: contatori (entità della compagnia, comandi riusciti, azioni sulla mappa) e pannello aperto.</summary>
|
||||
public sealed class TutorialFacts
|
||||
{
|
||||
/// <summary>Pannello «nessuno» (barra degli strumenti senza selezione).</summary>
|
||||
public const string NoPanel = "none";
|
||||
|
||||
/// <summary>Prefisso dei contatori dei comandi riusciti: <c>cmd:</c> + nome di <see cref="CommandType"/>.</summary>
|
||||
public const string CommandPrefix = "cmd:";
|
||||
|
||||
/// <summary>Pannelli della barra degli strumenti, con i nomi in minuscolo dell'enumerazione <c>Hud.Tool</c>.</summary>
|
||||
public static readonly IReadOnlyList<string> KnownPanels =
|
||||
[
|
||||
NoPanel, "track", "station", "signal", "depot", "trains", "lines", "maintenance", "employment", "industries", "market", "companies", "climb", "finance", "demolish",
|
||||
];
|
||||
|
||||
/// <summary>
|
||||
/// Contatori osservati: entità della compagnia nella copia locale (stazioni, depositi, archi, archi in
|
||||
/// funzione, archi in cantiere, locomotive, carri e carrozze, treni, linee, treni in linea), azioni del
|
||||
/// giocatore sulla mappa (spostamento in schermate, zoom in unità logaritmiche, cambi di velocità) e
|
||||
/// anteprime valide del tracciato.
|
||||
/// </summary>
|
||||
public static readonly IReadOnlyList<string> KnownCounters =
|
||||
[
|
||||
"stations", "depots", "edges", "edgesActive", "edgesBuilding", "locomotives", "cars", "trains", "lines", "trainsOnLine",
|
||||
"mapPan", "mapZoom", "speedChanges", "trackPreviews",
|
||||
];
|
||||
|
||||
public Dictionary<string, double> Counters { get; } = new(StringComparer.Ordinal);
|
||||
|
||||
public string Panel { get; set; } = NoPanel;
|
||||
|
||||
public double Get(string counter) => Counters.TryGetValue(counter, out double v) ? v : 0;
|
||||
|
||||
public void Set(string counter, double value) => Counters[counter] = value;
|
||||
|
||||
public void Add(string counter, double amount) => Counters[counter] = Get(counter) + amount;
|
||||
|
||||
/// <summary>Nome del contatore di un tipo di comando riuscito.</summary>
|
||||
public static string CommandCounter(CommandType type) => CommandPrefix + type;
|
||||
|
||||
public static bool IsKnownCounter(string name) =>
|
||||
KnownCounters.Contains(name)
|
||||
|| (name.StartsWith(CommandPrefix, StringComparison.Ordinal) && Enum.TryParse<CommandType>(name[CommandPrefix.Length..], ignoreCase: false, out var t)
|
||||
&& Enum.IsDefined(t) && t.ToString() == name[CommandPrefix.Length..]);
|
||||
|
||||
public TutorialFacts Clone()
|
||||
{
|
||||
var copy = new TutorialFacts { Panel = Panel };
|
||||
foreach (var (k, v) in Counters) copy.Counters[k] = v;
|
||||
return copy;
|
||||
}
|
||||
}
|
||||
|
||||
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, PropertyNameCaseInsensitive = true,
|
||||
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow, ReadCommentHandling = JsonCommentHandling.Skip,
|
||||
AllowTrailingCommas = true)]
|
||||
[JsonSerializable(typeof(TutorialScript))]
|
||||
internal sealed partial class TutorialJsonContext : JsonSerializerContext;
|
||||
@@ -0,0 +1,312 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.Screens;
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Data;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Protocol;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Tutorial;
|
||||
|
||||
/// <summary>
|
||||
/// Collega il tutorial alla partita: raccoglie i fatti che il client osserva (entità della compagnia nella
|
||||
/// copia locale, esiti dei comandi, pannello aperto, camera, velocità chiesta da questo client, anteprime del
|
||||
/// tracciato), fa avanzare <see cref="TutorialMachine"/>, aggiorna <see cref="TutorialOverlay"/> e salva
|
||||
/// l'avanzamento per partita. Non invia comandi e non decide regole. F1 riapre o nasconde il tutorial.
|
||||
/// </summary>
|
||||
public partial class TutorialController : Node
|
||||
{
|
||||
private const string ScriptPath = "res://assets/tutorial/tutorial.json";
|
||||
private const double FactsInterval = 0.2;
|
||||
|
||||
private readonly GameScreen _game;
|
||||
private readonly string _scope;
|
||||
private bool _requested;
|
||||
private bool _restart;
|
||||
private readonly CanvasLayer _layer = new() { Layer = 3 };
|
||||
private readonly TutorialOverlay _overlay = new();
|
||||
private readonly TutorialFacts _facts = new();
|
||||
private readonly Dictionary<string, VehicleKind> _vehicleKinds = [];
|
||||
private TutorialMachine? _machine;
|
||||
private string? _loadError;
|
||||
private string _gameKey = "";
|
||||
private bool _visible;
|
||||
private int _shownIndex = -1;
|
||||
// controllo già portato in vista nel suo contenitore a scorrimento per il passo mostrato
|
||||
private Control? _scrolledTo;
|
||||
private double _sinceFacts = FactsInterval;
|
||||
private Vector2? _lastCamera;
|
||||
private float _lastZoom;
|
||||
private int _lastSpeedRequests;
|
||||
|
||||
/// <param name="scope">origine della partita (locale, tutorial, server remoto) per la chiave dell'avanzamento</param>
|
||||
/// <param name="requested">casella «Mostra il tutorial» della schermata di connessione</param>
|
||||
/// <param name="restart">pulsante «Tutorial» della schermata di connessione: dal primo passo anche se già fatto</param>
|
||||
public TutorialController(GameScreen game, string scope, bool requested, bool restart)
|
||||
{
|
||||
_game = game;
|
||||
_scope = scope;
|
||||
_requested = requested;
|
||||
_restart = restart;
|
||||
}
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
try
|
||||
{
|
||||
using var file = Godot.FileAccess.Open(ScriptPath, Godot.FileAccess.ModeFlags.Read)
|
||||
?? throw new FileNotFoundException(ScriptPath);
|
||||
var script = TutorialScript.Parse(file.GetAsText());
|
||||
var errors = script.Validate();
|
||||
if (errors.Count > 0) throw new InvalidDataException(string.Join("; ", errors));
|
||||
_machine = new TutorialMachine(script);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
_loadError = e.Message;
|
||||
GD.PushWarning($"Tutorial non disponibile: {e.Message}");
|
||||
// chi l'ha chiesto deve saperlo: altrimenti vedrebbe una partita normale senza spiegazioni
|
||||
if (_requested || _restart) ReportUnavailable();
|
||||
return;
|
||||
}
|
||||
foreach (var v in _game.Session.World.Data.Vehicles) _vehicleKinds[v.Id] = v.Kind;
|
||||
AddChild(_layer);
|
||||
_layer.AddChild(_overlay);
|
||||
_overlay.NextPressed += () => Act(m => m.Next());
|
||||
_overlay.SkipPressed += () => Act(m => m.Skip());
|
||||
_overlay.ClosePressed += () => Act(m => m.Close());
|
||||
_game.Session.MessageApplied += OnMessage;
|
||||
_lastSpeedRequests = _game.Session.SpeedRequests;
|
||||
OpenForGame();
|
||||
}
|
||||
|
||||
public override void _ExitTree() => _game.Session.MessageApplied -= OnMessage;
|
||||
|
||||
private void ReportUnavailable() => _game.Toast(string.Format(T("Tutorial non disponibile: {0}"), _loadError), error: true);
|
||||
|
||||
/// <summary>All'avvio e a ogni Welcome (nuova partita, caricamento): chiave della partita e piano di apertura.</summary>
|
||||
private void OpenForGame()
|
||||
{
|
||||
if (_machine is null || _game.Session.World.Summary is not { } s) return;
|
||||
_gameKey = TutorialProgress.GameKey(_scope, s);
|
||||
var saved = TutorialSettings.Read(_gameKey);
|
||||
switch (TutorialMachine.Plan(_requested, _restart, saved))
|
||||
{
|
||||
case TutorialLaunch.StartFresh:
|
||||
_machine.Restart();
|
||||
Save();
|
||||
_visible = true;
|
||||
break;
|
||||
case TutorialLaunch.Resume:
|
||||
_machine.Restore(saved!.Value);
|
||||
_visible = true;
|
||||
break;
|
||||
default:
|
||||
if (saved is { } p) _machine.Restore(p);
|
||||
else _machine.Close();
|
||||
_visible = false;
|
||||
break;
|
||||
}
|
||||
// casella e pulsante della schermata di connessione valgono per la partita aperta, non per le successive (Nuova partita+)
|
||||
_requested = _restart = false;
|
||||
_lastCamera = null;
|
||||
_shownIndex = -1;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
private void OnMessage(IMessage message)
|
||||
{
|
||||
switch (message)
|
||||
{
|
||||
case Welcome:
|
||||
OpenForGame();
|
||||
break;
|
||||
case CommandResultMessage { Ok: true } r:
|
||||
_facts.Add(TutorialFacts.CommandCounter((CommandType)r.Type), 1);
|
||||
// subito, non al prossimo giro: due esiti ravvicinati contano per due passi diversi
|
||||
Evaluate();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void Act(Action<TutorialMachine> action)
|
||||
{
|
||||
if (_machine is null) return;
|
||||
action(_machine);
|
||||
Save();
|
||||
if (_machine.Status != TutorialStatus.Active) _visible = false;
|
||||
Refresh();
|
||||
}
|
||||
|
||||
private void Save()
|
||||
{
|
||||
if (_machine is not null && _gameKey.Length > 0) TutorialSettings.Save(_gameKey, _machine.Progress);
|
||||
}
|
||||
|
||||
public override void _UnhandledKeyInput(InputEvent e)
|
||||
{
|
||||
if (e is not InputEventKey { Pressed: true, Echo: false, Keycode: Key.F1 }) return;
|
||||
if (_machine is null)
|
||||
{
|
||||
if (_loadError is not null) ReportUnavailable();
|
||||
return;
|
||||
}
|
||||
if (_visible)
|
||||
{
|
||||
// F1 nasconde soltanto: il tutorial in corso resta salvato
|
||||
_visible = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// riapre dal passo salvato, o dall'inizio se era chiuso o completato
|
||||
if (_machine.Status != TutorialStatus.Active) _machine.Restart();
|
||||
_visible = true;
|
||||
_shownIndex = -1;
|
||||
Save();
|
||||
}
|
||||
Refresh();
|
||||
GetViewport().SetInputAsHandled();
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (_machine is null) return;
|
||||
TrackCameraAndSpeed();
|
||||
_sinceFacts += delta;
|
||||
if (_sinceFacts >= FactsInterval)
|
||||
{
|
||||
_sinceFacts = 0;
|
||||
CollectWorldFacts();
|
||||
Evaluate();
|
||||
}
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>Valuta il passo corrente sui fatti raccolti; se si completa salva e mostra «Fatto».</summary>
|
||||
private void Evaluate()
|
||||
{
|
||||
if (_machine is null || !_visible) return;
|
||||
string? title = _machine.Current is { } step ? T(step.Title) : null;
|
||||
if (!_machine.Update(_facts)) return;
|
||||
Save();
|
||||
if (title is not null) _overlay.Flash(title);
|
||||
// completato l'ultimo passo il riquadro si chiude
|
||||
if (_machine.Status != TutorialStatus.Active) _visible = false;
|
||||
}
|
||||
|
||||
/// <summary>Spostamento della camera (in schermate), zoom (in logaritmi) e velocità chieste da questo client, sommati.</summary>
|
||||
private void TrackCameraAndSpeed()
|
||||
{
|
||||
var map = _game.Map;
|
||||
var camera = map.Camera.Position;
|
||||
float zoom = map.Zoom;
|
||||
if (_lastCamera is { } last && zoom > 0 && _lastZoom > 0)
|
||||
{
|
||||
if (Math.Abs(zoom - _lastZoom) > 1e-6)
|
||||
{
|
||||
// lo zoom attorno al cursore sposta anche la camera: non è uno spostamento
|
||||
_facts.Add("mapZoom", Math.Abs(Math.Log(zoom / _lastZoom)));
|
||||
}
|
||||
else
|
||||
{
|
||||
float screen = map.GetViewportRect().Size.X / zoom;
|
||||
if (screen > 0) _facts.Add("mapPan", camera.DistanceTo(last) / screen);
|
||||
}
|
||||
}
|
||||
_lastCamera = camera;
|
||||
_lastZoom = zoom;
|
||||
|
||||
// solo le richieste di questo client: un altro giocatore che cambia la velocità del server non conta
|
||||
int requests = _game.Session.SpeedRequests;
|
||||
if (requests != _lastSpeedRequests) _facts.Add("speedChanges", requests - _lastSpeedRequests);
|
||||
_lastSpeedRequests = requests;
|
||||
}
|
||||
|
||||
/// <summary>Entità della compagnia nella copia locale, pannello aperto, anteprime del tracciato.</summary>
|
||||
private void CollectWorldFacts()
|
||||
{
|
||||
var w = _game.Session.World;
|
||||
int me = w.Summary?.CompanyId ?? -1;
|
||||
int edges = 0, active = 0, locos = 0, cars = 0, trains = 0, onLine = 0;
|
||||
foreach (var e in w.Edges.Values)
|
||||
{
|
||||
if (e.Owner != me) continue;
|
||||
edges++;
|
||||
if (e.State == (byte)EdgeState.Active) active++;
|
||||
}
|
||||
foreach (var v in w.Vehicles.Values)
|
||||
{
|
||||
if (v.Owner != me || !_vehicleKinds.TryGetValue(v.Type, out var kind)) continue;
|
||||
if (kind == VehicleKind.Locomotive) locos++;
|
||||
else cars++;
|
||||
}
|
||||
foreach (var t in w.Trains.Values)
|
||||
{
|
||||
if (t.Owner != me) continue;
|
||||
trains++;
|
||||
if (t.Line >= 0) onLine++;
|
||||
}
|
||||
_facts.Set("stations", w.Stations.Values.Count(s => s.Owner == me));
|
||||
_facts.Set("depots", w.Depots.Values.Count(d => d.Owner == me));
|
||||
_facts.Set("edges", edges);
|
||||
_facts.Set("edgesActive", active);
|
||||
// i cantieri sono gli archi non ancora in funzione (dismessi compresi: non bloccano un tutorial nuovo)
|
||||
_facts.Set("edgesBuilding", w.Edges.Values.Count(e => e.Owner == me && e.State == (byte)EdgeState.UnderConstruction));
|
||||
_facts.Set("locomotives", locos);
|
||||
_facts.Set("cars", cars);
|
||||
_facts.Set("trains", trains);
|
||||
_facts.Set("lines", w.Lines.Values.Count(l => l.Owner == me));
|
||||
_facts.Set("trainsOnLine", onLine);
|
||||
_facts.Set("trackPreviews", _game.TrackPreviews);
|
||||
_facts.Panel = _game.CurrentTool.ToString().ToLowerInvariant();
|
||||
}
|
||||
|
||||
/// <summary>Testi del passo corrente, posizione del riquadro ed elemento evidenziato.</summary>
|
||||
private void Refresh()
|
||||
{
|
||||
if (_machine is null) return;
|
||||
bool show = _visible && _machine.Current is not null && !_game.ChronicleVisible && _game.Session.IsOpen;
|
||||
_overlay.Visible = show;
|
||||
if (!show) return;
|
||||
var step = _machine.Current!;
|
||||
if (_shownIndex != _machine.Index)
|
||||
{
|
||||
_shownIndex = _machine.Index;
|
||||
_scrolledTo = null;
|
||||
_overlay.ShowStep(_machine.Index + 1, _machine.Script.Steps.Count, T(step.Title), T(step.Text), step.IsInformative, _machine.IsLast);
|
||||
}
|
||||
_overlay.Area = _game.TutorialArea();
|
||||
Rect2? target = null;
|
||||
if (step.Highlight is { } h) target = VisibleRect(_game.TutorialTarget(h));
|
||||
if (target is null && step.Fallback is { } f) target = VisibleRect(_game.TutorialTarget(f));
|
||||
_overlay.Target = target;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rettangolo visibile di un controllo, ritagliato dai contenitori a scorrimento che lo contengono (barra
|
||||
/// degli strumenti, pannello destro); null se il controllo non c'è o è del tutto fuori vista, così si usa
|
||||
/// il ripiego e il contorno non finisce su ciò che sta sotto. La prima volta in un passo il controllo
|
||||
/// coperto dallo scorrimento si porta in vista.
|
||||
/// </summary>
|
||||
private Rect2? VisibleRect(Control? c)
|
||||
{
|
||||
if (c is null || !IsInstanceValid(c) || !c.IsVisibleInTree() || c.Size.X <= 0) return null;
|
||||
if (_scrolledTo != c)
|
||||
{
|
||||
_scrolledTo = c;
|
||||
for (var p = c.GetParent(); p is not null; p = p.GetParent())
|
||||
{
|
||||
if (p is ScrollContainer scroll) scroll.EnsureControlVisible(c);
|
||||
}
|
||||
}
|
||||
var rect = c.GetGlobalRect();
|
||||
for (var p = c.GetParent(); p is not null; p = p.GetParent())
|
||||
{
|
||||
if (p is not ScrollContainer scroll) continue;
|
||||
rect = rect.Intersection(scroll.GetGlobalRect());
|
||||
if (rect.Size.X < 1 || rect.Size.Y < 1) return null;
|
||||
}
|
||||
return rect;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
using Godot;
|
||||
using RailEnterprise.Client.App;
|
||||
using static RailEnterprise.Client.App.Localization;
|
||||
|
||||
namespace RailEnterprise.Client.Tutorial;
|
||||
|
||||
/// <summary>
|
||||
/// Interfaccia del tutorial: riquadro ancorato in basso a sinistra dell'area della mappa (non modale, non
|
||||
/// copre barra degli strumenti né pannello destro) e contorno ambra animato attorno all'elemento da
|
||||
/// guardare. Tutto ciò che non è il riquadro lascia passare il mouse.
|
||||
/// </summary>
|
||||
public partial class TutorialOverlay : Control
|
||||
{
|
||||
private const float BoxWidth = 400;
|
||||
private const float Margin = 16;
|
||||
|
||||
private readonly PanelContainer _box = new();
|
||||
private readonly Label _counter = UiTheme.Text("", 12, Palette.TextSecondary);
|
||||
private readonly Label _title = UiTheme.TitleLabel("", 26, Palette.AmberLight);
|
||||
private readonly Label _text = UiTheme.Text("", 14);
|
||||
private readonly Label _done = UiTheme.Text("", 13, Palette.Ok, bold: true);
|
||||
private readonly ProgressBar _progress = new() { ShowPercentage = false, CustomMinimumSize = new Vector2(0, 4) };
|
||||
private readonly VBoxContainer _body = new();
|
||||
private readonly Button _next = UiTheme.Primary(T("Avanti"));
|
||||
private readonly Button _skip = new() { Text = T("Salta passo") };
|
||||
private readonly Button _close = new() { Text = T("Chiudi tutorial") };
|
||||
private readonly Button _collapse = new() { Text = "–", Flat = true, CustomMinimumSize = new Vector2(28, 24) };
|
||||
private readonly HighlightFrame _frame = new();
|
||||
private double _doneTimer;
|
||||
private bool _collapsed;
|
||||
|
||||
public event Action? NextPressed;
|
||||
public event Action? SkipPressed;
|
||||
public event Action? ClosePressed;
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
|
||||
MouseFilter = MouseFilterEnum.Ignore;
|
||||
UiTheme.Apply(this);
|
||||
AddChild(_frame);
|
||||
// i pulsanti non prendono il fuoco: Invio e spazio restano alla partita (Costruisci, pausa) e non
|
||||
// ripremono l'ultimo pulsante del tutorial
|
||||
foreach (var b in new[] { _next, _skip, _close, _collapse }) b.FocusMode = FocusModeEnum.None;
|
||||
|
||||
_box.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Amber, 10, 16));
|
||||
_box.CustomMinimumSize = new Vector2(BoxWidth, 0);
|
||||
AddChild(_box);
|
||||
var col = new VBoxContainer();
|
||||
col.AddThemeConstantOverride("separation", 8);
|
||||
_box.AddChild(col);
|
||||
|
||||
var header = new HBoxContainer();
|
||||
header.AddThemeConstantOverride("separation", 8);
|
||||
header.AddChild(UiTheme.Badge(T("Tutorial")));
|
||||
_counter.SizeFlagsHorizontal = SizeFlags.ExpandFill;
|
||||
_counter.SizeFlagsVertical = SizeFlags.ShrinkCenter;
|
||||
header.AddChild(_counter);
|
||||
_collapse.TooltipText = T("Riduci o espandi il riquadro del tutorial");
|
||||
_collapse.Pressed += () => SetCollapsed(!_collapsed);
|
||||
header.AddChild(_collapse);
|
||||
col.AddChild(header);
|
||||
|
||||
_progress.AddThemeStyleboxOverride("fill", UiTheme.Box(Palette.Amber, Palette.Amber, 2, 0));
|
||||
_progress.AddThemeStyleboxOverride("background", UiTheme.Box(Palette.Border, Palette.Border, 2, 0));
|
||||
col.AddChild(_progress);
|
||||
_title.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
col.AddChild(_title);
|
||||
|
||||
_body.AddThemeConstantOverride("separation", 10);
|
||||
col.AddChild(_body);
|
||||
_text.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
_body.AddChild(_text);
|
||||
_done.AutowrapMode = TextServer.AutowrapMode.WordSmart;
|
||||
_done.Visible = false;
|
||||
_body.AddChild(_done);
|
||||
var buttons = new HBoxContainer();
|
||||
buttons.AddThemeConstantOverride("separation", 8);
|
||||
buttons.AddChild(_next);
|
||||
buttons.AddChild(_skip);
|
||||
buttons.AddChild(new Control { SizeFlagsHorizontal = SizeFlags.ExpandFill });
|
||||
buttons.AddChild(_close);
|
||||
_body.AddChild(buttons);
|
||||
_next.Pressed += () => NextPressed?.Invoke();
|
||||
_skip.Pressed += () => SkipPressed?.Invoke();
|
||||
_close.Pressed += () => ClosePressed?.Invoke();
|
||||
_close.TooltipText = T("Il tutorial si riapre con F1 o dalla schermata iniziale");
|
||||
}
|
||||
|
||||
/// <summary>Mostra un passo: numero, titolo e testo già tradotti; Avanti solo per i passi informativi.</summary>
|
||||
public void ShowStep(int number, int count, string title, string text, bool informative, bool last)
|
||||
{
|
||||
_counter.Text = string.Format(T("Passo {0} di {1}"), number, count);
|
||||
_progress.MaxValue = count;
|
||||
_progress.Value = number - 1;
|
||||
_title.Text = title;
|
||||
_text.Text = text;
|
||||
_next.Visible = informative;
|
||||
_next.Text = last ? T("Fine") : T("Avanti");
|
||||
_skip.Visible = !informative;
|
||||
}
|
||||
|
||||
/// <summary>Breve conferma del passo appena completato.</summary>
|
||||
public void Flash(string completedTitle)
|
||||
{
|
||||
_done.Text = $"✓ {T("Fatto")}: {completedTitle}";
|
||||
_done.Visible = true;
|
||||
_doneTimer = 2.5;
|
||||
}
|
||||
|
||||
/// <summary>Area libera in cui ancorare il riquadro (rettangolo globale della mappa o del pannello a tutto schermo).</summary>
|
||||
public Rect2 Area { get; set; }
|
||||
|
||||
/// <summary>Elemento da evidenziare (rettangolo globale), null per nessuno.</summary>
|
||||
public Rect2? Target
|
||||
{
|
||||
get => _frame.Target;
|
||||
set => _frame.Target = value;
|
||||
}
|
||||
|
||||
private void SetCollapsed(bool collapsed)
|
||||
{
|
||||
_collapsed = collapsed;
|
||||
_body.Visible = !collapsed;
|
||||
_collapse.Text = collapsed ? "+" : "–";
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
if (_doneTimer > 0)
|
||||
{
|
||||
_doneTimer -= delta;
|
||||
if (_doneTimer <= 0) _done.Visible = false;
|
||||
}
|
||||
// in basso a sinistra dell'area libera; la larghezza si adatta alle finestre strette
|
||||
var area = Area.Size == Vector2.Zero ? GetViewportRect() : Area;
|
||||
float width = Math.Min(BoxWidth, Math.Max(240, area.Size.X - 2 * Margin));
|
||||
_box.CustomMinimumSize = new Vector2(width, 0);
|
||||
_box.Size = new Vector2(width, 0);
|
||||
var size = _box.GetCombinedMinimumSize();
|
||||
_box.Size = size;
|
||||
_box.Position = new Vector2(area.Position.X + Margin, area.End.Y - Margin - size.Y);
|
||||
}
|
||||
|
||||
/// <summary>Contorno ambra che pulsa attorno all'elemento evidenziato; non intercetta il mouse.</summary>
|
||||
private sealed partial class HighlightFrame : Control
|
||||
{
|
||||
private double _time;
|
||||
|
||||
public Rect2? Target { get; set; }
|
||||
|
||||
public override void _Ready()
|
||||
{
|
||||
SetAnchorsAndOffsetsPreset(LayoutPreset.FullRect);
|
||||
MouseFilter = MouseFilterEnum.Ignore;
|
||||
}
|
||||
|
||||
public override void _Process(double delta)
|
||||
{
|
||||
_time += delta;
|
||||
QueueRedraw();
|
||||
}
|
||||
|
||||
public override void _Draw()
|
||||
{
|
||||
if (Target is not { } t || t.Size.X <= 0 || t.Size.Y <= 0) return;
|
||||
float pulse = 0.5f + 0.5f * MathF.Sin((float)_time * 4f);
|
||||
float grow = 3 + 3 * pulse;
|
||||
var rect = t.Grow(grow);
|
||||
rect.Position -= GetGlobalRect().Position;
|
||||
var glow = new StyleBoxFlat { BgColor = Palette.WithAlpha(Palette.Amber, 0.06f + 0.06f * pulse), BorderColor = Palette.WithAlpha(Palette.AmberLight, 0.35f + 0.45f * pulse) };
|
||||
glow.SetBorderWidthAll(3);
|
||||
glow.SetCornerRadiusAll(10);
|
||||
DrawStyleBox(glow, rect);
|
||||
var outer = new StyleBoxFlat { BgColor = new Color(0, 0, 0, 0), BorderColor = Palette.WithAlpha(Palette.Amber, 0.25f * (1 - pulse)) };
|
||||
outer.SetBorderWidthAll(2);
|
||||
outer.SetCornerRadiusAll(14);
|
||||
DrawStyleBox(outer, rect.Grow(6 + 4 * pulse));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
using Godot;
|
||||
|
||||
namespace RailEnterprise.Client.Tutorial;
|
||||
|
||||
/// <summary>
|
||||
/// Stato del tutorial nelle impostazioni del client (<c>user://settings.cfg</c>, sezione <c>tutorial</c>):
|
||||
/// se il giocatore ha già aperto una partita (la casella «Mostra il tutorial» è attiva solo alla prima)
|
||||
/// e l'avanzamento di ogni partita, con la chiave di <see cref="TutorialProgress.GameKey"/>.
|
||||
/// </summary>
|
||||
public static class TutorialSettings
|
||||
{
|
||||
private const string Path = "user://settings.cfg";
|
||||
private const string Section = "tutorial";
|
||||
|
||||
/// <summary>Vero dopo la prima partita aperta.</summary>
|
||||
public static bool Played
|
||||
{
|
||||
get => (bool)Load().GetValue(Section, "played", false);
|
||||
set => Write(cfg => cfg.SetValue(Section, "played", value));
|
||||
}
|
||||
|
||||
public static TutorialProgress? Read(string gameKey) =>
|
||||
TutorialProgress.Decode((string)Load().GetValue(Section, gameKey, ""));
|
||||
|
||||
public static void Save(string gameKey, TutorialProgress progress) =>
|
||||
Write(cfg => cfg.SetValue(Section, gameKey, progress.Encode()));
|
||||
|
||||
private static ConfigFile Load()
|
||||
{
|
||||
var cfg = new ConfigFile();
|
||||
cfg.Load(Path);
|
||||
return cfg;
|
||||
}
|
||||
|
||||
private static void Write(Action<ConfigFile> change)
|
||||
{
|
||||
// si rilegge il file ogni volta: le altre impostazioni (lingua) restano com'erano
|
||||
var cfg = Load();
|
||||
change(cfg);
|
||||
var error = cfg.Save(Path);
|
||||
if (error != Error.Ok) GD.PushWarning($"Impostazioni del tutorial non salvate: {error}");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user