F6: compravendita in proprio e spedizione della merce tra stazioni

Dal livello che sblocca il commercio la compagnia può comprare e vendere
merci in proprio. Così può fare arbitraggio tra un produttore con il
magazzino pieno e un consumatore a secco anche dove il vettore non ha
contratti. Le regole sono nell'ADR 0016.

- Ogni stazione della compagnia ha un magazzino: 500 unità e una
  giacenza di 25 centesimi per unità al mese, in balance.json, blocco
  «trading». La merce in magazzino rientra nell'invariante delle merci.
- BuyGoods compra al prezzo locale marginale dell'ADR 0004, unità per
  unità, partendo dal più economico, dai produttori del bacino e dagli
  hub. La merce presa dagli hub conta come importata.
- SellGoods vende ai consumatori del bacino partendo dal prezzo più
  alto, entro lo spazio libero e la cassa di ciascuno. Vende anche agli
  hub, e quella merce conta come esportata.
- Il denaro di entrambi i comandi passa dal registro, sulla voce
  «Commercio».
- ShipGoods (comando 40) spedisce la merce propria come pacchetto senza
  tariffa né consumatore. Il pacchetto entra nel magazzino di
  destinazione, che riserva lo spazio alla partenza. Il percorso dei
  pacchetti già esistenti non cambia: l'accettazione F4 dà ancora
  35/20 guasti senza la linea e 75/2 con la linea.
- Il salvataggio passa al corpo versione 4 (TradingSerializer). I
  salvataggi più vecchi si caricano con i magazzini vuoti, e i magazzini
  entrano nell'hash di stato.
- MarketReport porta i magazzini nel blocco 1. Il Mercato globale ha il
  riquadro «Compravendita in proprio».
- Le IA non commerciano ancora.

Refs #31.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-07 15:26:20 +01:00
1 parent 3f00acb994
commit e157dd77bc
32 files changed
+1624 -25

No files matched your search

