using Godot; using RailEnterprise.Client.App; using RailEnterprise.Client.Hud; using RailEnterprise.Client.Map; using RailEnterprise.Client.Net; using RailEnterprise.Client.Panels; using RailEnterprise.Core.Commands; using RailEnterprise.Core.Common; using RailEnterprise.Core.Data; using RailEnterprise.Core.Rail; using RailEnterprise.Protocol; using RailEnterprise.Protocol.Messages; using static RailEnterprise.Client.App.Localization; namespace RailEnterprise.Client.Screens; /// /// Partita: mappa con i livelli, HUD (barra superiore, strumenti, pannello destro con minimappa, /// notiziario) e logica degli strumenti. Ogni modifica è un comando al server; il client calcola /// solo l'anteprima del tracciato con le classi di Core. /// public partial class GameScreen : Node { private readonly GameSession _session; private readonly MapView _map = new(); private readonly LabelLayer _labels = new(); private readonly TopBar _top = new(); private readonly Toolbar _toolbar = new(); private readonly Ticker _ticker = new(); private readonly Minimap _minimap = new(); private readonly ScrollContainer _scroll = new() { SizeFlagsVertical = Control.SizeFlags.ExpandFill, HorizontalScrollMode = ScrollContainer.ScrollMode.Disabled }; private readonly VBoxContainer _content = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; private readonly VBoxContainer _toasts = new(); private readonly Control _disconnected = new(); private Tool _tool = Tool.None; private TrackPanel? _trackPanel; private StationPanel? _stationPanel; private DepotPanel? _depotPanel; private LinesPanel? _linesPanel; private InfoPanel? _info; private MaintenancePanel? _maintenance; private IndustryPanel? _industryPanel; private CompaniesPanel? _companies; // pannelli a tutto schermo (Compagnie e borsa): coprono mappa e pannello destro, la barra resta private readonly PanelContainer _full = new() { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, Visible = false }; private Control? _mapArea; private Control? _side; // Cronaca finale (o provvisoria) sopra tutta la partita e avviso dell'osservatore private readonly CanvasLayer _overlay = new() { Layer = 3 }; private readonly PanelContainer _observer = new() { Visible = false }; private ChronicleScreen? _chronicleScreen; private Protocol.Messages.Chronicle? _seenChronicle; private bool _wantChronicle, _finalShown; private bool _heatMap; private readonly List _trackPoints = []; private Vector2? _mouse; private bool _previewDirty; private double _sincePreview; private TrackPlan? _plan; private Vector2 _lastViewportCenter; private float _lastViewportZoom; public event Action? Exit; public GameScreen(GameSession session) => _session = session; public GameSession Session => _session; public MapView Map => _map; /// Seleziona uno strumento come dalla barra (anche per il pilota automatico). public void UseTool(Tool tool) => _toolbar.Select(tool); /// Imposta i punti del tracciato in corso e aggiorna l'anteprima. public void SetTrackPoints(IEnumerable points, Vector2? mouse) { _trackPoints.Clear(); _trackPoints.AddRange(points); _mouse = mouse; _previewDirty = true; } /// Mostra la scheda di un treno e lo evidenzia. /// Apre la cartella di manutenzione del treno nel pannello Officine. public void OpenMaintenance(int train) { _toolbar.Select(Tool.Maintenance); _maintenance?.SelectTrain(train); } /// Apre il Registro officina del deposito nel pannello Officine. public void OpenWorkshop(int depot) { if (_tool != Tool.Maintenance) _toolbar.Select(Tool.Maintenance); _maintenance?.SelectDepot(depot); } /// Apre il pannello Industrie sull'industria indicata (scheda del proprietario). public void OpenIndustry(int industry) { if (_tool != Tool.Industries) _toolbar.Select(Tool.Industries); _industryPanel?.Select(industry); } /// Apre «Compagnie e borsa» a tutto schermo sulla compagnia indicata. public void OpenCompanies(int company) { if (_tool != Tool.Companies) _toolbar.Select(Tool.Companies); _companies?.Select(company); } /// Chiede al server la Cronaca (provvisoria a partita in corso) e la mostra all'arrivo. public void OpenChronicle() { _wantChronicle = true; _session.Send(new RequestDetail { Kind = DetailKind.Chronicle, Target = 0 }); } public bool ChronicleVisible => _chronicleScreen is not null; /// Mappa di calore della condizione dei treni. public void SetHeatMap(bool on) { _map.Trains.HeatMap = _heatMap = on; _maintenance?.SetHeatMap(on); } /// Scorre il pannello laterale (0 = in cima, 1 = in fondo). public void ScrollPanel(double fraction) { var bar = _scroll.GetVScrollBar(); _scroll.ScrollVertical = (int)Math.Round((bar.MaxValue - bar.Page) * Math.Clamp(fraction, 0, 1)); } public void SelectTrain(int id) { _map.Trains.SelectedTrain = id; _info?.Select(InfoPanel.Kind.Train, id); } public override void _Ready() { AddChild(_map); var labelLayer = new CanvasLayer { Layer = 1 }; AddChild(labelLayer); labelLayer.AddChild(_labels); _labels.Bind(_session.World, _map.Camera); var hud = new CanvasLayer { Layer = 2 }; AddChild(hud); var root = new VBoxContainer { MouseFilter = Control.MouseFilterEnum.Ignore }; UiTheme.Apply(root); root.SetAnchorsPreset(Control.LayoutPreset.FullRect); root.AddThemeConstantOverride("separation", 0); hud.AddChild(root); root.AddChild(_top); var middle = new HBoxContainer { SizeFlagsVertical = Control.SizeFlags.ExpandFill, MouseFilter = Control.MouseFilterEnum.Ignore }; middle.AddThemeConstantOverride("separation", 0); root.AddChild(middle); middle.AddChild(_toolbar); var mapArea = new Control { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill, MouseFilter = Control.MouseFilterEnum.Ignore }; middle.AddChild(mapArea); _mapArea = mapArea; _toasts.SetAnchorsPreset(Control.LayoutPreset.TopWide); _toasts.OffsetLeft = 16; _toasts.OffsetRight = -16; _toasts.OffsetTop = 12; _toasts.MouseFilter = Control.MouseFilterEnum.Ignore; mapArea.AddChild(_toasts); var side = new PanelContainer { CustomMinimumSize = new Vector2(440, 0) }; side.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.Panel, Palette.Border, 0, 18)); middle.AddChild(side); _side = side; _full.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.AppBackground, Palette.Border, 0, 20)); middle.AddChild(_full); BuildObserverBanner(mapArea); var sideCol = new VBoxContainer(); sideCol.AddThemeConstantOverride("separation", 12); side.AddChild(sideCol); sideCol.AddChild(_scroll); // margine destro: la barra di scorrimento non copre i valori allineati a destra var contentMargin = new MarginContainer { SizeFlagsHorizontal = Control.SizeFlags.ExpandFill }; contentMargin.AddThemeConstantOverride("margin_right", 12); _scroll.AddChild(contentMargin); contentMargin.AddChild(_content); var miniHeader = new HBoxContainer(); var miniTitle = UiTheme.Text(T("Minimappa"), 13, Palette.TextSecondary); miniTitle.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; miniHeader.AddChild(miniTitle); miniHeader.AddChild(UiTheme.Text(_session.World.Summary?.RegionId is { Length: > 0 } r ? $"{T("Regione di")} {char.ToUpperInvariant(r[0])}{r[1..]}" : "", 13, Palette.TextSecondary)); sideCol.AddChild(miniHeader); sideCol.AddChild(_minimap); root.AddChild(_ticker); BuildDisconnectedOverlay(hud); AddChild(_overlay); _map.Bind(_session); _minimap.Bind(_session.World, _map); _top.Bind(_session); _toolbar.Selected += SelectTool; _map.Clicked += OnMapClicked; _map.Hovered += OnMapHovered; _map.Cancelled += () => _toolbar.Select(Tool.None); _session.MessageApplied += OnMessage; _session.Notified += e => _ticker.Add(e); _session.CommandFailed += r => Toast(r.Message, error: true); SelectTool(Tool.None); SendViewport(force: true); // il Registro degli impieghi alimenta anche le schede di industrie e città _session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 }); } public override void _ExitTree() => _session.MessageApplied -= OnMessage; /// Avviso permanente dopo la fine della partita: si guarda il mondo, la Cronaca resta a portata. private void BuildObserverBanner(Control mapArea) { _observer.SetAnchorsPreset(Control.LayoutPreset.BottomWide); _observer.OffsetLeft = 16; _observer.OffsetRight = -16; _observer.OffsetTop = -70; _observer.OffsetBottom = -16; _observer.AddThemeStyleboxOverride("panel", UiTheme.Box(Palette.AmberDark, Palette.Amber, 8, 14)); var row = new HBoxContainer(); row.AddThemeConstantOverride("separation", 14); var text = UiTheme.Text(T("Partita conclusa: sei un osservatore. Il mondo va avanti e le compagnie IA continuano a giocare."), 14, Palette.AmberLight, bold: true); text.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; text.SizeFlagsVertical = Control.SizeFlags.ShrinkCenter; text.AutowrapMode = TextServer.AutowrapMode.WordSmart; row.AddChild(text); var open = UiTheme.Primary(T("Cronaca finale")); open.Pressed += () => { if (_session.World.Chronicle is { } c) ShowChronicle(c); else OpenChronicle(); }; row.AddChild(open); _observer.AddChild(row); mapArea.AddChild(_observer); } private void BuildDisconnectedOverlay(CanvasLayer hud) { _disconnected.SetAnchorsPreset(Control.LayoutPreset.FullRect); UiTheme.Apply(_disconnected); _disconnected.Visible = false; var shade = new ColorRect { Color = new Color(0, 0, 0, 0.55f) }; shade.SetAnchorsPreset(Control.LayoutPreset.FullRect); _disconnected.AddChild(shade); var center = new CenterContainer(); center.SetAnchorsPreset(Control.LayoutPreset.FullRect); _disconnected.AddChild(center); var panel = new PanelContainer(); var col = new VBoxContainer(); col.AddThemeConstantOverride("separation", 12); col.AddChild(UiTheme.TitleLabel(T("Connessione persa"), 36)); col.AddChild(UiTheme.Text(T("Il server non risponde più. La partita continua sul server."), 14, Palette.TextSecondary)); var back = UiTheme.Primary(T("Torna al menu")); back.Pressed += () => Exit?.Invoke(); col.AddChild(back); panel.AddChild(col); center.AddChild(panel); hud.AddChild(_disconnected); } // ------------------------------------------------------------------ messaggi e ciclo private void OnMessage(IMessage m) { switch (m) { case MapChunk c: _map.Terrain.MarkDirty(c.Cx, c.Cy); _map.Entities.ForestChunk(c.Cx, c.Cy); break; case Welcome: // nuova partita o caricamento: si ricomincia dalla copia locale vuota _map.Bind(_session); _minimap.Bind(_session.World, _map); CloseChronicle(); _seenChronicle = null; _wantChronicle = _finalShown = false; _toolbar.Select(Tool.None); SendViewport(force: true); _session.Send(new RequestDetail { Kind = DetailKind.Employment, Target = 0 }); break; case DailyDigest d: foreach (var e in d.Events.Where(e => e.Severity >= 2)) _ticker.Add(e); break; } } public override void _Process(double delta) { _session.Poll(); _disconnected.Visible = !_session.IsOpen; UpdateChronicle(); SendViewport(force: false); _sincePreview += delta; if (_previewDirty && _sincePreview > 0.12) { _previewDirty = false; _sincePreview = 0; UpdateTrackPreview(); } } /// Sottoscrive l'area visibile quando la camera si sposta di almeno un quarto di schermo. private void SendViewport(bool force) { var w = _session.World; if (w.Summary is null) return; var view = _map.VisibleRect(); var center = view.GetCenter(); if (!force && center.DistanceTo(_lastViewportCenter) < view.Size.X / 4 && Math.Abs(_map.Zoom - _lastViewportZoom) < _lastViewportZoom * 0.3f) return; _lastViewportCenter = center; _lastViewportZoom = _map.Zoom; double cs = w.Summary.CellSizeM; _session.Send(new Subscribe { X0 = Math.Max(0, (int)(view.Position.X / cs)), Y0 = Math.Max(0, (int)(view.Position.Y / cs)), X1 = Math.Min(w.Summary.WidthCells - 1, (int)(view.End.X / cs)), Y1 = Math.Min(w.Summary.HeightCells - 1, (int)(view.End.Y / cs)), Lod = (byte)(_map.Zoom >= MapScale.DetailZoom ? 0 : _map.Zoom >= MapScale.OverviewZoom ? 1 : 2), }); } public override void _UnhandledKeyInput(InputEvent e) { if (e is not InputEventKey { Pressed: true } key) return; switch (key.Keycode) { case Key.Escape: _toolbar.Select(Tool.None); break; case Key.Enter or Key.KpEnter when _tool == Tool.Track: BuildTrack(); break; case Key.Backspace when _tool == Tool.Track && _trackPoints.Count > 0: _trackPoints.RemoveAt(_trackPoints.Count - 1); _previewDirty = true; break; case Key.Space: _session.SetSpeed(_session.World.Speed == 0 ? (byte)1 : (byte)0); break; } } // ------------------------------------------------------------------ strumenti private void SelectTool(Tool tool) { _tool = tool; _trackPoints.Clear(); _plan = null; _map.Tools.Clear(); _map.Entities.SelectedStation = -1; foreach (var c in _content.GetChildren()) c.QueueFree(); _trackPanel = null; _stationPanel = null; _depotPanel = null; _linesPanel = null; _info = null; _maintenance = null; _industryPanel = null; _companies = null; foreach (var c in _full.GetChildren()) c.QueueFree(); bool full = tool == Tool.Companies; _full.Visible = full; if (_mapArea is not null) _mapArea.Visible = !full; if (_side is not null) _side.Visible = !full; Control panel; switch (tool) { case Tool.Track: _trackPanel = new TrackPanel(_session.World); _trackPanel.OptionsChanged += () => _previewDirty = true; _trackPanel.Build.Pressed += BuildTrack; _trackPanel.Cancel.Pressed += () => _toolbar.Select(Tool.None); panel = _trackPanel; break; case Tool.Station: panel = _stationPanel = new StationPanel(_session); break; case Tool.Depot: panel = _depotPanel = new DepotPanel(_session); break; case Tool.Signal: panel = new HelpPanel(T("Segnali"), T("Clic su un binario per posare un segnale di blocco: divide l'arco in sezioni e aumenta la capacità della linea.")); break; case Tool.Demolish: 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); trains.TrainSelected += id => { _map.Trains.SelectedTrain = id; if (_map.Trains.Heads.TryGetValue(id, out var p)) _map.CenterOn(p); }; panel = trains; break; case Tool.Lines: _linesPanel = new LinesPanel(_session); _linesPanel.StopsChanged += UpdateStopsOverlay; panel = _linesPanel; break; case Tool.Maintenance: _maintenance = new MaintenancePanel(_session, _heatMap); _maintenance.HeatMapToggled += on => _map.Trains.HeatMap = _heatMap = on; _maintenance.TrainSelected += id => { _map.Trains.SelectedTrain = id; if (_map.Trains.Heads.TryGetValue(id, out var p)) _map.CenterOn(p); }; panel = _maintenance; break; case Tool.Employment: panel = new EmploymentPanel(_session); break; case Tool.Industries: panel = _industryPanel = new IndustryPanel(_session); break; case Tool.Companies: _companies = new CompaniesPanel(_session); _companies.CloseRequested += () => _toolbar.Select(Tool.None); _companies.ChronicleRequested += OpenChronicle; _full.AddChild(_companies); panel = NewInfoPanel(); break; case Tool.Market: panel = new MarketPanel(_session); break; case Tool.Finance: panel = new FinancePanel(_session); break; default: panel = NewInfoPanel(); break; } panel.SizeFlagsHorizontal = Control.SizeFlags.ExpandFill; _content.AddChild(panel); } private InfoPanel NewInfoPanel() { _info = new InfoPanel(_session); _info.MaintenanceRequested += OpenMaintenance; _info.IndustryRequested += OpenIndustry; return _info; } private void OnMapHovered(Vector2 world) { _mouse = world; switch (_tool) { case Tool.Track: if (_trackPoints.Count > 0) _previewDirty = true; _map.Tools.SetTrack(_trackPoints, Snap(world), _plan); break; case Tool.Station: _map.Tools.SetGhost(ToolOverlay.Ghost.Station, world); break; case Tool.Depot: _map.Tools.SetGhost(ToolOverlay.Ghost.Depot, world); break; case Tool.Demolish: _map.Tools.SetGhost(ToolOverlay.Ghost.Demolish, world); break; } } private void OnMapClicked(Vector2 world) { var w = _session.World; var p = MapScale.W(world); switch (_tool) { case Tool.Track: _trackPoints.Add(Snap(world)); _previewDirty = true; break; case Tool.Station when _stationPanel is not null: string? name = string.IsNullOrWhiteSpace(_stationPanel.StationName.Text) ? null : _stationPanel.StationName.Text.Trim(); _session.Command(new BuildStationCommand(p, (int)_stationPanel.Platforms.Value, name), r => { if (r.Ok) Toast(r.Message); }); break; case Tool.Depot when _depotPanel is not null: _session.Command(new BuildDepotCommand(p, _depotPanel.SelectedSize), r => { if (r.Ok) Toast(r.Message); }); break; case Tool.Signal: if (NearestEdge(world) is { } hit) _session.Command(new PlaceSignalCommand(new EdgeId(hit.Edge), hit.S), r => { if (r.Ok) Toast(r.Message); }); break; case Tool.Demolish: Demolish(world); break; case Tool.Lines when _linesPanel is not null: if (NearestStation(world) is { } station) _linesPanel.AddStop(station); break; case Tool.Industries when _industryPanel is not null: if (IndustryAt(world) is { } industry) _industryPanel.Select(industry); break; default: SelectAt(world); break; } } /// Scatto a 45° rispetto al punto precedente (Maiusc per disattivarlo). private Vector2 Snap(Vector2 world) { if (_trackPoints.Count == 0 || Input.IsKeyPressed(Key.Shift)) return world; var prev = _trackPoints[^1]; var d = world - prev; if (d.LengthSquared() < 1) return world; float step = MathF.PI / 4; float angle = MathF.Round(d.Angle() / step) * step; return prev + Vector2.FromAngle(angle) * d.Length(); } private void UpdateTrackPreview() { if (_tool != Tool.Track || _trackPanel is null) return; var pts = new List(_trackPoints); if (_mouse is { } m && pts.Count >= 1) pts.Add(Snap(m)); if (pts.Count < 2) { _plan = null; _trackPanel.Show(null); _map.Tools.SetTrack(_trackPoints, _mouse, null); return; } try { _plan = _session.World.PreviewTrack(TrackCommand(pts, 0)); _trackPanel.Show(_plan); _trackPanel.SetStatus(""); } catch (Exception e) { _plan = null; _trackPanel.Show(null); _trackPanel.SetStatus(T("Anteprima non disponibile: ") + e.Message, error: true); } _map.Tools.SetTrack(_trackPoints, _mouse is { } mm ? Snap(mm) : null, _plan); } private BuildTrackCommand TrackCommand(List pts, long expectedCost) { var p = _trackPanel!; return new BuildTrackCommand(pts.Select(MapScale.W).ToList(), p.HeightOffset, p.AllowBridges, p.AllowTunnels, p.TrackClass, p.DoubleTrack, p.Electrified, expectedCost); } private void BuildTrack() { if (_trackPanel is null || _trackPoints.Count < 2) return; // si costruisce il tracciato dei punti fissati (senza il punto sotto il mouse) var plan = _session.World.PreviewTrack(TrackCommand(_trackPoints, 0)); if (!plan.Valid) { _trackPanel.SetStatus(plan.Errors[0].Message, error: true); return; } _session.Command(TrackCommand(_trackPoints, plan.TotalCost.Cents), r => { if (!r.Ok) { _trackPanel?.SetStatus(r.Message, error: true); return; } Toast(r.Message); // il prossimo tratto parte dall'ultimo punto var last = _trackPoints[^1]; _trackPoints.Clear(); _trackPoints.Add(last); _plan = null; _trackPanel?.Show(null); _map.Tools.SetTrack(_trackPoints, _mouse, null); }); } private void UpdateStopsOverlay() { if (_linesPanel is null) return; var pts = _linesPanel.Stops.Where(_session.World.Stations.ContainsKey).Select(s => MapScale.V(_session.World.Stations[s].Position)).ToList(); _map.Tools.SetStops(pts); } private float PickRadius => 24f / _map.Zoom; private int? NearestStation(Vector2 world) { int? best = null; float bestD = Math.Max(PickRadius, 150); foreach (var s in _session.World.Stations.Values) { float d = MapScale.V(s.Position).DistanceTo(world); if (d < bestD) { bestD = d; best = s.Id; } } return best; } private int? NearestDepot(Vector2 world) { int? best = null; float bestD = Math.Max(PickRadius, 120); foreach (var d in _session.World.Depots.Values) { float dist = MapScale.V(d.Position).DistanceTo(world); if (dist < bestD) { bestD = dist; best = d.Id; } } return best; } private (int Edge, double S)? NearestEdge(Vector2 world) { (int, double)? best = null; double bestD = Math.Max(PickRadius, 25); var p = MapScale.W(world); foreach (var e in _session.World.Edges.Values) { for (int i = 0; i < e.S.Length - 1; i++) { var a = new Vec2(e.X[i], e.Y[i]); var b = new Vec2(e.X[i + 1], e.Y[i + 1]); double d = RailNetwork.DistanceToSegment(p, a, b, out double t); if (d >= bestD) continue; bestD = d; best = (e.Id, e.S[i] + (e.S[i + 1] - e.S[i]) * t); } } return best; } private void Demolish(Vector2 world) { if (NearestStation(world) is { } st) _session.Command(new DemolishCommand(DemolishTarget.Station, st), r => { if (r.Ok) Toast(r.Message); }); else if (NearestDepot(world) is { } dp) _session.Command(new DemolishCommand(DemolishTarget.Depot, dp), r => { if (r.Ok) Toast(r.Message); }); else if (NearestEdge(world) is { } hit) _session.Command(new DemolishCommand(DemolishTarget.Edge, hit.Edge), r => { if (r.Ok) Toast(r.Message); }); } private void SelectAt(Vector2 world) { if (_info is null) return; var w = _session.World; foreach (var (id, head) in _map.Trains.Heads) { if (head.DistanceTo(world) < PickRadius * 1.5f) { _map.Trains.SelectedTrain = id; _info.Select(InfoPanel.Kind.Train, id); return; } } _map.Trains.SelectedTrain = -1; if (NearestStation(world) is { } st) { _map.Entities.SelectedStation = st; _map.Entities.QueueRedraw(); _info.Select(InfoPanel.Kind.Station, st); return; } _map.Entities.SelectedStation = -1; _map.Entities.QueueRedraw(); double cs = w.Summary?.CellSizeM ?? 100; if (IndustryAt(world) is { } industry) { _info.Select(InfoPanel.Kind.Industry, industry); return; } foreach (var town in w.Towns.Values) { if (MapScale.V(town.Position).DistanceTo(world) < Math.Max(PickRadius, (town.RadiusCells + 0.5) * cs)) { _info.Select(InfoPanel.Kind.Town, town.Id); return; } } _info.Select(InfoPanel.Kind.None, -1); } private int? IndustryAt(Vector2 world) { double cs = _session.World.Summary?.CellSizeM ?? 100; foreach (var ind in _session.World.Industries.Values) { if (MapScale.V(ind.Position).DistanceTo(world) < Math.Max(PickRadius, ind.FootprintCells * cs * 0.6)) return ind.Id; } return null; } // ------------------------------------------------------------------ Cronaca finale e osservatore /// Mostra la Cronaca quando arriva: subito se la partita è finita, oppure se l'ha chiesta il giocatore. private void UpdateChronicle() { var chronicle = _session.World.Chronicle; if (!ReferenceEquals(chronicle, _seenChronicle)) { _seenChronicle = chronicle; if (chronicle is not null && ((chronicle.GameOver && !_finalShown) || _wantChronicle)) { _wantChronicle = false; if (chronicle.GameOver) _finalShown = true; ShowChronicle(chronicle); } } _observer.Visible = chronicle?.GameOver == true && _chronicleScreen is null; } private void ShowChronicle(Protocol.Messages.Chronicle chronicle) { CloseChronicle(); var next = NextDifficulty(); string name = TranslationServer.GetLocale().StartsWith("en") ? next.NameEn : next.NameIt; var screen = new ChronicleScreen(_session.World, chronicle, name); screen.Closed += CloseChronicle; screen.NewGamePlus += StartNewGamePlus; _overlay.AddChild(screen); _chronicleScreen = screen; } private void CloseChronicle() { _chronicleScreen?.QueueFree(); _chronicleScreen = null; } /// Difficoltà successiva a quella della partita (l'ultima resta l'ultima). private DifficultyDef NextDifficulty() { var file = _session.World.Data.Difficulty; int i = file.Presets.FindIndex(p => p.Id == _session.Difficulty); if (i < 0) i = file.Presets.FindIndex(p => p.Id == file.Default); return file.Presets[Math.Clamp(i + 1, 0, file.Presets.Count - 1)]; } /// Nuova partita+: mappa nuova (seme successivo, stessa dimensione) con la difficoltà superiore. private void StartNewGamePlus() { var summary = _session.World.Summary; var next = NextDifficulty(); _session.Send(new NewGame { Seed = (summary?.Seed ?? 0) + 1, SizeKm = summary?.SizeKm ?? 0, DifficultyPreset = next.Id }); CloseChronicle(); Toast($"{T("Nuova partita+ in preparazione")}: {(TranslationServer.GetLocale().StartsWith("en") ? next.NameEn : next.NameIt)}"); } /// Messaggio temporaneo in alto sulla mappa. private 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)); _toasts.AddChild(notice); GetTree().CreateTimer(4.5).Timeout += () => { if (IsInstanceValid(notice)) notice.QueueFree(); }; while (_toasts.GetChildCount() > 4) _toasts.GetChild(0).QueueFree(); } }