Files
Alby96andClaude Opus 5.5 64209afd5f
CI / Build e test (pull_request) Successful in 1m29s
CI / Immagine Docker (pull_request) Successful in 30s
F6: tutorial, correzioni della revisione
Unisce origin/main (audio, ere e obsolescenza, scheda dell'industria e
schermata di connessione) e corregge i rilievi della revisione del
tutorial (ADR 0023 aggiornato).

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

Refs #45.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-08 14:51:31 +01:00

313 lines
12 KiB
C#

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;
}
}