@@ -517,3 +517,23 @@ set,,Sep
unità/mese,,units/month
è più alto del,,is higher by
è più basso del,,is lower by
Spedisci a,,Ship to
Quantità,,Quantity
"Compra dai produttori e dagli hub nel bacino della stazione, dal prezzo più basso, fino al 10 % sopra il prezzo indicato.",,"Buys from producers and hubs in the station's catchment, cheapest first, up to 10% above the quoted price."
"Vende dal magazzino ai consumatori e agli hub nel bacino, dal prezzo più alto, fino al 10 % sotto il prezzo indicato.",,"Sells from the warehouse to consumers and hubs in the catchment, highest price first, down to 10% below the quoted price."
"Spedisce la merce sulle tue linee al magazzino di un'altra tua stazione, senza tariffa.",,"Ships the goods on your lines to the warehouse of another of your stations, with no fare."
In magazzino,,In the warehouse
Costruisci una stazione per avere un magazzino dove comprare e vendere.,,Build a station to get a warehouse where you can buy and sell.
in magazzino,,in the warehouse
Si compra a,,Buy at
disponibili,,available
Nessun produttore né hub nel bacino la vende,,No producer or hub in the catchment sells it
si vende a,,sell at
richieste,,wanted
nessun consumatore né hub nel bacino la compra,,no consumer or hub in the catchment buys it
Prezzo locale: sale man mano che il venditore si svuota e scende man mano che il compratore si riempie.,,Local price: it rises as the seller runs low and falls as the buyer fills up.
Magazzino,,Warehouse
unità,,units
di cui,,of which
Vuoto,,Empty
Scegli una stazione di arrivo diversa da quella di partenza,,Choose a destination station different from the departure one
1 keys it en
517 unità/mese units/month
518 è più alto del is higher by
519 è più basso del is lower by
520 Spedisci a Ship to
521 Quantità Quantity
522 Compra dai produttori e dagli hub nel bacino della stazione, dal prezzo più basso, fino al 10 % sopra il prezzo indicato. Buys from producers and hubs in the station's catchment, cheapest first, up to 10% above the quoted price.
523 Vende dal magazzino ai consumatori e agli hub nel bacino, dal prezzo più alto, fino al 10 % sotto il prezzo indicato. Sells from the warehouse to consumers and hubs in the catchment, highest price first, down to 10% below the quoted price.
524 Spedisce la merce sulle tue linee al magazzino di un'altra tua stazione, senza tariffa. Ships the goods on your lines to the warehouse of another of your stations, with no fare.
525 In magazzino In the warehouse
526 Costruisci una stazione per avere un magazzino dove comprare e vendere. Build a station to get a warehouse where you can buy and sell.
527 in magazzino in the warehouse
528 Si compra a Buy at
529 disponibili available
530 Nessun produttore né hub nel bacino la vende No producer or hub in the catchment sells it
531 si vende a sell at
532 richieste wanted
533 nessun consumatore né hub nel bacino la compra no consumer or hub in the catchment buys it
534 Prezzo locale: sale man mano che il venditore si svuota e scende man mano che il compratore si riempie. Local price: it rises as the seller runs low and falls as the buyer fills up.
535 Magazzino Warehouse
536 unità units
537 di cui of which
538 Vuoto Empty
539 Scegli una stazione di arrivo diversa da quella di partenza Choose a destination station different from the departure one
@@ -33,6 +33,7 @@ public partial class MarketPanel : VBoxContainer
private readonly VBoxContainer _sell = PanelKit.Column(4);
private readonly VBoxContainer _right = PanelKit.Column(14);
private readonly Dictionary<int, GoodRow> _rowByGood = [];
private readonly TradeBox _trade;
private MarketReport? _shown;
private string _rowsKey = "";
private int _selected = -1;
@@ -46,6 +47,9 @@ public partial class MarketPanel : VBoxContainer
public MarketPanel(GameSession session)
{
_session = session;
_trade = new TradeBox(session);
// dopo un comando di compravendita si chiede subito il quadro aggiornato (giacenze e prezzi)
_trade.Traded += () => _requestedDay = long.MinValue;
AddThemeConstantOverride("separation", 14);
SizeFlagsVertical = SizeFlags.ExpandFill;
@@ -111,6 +115,12 @@ public partial class MarketPanel : VBoxContainer
_subtitle.Text = T("In attesa dei prezzi dal server…");
}
public override void _Notification(int what)
{
// il riquadro della compravendita fuori dall'albero (commercio non sbloccato) va liberato a mano
if (what == NotificationPredelete && IsInstanceValid(_trade) && _trade.GetParent() is null) _trade.Free();
}
/// <summary>Bene mostrato al centro (−1 se nessuno).</summary>
public int Selected => _selected;
@@ -118,7 +128,11 @@ public partial class MarketPanel : VBoxContainer
{
_selected = good;
foreach (var (id, row) in _rowByGood) row.SetSelected(id == good);
if (_session.World.Market is { } report) ShowGood(_session.World, report);
if (_session.World.Market is { } report)
{
ShowGood(_session.World, report);
_trade.Update(report, good);
}
}
private static VBoxContainer Column(HBoxContainer body, float ratio)
@@ -425,6 +439,8 @@ public partial class MarketPanel : VBoxContainer
private void RefreshRight(ClientWorld w, MarketReport report)
{
// il riquadro della compravendita resta lo stesso nodo tra un quadro e l'altro
_trade.GetParent()?.RemoveChild(_trade);
foreach (var c in _right.GetChildren()) c.QueueFree();
foreach (var h in report.Hubs) _right.AddChild(HubCard(w, h));
_right.AddChild(EventCard(w, report));
@@ -485,7 +501,7 @@ public partial class MarketPanel : VBoxContainer
return card;
}
private static Control TradingCard(ClientWorld w, MarketReport report)
private Control TradingCard(ClientWorld w, MarketReport report)
{
var card = Card(Palette.Panel, Palette.Border);
var col = (VBoxContainer)card.GetChild(0);
@@ -494,7 +510,8 @@ public partial class MarketPanel : VBoxContainer
if (report.TradingUnlocked)
{
col.AddChild(Wrapped($"{T("Compra merci all'origine e rivendile dove il prezzo è più alto. Sbloccata al livello")} {tier}.", 13, Palette.Text));
col.AddChild(Bar(1, Palette.Amber));
col.AddChild(_trade);
_trade.Update(report, _selected);
return card;
}
col.AddChild(Wrapped($"{T("Compra merci all'origine e rivendile dove il prezzo è più alto. Si sblocca al livello")} {tier}.", 13, Palette.Text));
@@ -0,0 +1,211 @@
using Godot;
using RailEnterprise.Client.App;
using RailEnterprise.Client.Net;
using RailEnterprise.Core.Commands;
using RailEnterprise.Core.Common;
using RailEnterprise.Protocol.Client;
using RailEnterprise.Protocol.Messages;
using static RailEnterprise.Client.App.Localization;
namespace RailEnterprise.Client.Panels;
/// <summary>
/// Riquadro «Compravendita in proprio» del Mercato globale, quando il livello lo sblocca (ADR 0016):
/// scelta della stazione propria, quantità, Compra, Vendi e Spedisci a un'altra stazione per la
/// merce scelta nel pannello; giacenze del magazzino. Prezzi, disponibilità e giacenze arrivano dal
/// server nel MarketReport: i comandi li ricalcola il server. I controlli restano gli stessi tra un
/// quadro e l'altro, così le scelte non si perdono a ogni nuovo giorno.
/// </summary>
public sealed partial class TradeBox : VBoxContainer
{
/// <summary>Margine sul prezzo mostrato: si compra fino al 10 % sopra e si vende fino al 10 % sotto.</summary>
private const double PriceTolerance = 0.10;
private readonly GameSession _session;
private readonly OptionButton _station = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, ClipText = true, CustomMinimumSize = new Vector2(60, 0) };
private readonly OptionButton _destination = new() { SizeFlagsHorizontal = SizeFlags.ExpandFill, ClipText = true, CustomMinimumSize = new Vector2(60, 0) };
private readonly SpinBox _quantity = new() { MinValue = 1, MaxValue = 100_000, Step = 1, Rounded = true, Value = 50, SizeFlagsHorizontal = SizeFlags.ExpandFill };
private readonly Label _good = UiTheme.Text("", 14, bold: true);
private readonly Label _quote = UiTheme.Text("", 12, Palette.TextSecondary);
private readonly Label _capacity = UiTheme.Text("", 12, Palette.TextSecondary);
private readonly VBoxContainer _stock = PanelKit.Column(2);
private readonly Label _status = UiTheme.Text("", 12);
private readonly Button _buy = UiTheme.Primary(T("Compra"));
private readonly Button _sell = new() { Text = T("Vendi") };
private readonly Button _ship = new() { Text = T("Spedisci a") };
private readonly List<int> _stationIds = [];
private readonly List<int> _destinationIds = [];
private MarketReport? _report;
private int _goodId = -1;
/// <summary>Esito di un comando: il pannello chiede subito un quadro aggiornato.</summary>
public event Action? Traded;
public TradeBox(GameSession session)
{
_session = session;
AddThemeConstantOverride("separation", 8);
foreach (var l in new[] { _quote, _capacity, _status }) l.AutowrapMode = TextServer.AutowrapMode.WordSmart;
var station = PanelKit.Row(6);
station.AddChild(UiTheme.Text(T("Stazione"), 13, Palette.TextSecondary));
station.AddChild(_station);
AddChild(station);
_station.ItemSelected += _ => Render();
AddChild(_good);
AddChild(_quote);
var qty = PanelKit.Row(6);
qty.AddChild(UiTheme.Text(T("Quantità"), 13, Palette.TextSecondary));
qty.AddChild(_quantity);
AddChild(qty);
var trade = PanelKit.Row(6);
_buy.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_sell.SizeFlagsHorizontal = SizeFlags.ExpandFill;
_buy.TooltipText = T("Compra dai produttori e dagli hub nel bacino della stazione, dal prezzo più basso, fino al 10 % sopra il prezzo indicato.");
_sell.TooltipText = T("Vende dal magazzino ai consumatori e agli hub nel bacino, dal prezzo più alto, fino al 10 % sotto il prezzo indicato.");
_buy.Pressed += Buy;
_sell.Pressed += Sell;
trade.AddChild(_buy);
trade.AddChild(_sell);
AddChild(trade);
var ship = PanelKit.Row(6);
_ship.TooltipText = T("Spedisce la merce sulle tue linee al magazzino di un'altra tua stazione, senza tariffa.");
_ship.Pressed += Ship;
ship.AddChild(_ship);
ship.AddChild(_destination);
AddChild(ship);
AddChild(_capacity);
AddChild(UiTheme.Text(T("In magazzino"), 13, Palette.TextSecondary, bold: true));
AddChild(_stock);
AddChild(_status);
}
/// <summary>Aggiorna stazioni, quotazioni e giacenze dal quadro ricevuto, per la merce scelta.</summary>
public void Update(MarketReport report, int good)
{
_report = report;
_goodId = good;
var w = _session.World;
int keep = _station.Selected >= 0 && _station.Selected < _stationIds.Count ? _stationIds[_station.Selected] : -1;
int keepTo = _destination.Selected >= 0 && _destination.Selected < _destinationIds.Count ? _destinationIds[_destination.Selected] : -1;
_stationIds.Clear();
_station.Clear();
foreach (var h in report.Warehouses)
{
_stationIds.Add(h.Station);
_station.AddItem(StationName(w, h.Station));
}
int index = _stationIds.IndexOf(keep);
if (_stationIds.Count > 0) _station.Select(index >= 0 ? index : 0);
_destinationIds.Clear();
_destination.Clear();
foreach (var h in report.Warehouses)
{
_destinationIds.Add(h.Station);
_destination.AddItem(StationName(w, h.Station));
}
int to = _destinationIds.IndexOf(keepTo);
if (_destinationIds.Count > 0) _destination.Select(to >= 0 ? to : Math.Min(1, _destinationIds.Count - 1));
Render();
}
private WarehouseInfo? Current =>
_report is null || _station.Selected < 0 || _station.Selected >= _stationIds.Count
? null
: _report.Warehouses.FirstOrDefault(h => h.Station == _stationIds[_station.Selected]);
private WarehouseGoodInfo? CurrentGood => Current?.Goods.FirstOrDefault(g => g.Good == _goodId);
private void Render()
{
var w = _session.World;
foreach (var c in _stock.GetChildren()) c.QueueFree();
var house = Current;
bool any = house is not null && _goodId >= 0 && _goodId < w.Data.Goods.Count;
_buy.Disabled = _sell.Disabled = _ship.Disabled = !any;
if (!any)
{
_good.Text = "";
_quote.Text = T("Costruisci una stazione per avere un magazzino dove comprare e vendere.");
_capacity.Text = "";
return;
}
string unit = w.Data.Goods[_goodId].Unit;
var g = CurrentGood;
_good.Text = $"{T("Merce")}: {GoodName(w, _goodId)} · {T("in magazzino")} {g?.Units ?? 0} {unit}";
string buy = g is { BuyPrice: >= 0 }
? $"{T("Si compra a")} {Price(g.BuyPrice)}/{unit} ({Fmt.Number(g.BuyUnits, 0)} {unit} {T("disponibili")})"
: T("Nessun produttore né hub nel bacino la vende");
string sell = g is { SellPrice: >= 0 }
? $"{T("si vende a")} {Price(g.SellPrice)}/{unit} ({Fmt.Number(g.SellUnits, 0)} {unit} {T("richieste")})"
: T("nessun consumatore né hub nel bacino la compra");
_quote.Text = $"{buy}; {sell}. {T("Prezzo locale: sale man mano che il venditore si svuota e scende man mano che il compratore si riempie.")}";
_buy.Disabled = g is not { BuyPrice: >= 0 };
_sell.Disabled = g is not { SellPrice: >= 0 } || g.Units <= 0;
_ship.Disabled = (g?.Units ?? 0) <= 0 || _destinationIds.Count < 2;
int used = house!.Goods.Sum(x => x.Units) + house.Incoming;
_capacity.Text = $"{T("Magazzino")}: {Fmt.Number(used, 0)} / {Fmt.Number(house.Capacity, 0)} {T("unità")}"
+ (house.Incoming > 0 ? $" ({T("di cui")} {Fmt.Number(house.Incoming, 0)} {T("in arrivo")})" : "");
var held = house.Goods.Where(x => x.Units > 0).ToList();
if (held.Count == 0) _stock.AddChild(UiTheme.Text(T("Vuoto"), 12, Palette.TextSecondary));
foreach (var x in held)
_stock.AddChild(PanelKit.Pair(GoodName(w, x.Good), PanelKit.Value($"{Fmt.Number(x.Units, 0)} {w.Data.Goods[x.Good].Unit}")));
}
private void Buy()
{
if (Current is not { } house || CurrentGood is not { BuyPrice: >= 0 } g) return;
var max = Money.FromCentsRounded(g.BuyPrice * (1 + PriceTolerance));
_session.Command(new BuyGoodsCommand(new StationId(house.Station), GoodId(), Units(), max), Result);
}
private void Sell()
{
if (Current is not { } house || CurrentGood is not { SellPrice: >= 0 } g) return;
var min = Money.FromCentsRounded(g.SellPrice * (1 - PriceTolerance));
_session.Command(new SellGoodsCommand(new StationId(house.Station), GoodId(), Units(), min), Result);
}
private void Ship()
{
if (Current is not { } house || _destination.Selected < 0 || _destination.Selected >= _destinationIds.Count) return;
int to = _destinationIds[_destination.Selected];
if (to == house.Station)
{
ShowStatus(T("Scegli una stazione di arrivo diversa da quella di partenza"), false);
return;
}
_session.Command(new ShipGoodsCommand(new StationId(house.Station), new StationId(to), GoodId(), Units()), Result);
}
private string GoodId() => _session.World.Data.Goods[_goodId].Id;
private int Units() => (int)Math.Max(1, Math.Round(_quantity.Value));
private void Result(CommandResultMessage r)
{
ShowStatus(r.Message, r.Ok);
Traded?.Invoke();
}
private void ShowStatus(string text, bool ok)
{
_status.Text = text;
_status.AddThemeColorOverride("font_color", ok ? Palette.Ok : Palette.Danger);
}
private static string StationName(ClientWorld w, int station) =>
w.Stations.TryGetValue(station, out var s) ? s.Name : $"{T("Stazione")} {station}";
private static string GoodName(ClientWorld w, int good)
{
var def = w.Data.Goods[Math.Clamp(good, 0, w.Data.Goods.Count - 1)];
return TranslationServer.GetLocale().StartsWith("en") ? def.NameEn : def.NameIt;
}
private static string Price(double cents) => Money.FromCentsRounded(cents).ToString();
}