Correzioni dalla revisione della scheda industria e della schermata di
connessione.
- Dati di altre compagnie: la forza lavoro della scheda mostra solo i
contratti a piedi, quelli della compagnia della sessione e, se
l'industria è sua, quelli di tutti i vettori, come il Registro degli
impieghi. Lo stesso filtro vale per provenienze, conteggio e viaggio
medio.
- Prezzo: «prezzo medio realizzato» mescolava una media mobile dei
ricavi con i totali del trimestre in corso. Al suo posto c'è il prezzo
di vendita, cioè il prezzo globale del giorno (SalePrice).
- Avvisi del server: hanno il giorno −1, così il rifiuto di Load o
NewGame non si confonde più con gli eventi del mondo che arrivano
mentre si aspetta il Welcome.
- Schermata di connessione:
- all'apertura avvia la strada scelta l'ultima volta;
- cambiando strada chiude la sessione dell'altra;
- senza sessione «Connetti e riprendi» la apre;
- il cambio di lingua passa la sessione alla schermata nuova;
- la scelta del salvataggio si tiene per id;
- Load e nuova partita chiedono conferma;
- stato del server su 3×2 con la versione del protocollo, salvataggi
su tre colonne, «Attivo da» che avanza.
- Scheda dell'industria:
- collegamenti e nodi non collegati sono leggibili;
- testo per l'industria inattiva;
- revisione e ammodernamento disabilitati, con il motivo, quando il
server li rifiuterebbe;
- l'esito dell'acquisto compare accanto al pulsante;
- le righe lunghe vanno a capo;
- «in sede» al posto di «al lavoro ora».
- Gli avvisi dei comandi compaiono anche sulle schermate a tutto
schermo.
- Pilota automatico:
- la schermata 20 sta su un suo CanvasLayer sopra l'interfaccia;
- 12 e 12b sono ora la scheda a tutto schermo.
- Test: pendolari di altri vettori nascosti, Load rifiutato via
WebSocket, Welcome senza ServerInfo. 202 test, 183 senza i lenti.
Refs #42.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
288 lines
13 KiB
C#
288 lines
13 KiB
C#
using Godot;
|
||
using RailEnterprise.Client.Hud;
|
||
using RailEnterprise.Client.Map;
|
||
using RailEnterprise.Client.Net;
|
||
using RailEnterprise.Client.Screens;
|
||
using RailEnterprise.Core.Commands;
|
||
using RailEnterprise.Core.Common;
|
||
using RailEnterprise.Core.Rail;
|
||
using RailEnterprise.Protocol.Client;
|
||
using RailEnterprise.Protocol.Messages;
|
||
|
||
namespace RailEnterprise.Client.App;
|
||
|
||
/// <summary>
|
||
/// Pilota automatico per il collaudo del client (<c>-- --autopilot cartella</c>): nella partita
|
||
/// locale costruisce stazioni, deposito e una linea con ponte usando l'anteprima, compra un treno,
|
||
/// lo mette in linea e salva schermate della mappa, del ponte, del treno e del profilo; poi apre
|
||
/// officine e impieghi (F4), la scheda del proprietario di un'industria, «Compagnie e borsa» e la
|
||
/// Cronaca provvisoria (F5).
|
||
/// </summary>
|
||
public partial class AutoPilot : Node
|
||
{
|
||
private readonly GameScreen _game;
|
||
private readonly string _out;
|
||
|
||
public AutoPilot(GameScreen game, string outDir)
|
||
{
|
||
_game = game;
|
||
_out = outDir;
|
||
}
|
||
|
||
private GameSession Session => _game.Session;
|
||
private ClientWorld World => _game.Session.World;
|
||
|
||
public override async void _Ready()
|
||
{
|
||
int code = 0;
|
||
try
|
||
{
|
||
await Run();
|
||
GD.Print("autopilot: ok");
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
GD.PrintErr($"autopilot: FALLITO {e.Message}\n{e.StackTrace}");
|
||
code = 1;
|
||
}
|
||
GetTree().Quit(code);
|
||
}
|
||
|
||
private async Task Frame() => await ToSignal(GetTree(), SceneTree.SignalName.ProcessFrame);
|
||
|
||
private async Task Until(Func<bool> condition, string what, double timeoutS = 120)
|
||
{
|
||
ulong start = Time.GetTicksMsec();
|
||
while (!condition())
|
||
{
|
||
if (Time.GetTicksMsec() - start > timeoutS * 1000) throw new TimeoutException(what);
|
||
await Frame();
|
||
}
|
||
}
|
||
|
||
private Task<CommandResultMessage> Do(GameCommand command)
|
||
{
|
||
var tcs = new TaskCompletionSource<CommandResultMessage>();
|
||
Session.Command(command, r => tcs.TrySetResult(r));
|
||
return tcs.Task;
|
||
}
|
||
|
||
private async Task<int> Ok(GameCommand command)
|
||
{
|
||
var r = await Do(command);
|
||
if (!r.Ok) throw new InvalidOperationException($"{command.Type}: {r.Message}");
|
||
GD.Print($"autopilot: {r.Message}");
|
||
return r.Created.Length > 0 ? r.Created[0] : -1;
|
||
}
|
||
|
||
/// <summary>Attende una condizione al massimo per il tempo indicato, senza fallire.</summary>
|
||
private async Task<bool> Wait(Func<bool> condition, double timeoutS)
|
||
{
|
||
ulong start = Time.GetTicksMsec();
|
||
while (!condition())
|
||
{
|
||
if (Time.GetTicksMsec() - start > timeoutS * 1000) return false;
|
||
await Frame();
|
||
}
|
||
return true;
|
||
}
|
||
|
||
private async Task Shot(string name, int settleFrames = 30)
|
||
{
|
||
for (int i = 0; i < settleFrames; i++) await Frame();
|
||
await ToSignal(RenderingServer.Singleton, RenderingServer.SignalName.FramePostDraw);
|
||
var image = GetViewport().GetTexture().GetImage();
|
||
string path = Path.Combine(_out, name + ".jpg");
|
||
image.SaveJpg(path, 0.88f);
|
||
GD.Print($"autopilot: schermata {path}");
|
||
}
|
||
|
||
private async Task Run()
|
||
{
|
||
Directory.CreateDirectory(_out);
|
||
var summary = World.Summary!;
|
||
Session.Send(new Subscribe { X0 = 0, Y0 = 0, X1 = summary.WidthCells - 1, Y1 = summary.HeightCells - 1 });
|
||
int chunks = ((summary.WidthCells + summary.ChunkCells - 1) / summary.ChunkCells) * ((summary.HeightCells + summary.ChunkCells - 1) / summary.ChunkCells);
|
||
await Until(() => World.Chunks.Count == chunks && World.Towns.Count > 0, "terreno");
|
||
await Shot("01_avvio", 90);
|
||
|
||
await Ok(new TakeLoanCommand(Money.FromLire(200_000)));
|
||
var site = BridgeSiteFinder.Find(World) ?? throw new InvalidOperationException("nessun sito con ponte");
|
||
int a = await Ok(new BuildStationCommand(site.A, 2));
|
||
int b = await Ok(new BuildStationCommand(site.B, 2));
|
||
int depot = await Ok(new BuildDepotCommand(site.Depot, "small"));
|
||
await Until(() => World.Stations.ContainsKey(b) && World.Depots.ContainsKey(depot), "stazioni");
|
||
var main = new BuildTrackCommand([site.A, site.B]);
|
||
var plan = World.PreviewTrack(main);
|
||
await Ok(main with { ExpectedCostCents = plan.TotalCost.Cents });
|
||
await Until(() => World.Edges.Count > 0, "binario");
|
||
var spur = new BuildTrackCommand([site.Depot, site.A]);
|
||
await Ok(spur with { ExpectedCostCents = World.PreviewTrack(spur).TotalCost.Cents });
|
||
|
||
// vista d'insieme del cantiere
|
||
var center = MapScale.V((site.A + site.B) / 2);
|
||
_game.Map.CenterOn(center);
|
||
_game.Map.SetZoom(0.22f);
|
||
await Shot("02_cantiere");
|
||
|
||
Session.SetSpeed(8);
|
||
await Until(() => World.Edges.Count >= 2 && World.Edges.Values.All(e => e.State == (byte)EdgeState.Active), "cantieri", 240);
|
||
var loco = await Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
|
||
var wagons = await Do(new BuyVehicleCommand("wagon_hopper", new DepotId(depot), 3));
|
||
int train = await Ok(new ComposeTrainCommand(new DepotId(depot), loco.Created.Concat(wagons.Created).Select(i => new VehicleId(i)).ToList(), "Treno 1"));
|
||
var loco2 = await Do(new BuyVehicleCommand("loco_steam_1850", new DepotId(depot), 1));
|
||
var coaches = await Do(new BuyVehicleCommand("coach_worker", new DepotId(depot), 2));
|
||
int train2 = await Ok(new ComposeTrainCommand(new DepotId(depot), loco2.Created.Concat(coaches.Created).Select(i => new VehicleId(i)).ToList(), "Treno 2"));
|
||
int line = await Ok(new CreateLineCommand("Linea 1, collaudo", "#e0a526", [new LineStop(new StationId(a)), new LineStop(new StationId(b))]));
|
||
await Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
|
||
Session.SetSpeed(1);
|
||
await Until(() => World.Motions.TryGetValue(train, out var m) && m.Speed > 3, "treno in moto", 120);
|
||
await Ok(new AssignTrainCommand(new TrainId(train2), new LineId(line)));
|
||
|
||
_game.Map.CenterOn(center);
|
||
_game.Map.SetZoom(0.22f);
|
||
await Shot("03_linea");
|
||
|
||
// ponte da vicino (immagine 02)
|
||
_game.Map.CenterOn(MapScale.V(site.River));
|
||
_game.Map.SetZoom(0.9f);
|
||
await Shot("04_ponte");
|
||
|
||
// treno da vicino (immagine 03): la camera lo segue per qualche fotogramma
|
||
for (int i = 0; i < 40; i++)
|
||
{
|
||
if (World.TrainHead(train) is { } head) _game.Map.CenterOn(MapScale.V(head));
|
||
_game.Map.SetZoom(1.4f);
|
||
await Frame();
|
||
}
|
||
_game.SelectTrain(train);
|
||
await Shot("05_treno", 5);
|
||
|
||
// scheda del treno con la mappa d'insieme
|
||
_game.Map.SetZoom(0.3f);
|
||
await Shot("06_scheda_treno", 20);
|
||
|
||
// strumento binari con il profilo di un tracciato in collina
|
||
_game.UseTool(Tool.Track);
|
||
var dir = (site.B - site.A).Normalized();
|
||
var normal = new Vec2(-dir.Y, dir.X);
|
||
var p0 = MapScale.V(site.B);
|
||
var p1 = MapScale.V(site.B + normal * 2500);
|
||
var p2 = MapScale.V(site.B + normal * 4000 + dir * 1500);
|
||
_game.SetTrackPoints([p0, p1], p2);
|
||
_game.Map.CenterOn(MapScale.V(site.B + normal * 2000 + dir * 500));
|
||
_game.Map.SetZoom(0.2f);
|
||
await Shot("07_profilo", 40);
|
||
_game.UseTool(Tool.None);
|
||
_game.Map.SetZoom(0.06f);
|
||
await Shot("08_panoramica", 60);
|
||
|
||
// manutenzione (F4): un tagliando prenotato, cartella del treno, registro officina, mappa di calore
|
||
await Ok(new ScheduleServiceCommand(new TrainId(train2), "service"));
|
||
Session.SetSpeed(8);
|
||
await Until(() => World.Trains.TryGetValue(train2, out var t2) && t2.Maintenance == TrainMaintenanceStatus.InWorkshop, "treno in officina", 240);
|
||
Session.SetSpeed(1);
|
||
_game.OpenMaintenance(train);
|
||
_game.OpenWorkshop(depot);
|
||
await Until(() => World.Cards.ContainsKey(train) && World.Workshops.TryGetValue(depot, out var reg) && reg.Jobs.Count > 0, "cartella e registro", 30);
|
||
_game.Map.CenterOn(center);
|
||
_game.Map.SetZoom(0.22f);
|
||
await Shot("09_officine", 40);
|
||
_game.ScrollPanel(1);
|
||
await Shot("09b_registro_officina", 20);
|
||
_game.ScrollPanel(0);
|
||
_game.SetHeatMap(true);
|
||
await Shot("10_mappa_di_calore", 20);
|
||
|
||
// Registro degli impieghi (sezione 9)
|
||
_game.UseTool(Tool.Employment);
|
||
await Until(() => World.Employment is not null, "registro degli impieghi", 30);
|
||
await Shot("11_impieghi", 30);
|
||
|
||
await IndustriesAndMarket(site.A);
|
||
}
|
||
|
||
/// <summary>F5: scheda del proprietario di un'industria, borsa con il libro dei soci, Cronaca provvisoria.</summary>
|
||
private async Task IndustriesAndMarket(Vec2 near)
|
||
{
|
||
int me = World.Summary!.CompanyId;
|
||
var anchor = MapScale.V(near);
|
||
var industry = World.Industries.Values.Where(i => !i.Closed && i.Owner < 0 && i.Level > 0)
|
||
.OrderBy(i => MapScale.V(i.Position).DistanceTo(anchor)).ThenBy(i => i.Id).First();
|
||
// dalla F6 la scheda dell'industria è a tutto schermo (immagine 07): 12 è la scheda di
|
||
// un'industria dei privati con l'avviso dell'acquisto rifiutato, 12b la stessa scheda in fondo
|
||
// (impianti, crescita, storico dei fermi). La mappa non si vede: niente centratura né zoom
|
||
_game.OpenIndustry(industry.Id);
|
||
await Until(() => World.IndustryCards.ContainsKey(industry.Id), "scheda dell'industria", 30);
|
||
// al livello iniziale il server rifiuta l'acquisto: l'avviso compare in alto sopra la scheda
|
||
var buy = await Do(new BuyIndustryCommand(new IndustryId(industry.Id), World.IndustryCards[industry.Id].Valuation));
|
||
GD.Print($"autopilot: acquisto di {industry.Name}: {buy.Message}");
|
||
await Shot("12_industria", 40);
|
||
_game.ScrollPanel(1);
|
||
await Shot("12b_industria_scorte", 20);
|
||
_game.ScrollPanel(0);
|
||
|
||
// borsa: azioni di una compagnia IA, qualche mese di prezzi, poi listino e libro dei soci
|
||
var ai = World.Companies.Values.Where(c => !c.IsPlayer && c.Listed && !c.Bankrupt).OrderBy(c => c.Id).FirstOrDefault();
|
||
if (ai is not null) await Ok(new BuySharesCommand(new CompanyId(ai.Id), 20_000, Money.Zero));
|
||
_game.OpenCompanies(ai?.Id ?? me);
|
||
Session.SetSpeed(8);
|
||
bool history = await Wait(() => ai is null || (World.CompanyCards.TryGetValue(ai.Id, out var card) && card.PriceHistory.Count >= 3), 200);
|
||
if (!history) GD.Print("autopilot: storico dei prezzi ancora corto");
|
||
Session.SetSpeed(1);
|
||
await Until(() => World.Tape is not null, "listino di borsa", 60);
|
||
await Shot("13_compagnie", 60);
|
||
_game.OpenCompanies(me);
|
||
await Until(() => World.CompanyCards.ContainsKey(me), "scheda della compagnia del giocatore", 30);
|
||
await Shot("14_compagnia_giocatore", 40);
|
||
|
||
// Mercato globale (immagine 06): storico, previsione, hub ed evento in corso
|
||
_game.OpenMarket();
|
||
await Until(() => World.Market is not null, "quadro del mercato", 30);
|
||
await Shot("16_mercato", 40);
|
||
|
||
// La tua scalata (immagine 08): livelli, sblocchi, requisiti, stato patrimoniale
|
||
_game.OpenClimb();
|
||
await Until(() => World.Climb is not null, "quadro della scalata", 30);
|
||
await Shot("17_scalata", 40);
|
||
|
||
// Finanze: conto economico per voce, rating spiegato, prestiti
|
||
_game.OpenFinance();
|
||
await Until(() => World.Finance is not null, "quadro delle finanze", 30);
|
||
await Shot("18_finanze", 40);
|
||
|
||
// Cronaca provvisoria
|
||
_game.OpenChronicle();
|
||
await Until(() => _game.ChronicleVisible, "cronaca", 30);
|
||
await Shot("15_cronaca", 30);
|
||
_game.CloseChronicle();
|
||
|
||
// F6, scheda dell'industria (immagine 07): un'industria di trasformazione vicino alla linea,
|
||
// con catena produttiva, forza lavoro e crescita
|
||
var processing = World.Industries.Values
|
||
.Where(i => !i.Closed && i.Level > 0 && World.Data.Industries.FirstOrDefault(d => d.Id == i.Type)?.Recipe.Inputs.Count > 0)
|
||
.OrderBy(i => MapScale.V(i.Position).DistanceTo(anchor)).ThenBy(i => i.Id).FirstOrDefault() ?? industry;
|
||
_game.OpenIndustry(processing.Id);
|
||
await Until(() => World.IndustryCards.TryGetValue(processing.Id, out var c) && c.Sheet is not null, "scheda completa dell'industria", 30);
|
||
_game.ScrollPanel(0);
|
||
await Shot("19_scheda_industria", 40);
|
||
|
||
// F6, schermata di connessione (immagine 09) sopra la partita: sessione di prova sul server
|
||
// locale con il suo stato e l'elenco dei salvataggi (uno appena fatto)
|
||
Session.Send(new Save { Name = "Collaudo" });
|
||
var launcher = Session.LocalServer ?? throw new InvalidOperationException("collaudo senza server locale");
|
||
// livello proprio sopra l'interfaccia della partita (CanvasLayer 1–3): sul livello 0 la
|
||
// schermata finirebbe sotto la scheda a tutto schermo e trasformata dalla camera della mappa
|
||
_game.CloseTools();
|
||
var layer = new CanvasLayer { Layer = 10 };
|
||
_game.AddChild(layer);
|
||
var connect = new ConnectScreen(World.Data, remember: false, autoStart: false);
|
||
layer.AddChild(connect);
|
||
await Frame();
|
||
await connect.ProbeRemote(new Uri($"ws://127.0.0.1:{launcher.Port}/ws"), launcher.Token);
|
||
await Until(() => connect.Loaded, "stato del server e salvataggi", 30);
|
||
await Shot("20_connessione", 30);
|
||
layer.QueueFree();
|
||
}
|
||
}
|