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:
1 parent
7eec322202
commit
ebe4308e75
21 files changed
+1524
-8
No files matched your search
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user