F6: tutorial guidato della prima partita

Tutorial facoltativo che accompagna il giocatore dalla mappa alla prima
linea in servizio e poi a Mercato globale, Finanze e La tua scalata. È
un'esperienza del solo client: osserva ciò che il client già riceve
(entità della compagnia in ClientWorld, esiti riusciti dei comandi,
pannello aperto, camera, velocità, anteprime del tracciato), non invia
comandi e non decide regole; Core, Protocol, Server e salvataggi non
cambiano (ADR 0023).

- Copione in assets/tutorial/tutorial.json (19 passi, chiavi di testo
  per T(), elemento da evidenziare con ripiego, condizione osservabile),
  esportato con il gioco; testi italiani e inglesi in strings.csv.
- Logica pura senza Godot in scripts/Tutorial/Logic: copione con
  validazione, fatti, condizioni counter/panel/all/any, macchina a stati,
  avanzamento salvato; compilata anche dal progetto dei test (8 test).
- Riquadro non modale in basso a sinistra della mappa, contorno ambra
  animato, Avanti / Salta passo / Chiudi tutorial, F1 per nasconderlo o
  riaprirlo; nel menu la casella «Mostra il tutorial» (attiva alla prima
  partita) e l'opzione «Tutorial».
- Avanzamento per partita in user://settings.cfg, ripreso dopo il
  caricamento; il pilota automatico non crea il tutorial.

Refs #45.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-08 14:21:12 +01:00
1 parent 7eec322202
commit ebe4308e75
21 files changed
+1524 -8

No files matched your search

@@ -0,0 +1,159 @@
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:&lt;id&gt;</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: seme, impronta del terreno e compagnia del giocatore, che il
/// client riceve nel Welcome. Resta la stessa dopo un salvataggio e un caricamento della stessa partita.
/// </summary>
public static string GameKey(ulong seed, ulong terrainHash, int companyId) => $"g_{seed:x16}_{terrainHash:x16}_{companyId}";
/// <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 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"/> (opzione «Tutorial»
/// del menu) riparte sempre dal primo passo; un tutorial in corso in quella partita si riprende; uno
/// completato o chiuso resta nascosto; senza voce salvata si mostra solo se il giocatore l'ha chiesto
/// (casella «Mostra il tutorial», attiva alla prima partita).
/// </summary>
public static TutorialLaunch Plan(bool requested, bool restart, TutorialProgress? saved)
{
if (restart) return TutorialLaunch.StartFresh;
if (saved is { } s) return s.Status == TutorialStatus.Active ? TutorialLaunch.Resume : TutorialLaunch.Hidden;
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();
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 dal menu.</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,205 @@
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: 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.Count == 0) errors.Add("nessun passo");
var ids = new HashSet<string>(StringComparer.Ordinal);
foreach (var step in Steps)
{
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) 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,266 @@
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à, 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 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 _gameKey = "";
private bool _visible;
private int _shownIndex = -1;
private double _sinceFacts = FactsInterval;
private Vector2? _lastCamera;
private float _lastZoom;
private byte? _lastSpeed;
/// <param name="requested">casella «Mostra il tutorial» del menu</param>
/// <param name="restart">opzione «Tutorial» del menu: dal primo passo anche se già fatto</param>
public TutorialController(GameScreen game, bool requested, bool restart)
{
_game = game;
_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)
{
GD.PushWarning($"Tutorial non disponibile: {e.Message}");
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;
OpenForGame();
}
public override void _ExitTree() => _game.Session.MessageApplied -= OnMessage;
/// <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(s.Seed, s.TerrainHash, s.CompanyId);
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 opzione del menu valgono per la partita aperta, non per le successive (Nuova partita+)
_requested = _restart = false;
_lastCamera = null;
_lastSpeed = 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);
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 (_machine is null || e is not InputEventKey { Pressed: true, Echo: false, Keycode: Key.F1 }) 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();
if (_visible)
{
string? title = _machine.Current is { } step ? T(step.Title) : null;
if (_machine.Update(_facts))
{
Save();
if (title is not null) _overlay.Flash(title);
// completato l'ultimo passo il riquadro si chiude
if (_machine.Status != TutorialStatus.Active) _visible = false;
}
}
}
Refresh();
}
/// <summary>Spostamento della camera (in schermate), zoom (in logaritmi) e cambi di velocità, 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;
var w = _game.Session.World;
byte speed = _game.Session.RequestedSpeed ?? w.LastDigest?.Speed ?? w.Speed;
if (_lastSpeed is { } s && s != speed) _facts.Add("speedChanges", 1);
_lastSpeed = speed;
}
/// <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;
_overlay.ShowStep(_machine.Index + 1, _machine.Script.Steps.Count, T(step.Title), T(step.Text), step.IsInformative, _machine.IsLast);
}
_overlay.Area = _game.TutorialArea();
Control? target = null;
if (step.Highlight is { } h) target = Shown(_game.TutorialTarget(h));
if (target is null && step.Fallback is { } f) target = Shown(_game.TutorialTarget(f));
_overlay.Target = target?.GetGlobalRect();
}
private static Control? Shown(Control? c) => c is not null && IsInstanceValid(c) && c.IsVisibleInTree() && c.Size.X > 0 ? c : null;
}
@@ -0,0 +1,178 @@
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);
_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 dal menu");
}
/// <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}");
}
}