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>
212 lines
9.9 KiB
C#
212 lines
9.9 KiB
C#
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();
|
|
}
|