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:
1 parent
3f00acb994
commit
e157dd77bc
32 files changed
+1624
-25
No files matched your search
@@ -0,0 +1,463 @@
|
||||
using RailEnterprise.Core.Commands;
|
||||
using RailEnterprise.Core.Common;
|
||||
using RailEnterprise.Core.Economy;
|
||||
using RailEnterprise.Core.Persistence;
|
||||
using RailEnterprise.Core.Rail;
|
||||
using RailEnterprise.Core.Simulation;
|
||||
using RailEnterprise.Core.Simulation.Systems;
|
||||
using RailEnterprise.Protocol;
|
||||
using RailEnterprise.Protocol.Messages;
|
||||
using RailEnterprise.Tests.Harness;
|
||||
using RailEnterprise.Tests.Rail;
|
||||
using static RailEnterprise.Tests.Rail.RailFixture;
|
||||
|
||||
namespace RailEnterprise.Tests.Economy;
|
||||
|
||||
/// <summary>Compravendita in proprio e spedizione della merce tra stazioni (F6, issue #31, ADR 0016).</summary>
|
||||
public static class TradingTests
|
||||
{
|
||||
private static int GoodIndex(World w, string id) => w.Data.Goods.First(g => g.Id == id).Index;
|
||||
|
||||
private static void AssertInvariants(World w, string when)
|
||||
{
|
||||
Assert.Equal(0L, w.MoneyBalanceSum(), $"denaro {when}");
|
||||
for (int g = 0; g < w.Data.GoodCount; g++)
|
||||
Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id} {when}");
|
||||
}
|
||||
|
||||
/// <summary>Merce creata dal test nel magazzino di una stazione, contabilizzata come prodotta (ADR 0004 §4).</summary>
|
||||
private static void Inject(World w, Station s, int good, int units)
|
||||
{
|
||||
TradingMath.AddToWarehouse(s, good, units, w.Data.GoodCount);
|
||||
w.Goods.Produced[good] += units;
|
||||
}
|
||||
|
||||
private static void Unlock(World w) => w.Player.Tier = w.Data.Tiers.Tiers.First(t => t.Unlocks.Trading).Level;
|
||||
|
||||
/// <summary>Valdoria con le stazioni delle miniere, dell'acciaieria e del porto, senza binari.</summary>
|
||||
private static (RailFixture F, Station Mine, Station Mill, Station Port) Stations()
|
||||
{
|
||||
var f = Valdoria();
|
||||
int mine = f.Ok(new BuildStationCommand(K(2.2, 2.6), 2, "Rocca Bruna"));
|
||||
int mill = f.Ok(new BuildStationCommand(K(10.6, 5.4), 4, "Acciaieria"));
|
||||
int port = f.Ok(new BuildStationCommand(K(14.5, 6.3), 2, "Porto di Levante"));
|
||||
var net = f.W.Network;
|
||||
return (f, net.Stations[mine], net.Stations[mill], net.Stations[port]);
|
||||
}
|
||||
|
||||
[Test(Description = "Compra dal produttore del bacino al prezzo locale marginale: prezzo, cassa, registro e giacenze esatti")]
|
||||
public static void BuyFromProducerAtTheLocalPrice()
|
||||
{
|
||||
var (f, mine, _, _) = Stations();
|
||||
var w = f.W;
|
||||
Unlock(w);
|
||||
int ore = GoodIndex(w, "iron_ore");
|
||||
var producer = w.Industries.First(i => i.Def.Id == "iron_mine");
|
||||
Assert.True(mine.Industries.Contains(producer.Id), "la miniera è nel bacino");
|
||||
int cap = IndustryMath.OutputCapacity(producer, 0, w.Calendar.DaysPerMonth);
|
||||
int start = cap / 2;
|
||||
Assert.True(start > 60, $"capienza del minerale della miniera: {cap}");
|
||||
w.Goods.Produced[ore] += start - producer.OutputStock[0];
|
||||
producer.OutputStock[0] = start;
|
||||
|
||||
// prezzo atteso: ogni unità al prezzo locale con la giacenza che resta (Dl = spazio libero, Sl = giacenza)
|
||||
const int units = 40;
|
||||
double pg = w.Market.GlobalPrice[ore];
|
||||
var lp = w.Data.Balance.LocalPrice;
|
||||
double expected = 0;
|
||||
for (int k = 0; k < units; k++) expected += Market.LocalPrice(pg, cap - (start - k), start - k, lp);
|
||||
Assert.Approx(pg, Market.LocalPrice(pg, cap - start, start, lp), pg * 0.02, "a metà magazzino il prezzo è quello globale");
|
||||
var cost = Money.FromCentsRounded(expected);
|
||||
var cash = w.Player.Cash;
|
||||
var industryCash = producer.Cash;
|
||||
long trading = w.Player.MonthEntries[(int)LedgerEntry.Trading];
|
||||
|
||||
var r = f.Do(new BuyGoodsCommand(mine.Id, "iron_ore", units, Money.FromLire(1000)));
|
||||
Assert.True(r.Ok, r.Message);
|
||||
Assert.True(r.Message.Contains("Comprate 40 t", StringComparison.Ordinal), r.Message);
|
||||
Assert.Equal(units, mine.StockOf(ore));
|
||||
Assert.Equal(cash - cost, w.Player.Cash);
|
||||
Assert.Equal(industryCash + cost, producer.Cash);
|
||||
Assert.Equal(trading - cost.Cents, w.Player.MonthEntries[(int)LedgerEntry.Trading]);
|
||||
Assert.True(producer.LastServedDay >= w.Clock.Day - 1, "la miniera è servita");
|
||||
AssertInvariants(w, "dopo l'acquisto");
|
||||
|
||||
// il prezzo sale man mano che il produttore si svuota: con un tetto sotto il prossimo prezzo si compra meno
|
||||
double next = Market.LocalPrice(pg, cap - (producer.OutputStock[0]), producer.OutputStock[0], lp);
|
||||
var capped = f.Do(new BuyGoodsCommand(mine.Id, "iron_ore", 1000, Money.FromCentsRounded(next + 30)));
|
||||
Assert.True(capped.Ok, capped.Message);
|
||||
Assert.True(mine.StockOf(ore) > units && mine.StockOf(ore) < units + start - units, $"comprate {mine.StockOf(ore) - units} unità sotto il tetto");
|
||||
Assert.True(capped.Message.Contains("tetto", StringComparison.Ordinal), capped.Message);
|
||||
AssertInvariants(w, "dopo l'acquisto con il tetto");
|
||||
}
|
||||
|
||||
[Test(Description = "Compra dall'hub del bacino al prezzo d'importazione: conta come importato e usa la capacità dell'hub")]
|
||||
public static void BuyFromHubCountsAsImported()
|
||||
{
|
||||
var (f, _, _, port) = Stations();
|
||||
var w = f.W;
|
||||
Unlock(w);
|
||||
int coal = GoodIndex(w, "coal");
|
||||
var hub = w.Hubs[0];
|
||||
Assert.True(port.Hubs.Contains(hub.Id), "il porto è nel bacino");
|
||||
int imported = (int)w.Goods.Imported[coal];
|
||||
int used = hub.UsedThisMonth;
|
||||
double price = hub.SellPrice(w.Market.GlobalPrice[coal]);
|
||||
var cash = w.Player.Cash;
|
||||
var external = w.Money.External;
|
||||
|
||||
var r = f.Do(new BuyGoodsCommand(port.Id, "coal", 60, Money.FromCentsRounded(price + 1)));
|
||||
Assert.True(r.Ok, r.Message);
|
||||
Assert.Equal(60, port.StockOf(coal));
|
||||
Assert.Equal(imported + 60L, w.Goods.Imported[coal]);
|
||||
Assert.Equal(used + 60, hub.UsedThisMonth);
|
||||
Assert.Approx(60 * price, (cash - w.Player.Cash).Cents, 1);
|
||||
Assert.Equal(external + (cash - w.Player.Cash), w.Money.External);
|
||||
AssertInvariants(w, "dopo l'importazione");
|
||||
|
||||
// il tetto sotto il prezzo dell'hub rifiuta senza cambiare nulla
|
||||
var refused = f.Do(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromCentsRounded(price - 100)));
|
||||
Assert.Equal(CommandError.InvalidArgument, refused.Error);
|
||||
Assert.Equal(60, port.StockOf(coal));
|
||||
}
|
||||
|
||||
[Test(Description = "Vende al consumatore del bacino al prezzo locale (decrescente), entro spazio e cassa dell'industria")]
|
||||
public static void SellToConsumerWithinSpaceAndCash()
|
||||
{
|
||||
var (f, _, mill, _) = Stations();
|
||||
var w = f.W;
|
||||
Unlock(w);
|
||||
int ore = GoodIndex(w, "iron_ore");
|
||||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
int input = steel.InputIndexOf(ore);
|
||||
int desired = IndustryMath.InputCapacity(steel, input, w.Calendar.DaysPerMonth);
|
||||
Assert.True(mill.Industries.Contains(steel.Id) && desired > 10, $"acciaieria nel bacino, capienza {desired}");
|
||||
w.Goods.Consumed[ore] += steel.InputStock[input];
|
||||
steel.InputStock[input] = 0;
|
||||
Inject(w, mill, ore, desired + 50);
|
||||
// cassa dell'acciaieria abbondante
|
||||
w.Money.Transfer(Account.External, Account.Of(steel.Id), Money.FromLire(1_000_000), LedgerEntry.Other);
|
||||
|
||||
double pg = w.Market.GlobalPrice[ore];
|
||||
var lp = w.Data.Balance.LocalPrice;
|
||||
int units = desired / 2;
|
||||
double expected = 0;
|
||||
for (int k = 0; k < units; k++) expected += Market.LocalPrice(pg, desired, k, lp);
|
||||
Assert.True(Market.LocalPrice(pg, desired, 0, lp) > pg * 1.3, "a magazzino vuoto il consumatore paga di più");
|
||||
var cash = w.Player.Cash;
|
||||
var r = f.Do(new SellGoodsCommand(mill.Id, "iron_ore", units, Money.FromLire(1)));
|
||||
Assert.True(r.Ok, r.Message);
|
||||
Assert.Equal(units, steel.InputStock[input]);
|
||||
Assert.Equal(desired + 50 - units, mill.StockOf(ore));
|
||||
Assert.Equal(cash + Money.FromCentsRounded(expected), w.Player.Cash);
|
||||
AssertInvariants(w, "dopo la vendita");
|
||||
|
||||
// il prezzo minimo sopra quello offerto rifiuta
|
||||
var refused = f.Do(new SellGoodsCommand(mill.Id, "iron_ore", 5, Money.FromLire(10_000)));
|
||||
Assert.Equal(CommandError.InvalidArgument, refused.Error);
|
||||
|
||||
// un'industria con poca cassa compra solo quanto può pagare
|
||||
w.Money.Transfer(Account.Of(steel.Id), Account.External, steel.Cash, LedgerEntry.Other);
|
||||
double one = Market.LocalPrice(pg, desired, steel.InputStock[input], lp);
|
||||
w.Money.Transfer(Account.External, Account.Of(steel.Id), Money.FromCentsRounded(one * 3.5), LedgerEntry.Other);
|
||||
var poor = f.Do(new SellGoodsCommand(mill.Id, "iron_ore", 20, Money.FromLire(1)));
|
||||
Assert.True(poor.Ok, poor.Message);
|
||||
Assert.Equal(units + 3, steel.InputStock[input]);
|
||||
Assert.True(steel.Cash.Cents >= 0, "l'industria non va in rosso");
|
||||
AssertInvariants(w, "dopo la vendita a credito limitato");
|
||||
|
||||
// senza cassa nessuna vendita
|
||||
w.Money.Transfer(Account.Of(steel.Id), Account.External, steel.Cash, LedgerEntry.Other);
|
||||
Assert.Equal(CommandError.InsufficientFunds, f.Do(new SellGoodsCommand(mill.Id, "iron_ore", 5, Money.FromLire(1))).Error);
|
||||
}
|
||||
|
||||
[Test(Description = "Vende all'hub del bacino al prezzo d'esportazione: conta come esportato")]
|
||||
public static void SellToHubCountsAsExported()
|
||||
{
|
||||
var (f, _, _, port) = Stations();
|
||||
var w = f.W;
|
||||
Unlock(w);
|
||||
int coal = GoodIndex(w, "coal");
|
||||
var hub = w.Hubs[0];
|
||||
Inject(w, port, coal, 40);
|
||||
long exported = w.Goods.Exported[coal];
|
||||
double price = hub.BuyPrice(w.Market.GlobalPrice[coal]);
|
||||
var cash = w.Player.Cash;
|
||||
var r = f.Do(new SellGoodsCommand(port.Id, "coal", 100, Money.FromCentsRounded(price - 1)));
|
||||
Assert.True(r.Ok, r.Message);
|
||||
Assert.Equal(0, port.StockOf(coal));
|
||||
Assert.Equal(exported + 40, w.Goods.Exported[coal]);
|
||||
Assert.Approx(40 * price, (w.Player.Cash - cash).Cents, 1);
|
||||
AssertInvariants(w, "dopo l'esportazione");
|
||||
Assert.Equal(CommandError.NotFound, f.Do(new SellGoodsCommand(port.Id, "coal", 1, Money.Zero)).Error);
|
||||
}
|
||||
|
||||
[Test(Description = "Rifiuti: livello, stazione altrui o demolita, merce sconosciuta o dell'era futura, prezzo, cassa, magazzino pieno")]
|
||||
public static void InvalidTradesAreRefusedWithoutEffects()
|
||||
{
|
||||
var (f, mine, mill, port) = Stations();
|
||||
var w = f.W;
|
||||
int coal = GoodIndex(w, "coal");
|
||||
Assert.Equal(1, w.Player.Tier);
|
||||
var locked = f.Do(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromLire(1000)));
|
||||
Assert.Equal(CommandError.TierLocked, locked.Error);
|
||||
Assert.True(locked.Message.Contains("Compagnia regionale", StringComparison.Ordinal), locked.Message);
|
||||
Assert.Equal(CommandError.TierLocked, f.Do(new ShipGoodsCommand(port.Id, mill.Id, "coal", 1)).Error);
|
||||
Unlock(w);
|
||||
|
||||
Assert.Equal(CommandError.NotFound, f.Do(new BuyGoodsCommand(port.Id, "unobtainium", 10, Money.FromLire(1000))).Error);
|
||||
Assert.Equal(CommandError.NotFound, f.Do(new BuyGoodsCommand(new StationId(999), "coal", 10, Money.FromLire(1000))).Error);
|
||||
Assert.Equal(CommandError.InvalidArgument, f.Do(new BuyGoodsCommand(port.Id, "coal", 0, Money.FromLire(1000))).Error);
|
||||
var future = w.Data.Goods.First(g => g.Era > w.Clock.Year);
|
||||
Assert.Equal(CommandError.EraLocked, f.Do(new BuyGoodsCommand(port.Id, future.Id, 10, Money.FromLire(1000))).Error);
|
||||
Assert.Equal(CommandError.NotFound, f.Do(new BuyGoodsCommand(mill.Id, "goods", 10, Money.FromLire(1000))).Error, "nessun venditore");
|
||||
|
||||
// stazione di un'altra compagnia
|
||||
var owner = port.Owner;
|
||||
port.Owner = new CompanyId(owner.Value + 1);
|
||||
var foreign = f.Do(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromLire(1000)));
|
||||
Assert.Equal(CommandError.NotAllowed, foreign.Error);
|
||||
port.Owner = owner;
|
||||
|
||||
// cassa insufficiente
|
||||
var cash = w.Player.Cash;
|
||||
w.Money.Transfer(Account.Of(f.Me), Account.External, cash, LedgerEntry.Other);
|
||||
Assert.Equal(CommandError.InsufficientFunds, f.Do(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromLire(1000))).Error);
|
||||
w.Money.Transfer(Account.External, Account.Of(f.Me), cash, LedgerEntry.Other);
|
||||
|
||||
// magazzino pieno
|
||||
int capacity = w.Data.Balance.Trading.WarehouseCapacity;
|
||||
Inject(w, port, coal, capacity);
|
||||
var full = f.Do(new BuyGoodsCommand(port.Id, "coal", 1, Money.FromLire(1000)));
|
||||
Assert.Equal(CommandError.Blocked, full.Error);
|
||||
Assert.Equal(capacity, port.StockOf(coal));
|
||||
Assert.Equal(CommandError.NotFound, f.Do(new ShipGoodsCommand(port.Id, mine.Id, "coal", 10)).Error, "nessun percorso");
|
||||
Assert.Equal(CommandError.InvalidArgument, f.Do(new ShipGoodsCommand(port.Id, port.Id, "coal", 10)).Error);
|
||||
Assert.Equal(CommandError.NotFound, f.Do(new SellGoodsCommand(mine.Id, "coal", 10, Money.Zero)).Error, "magazzino vuoto");
|
||||
|
||||
// una stazione con merce in magazzino non si demolisce
|
||||
var demolish = f.Do(new DemolishCommand(DemolishTarget.Station, port.Id.Value));
|
||||
Assert.Equal(CommandError.NotAllowed, demolish.Error);
|
||||
Assert.True(w.Network.IsAlive(port));
|
||||
AssertInvariants(w, "dopo i rifiuti");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rete merci di Valdoria con un treno di carri coperti tra le miniere e l'acciaieria: la linea non
|
||||
/// porta minerale né acciaio, quindi le uniche merci a bordo sono quelle spedite dalla compagnia.
|
||||
/// </summary>
|
||||
private static (RailFixture F, Station Mine, Station Mill, Train Train) BoxLine()
|
||||
{
|
||||
var f = Valdoria();
|
||||
var (mine, mill, depot) = f.BuildFreightNetwork();
|
||||
int train = f.Train(depot, "Coperti 1", ("loco_steam_1850", 1), ("wagon_box", 4));
|
||||
int line = f.Ok(new CreateLineCommand("Linea 1", "#e0a526", new[] { new LineStop(new StationId(mine)), new LineStop(new StationId(mill)) }));
|
||||
f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
|
||||
Unlock(f.W);
|
||||
return (f, f.W.Network.Stations[mine], f.W.Network.Stations[mill], f.W.Trains[train]);
|
||||
}
|
||||
|
||||
[Test(Slow = true, Description = "Spedizione tra due stazioni della compagnia: consegnata nel magazzino di destinazione, senza tariffa né consumatori")]
|
||||
public static void ShippedGoodsReachTheDestinationWarehouseWithoutFare()
|
||||
{
|
||||
var (f, mine, mill, train) = BoxLine();
|
||||
var w = f.W;
|
||||
int goods = GoodIndex(w, "goods");
|
||||
Inject(w, mine, goods, 50);
|
||||
|
||||
var r = f.Do(new ShipGoodsCommand(mine.Id, mill.Id, "goods", 80));
|
||||
Assert.True(r.Ok, r.Message);
|
||||
Assert.Equal(1, r.Created.Length);
|
||||
Assert.Equal(0, mine.StockOf(goods));
|
||||
Assert.Equal(50, TradingMath.ReservedByStation(w)[mill.Id.Value]);
|
||||
Assert.Equal(w.Data.Balance.Trading.WarehouseCapacity - 50, TradingMath.FreeSpace(w, mill, 50));
|
||||
var packet = mine.Waiting.Single(p => p.Owned);
|
||||
Assert.Equal(r.Created[0], packet.Id);
|
||||
Assert.Equal(0, mill.Incoming[goods]);
|
||||
AssertInvariants(w, "alla spedizione");
|
||||
|
||||
// ricavi merci giorno per giorno (le voci annuali si azzerano a capodanno)
|
||||
long revenue = 0, before = w.Player.YearEntries[(int)LedgerEntry.FreightRevenue];
|
||||
int year = w.Clock.Year;
|
||||
bool onBoard = false;
|
||||
bool arrived = f.RunUntil(() =>
|
||||
{
|
||||
onBoard |= train.Cargo.Any(p => p.Owned);
|
||||
long now = w.Player.YearEntries[(int)LedgerEntry.FreightRevenue];
|
||||
if (w.Clock.Year != year)
|
||||
{
|
||||
revenue += w.Player.LastYearEntries[(int)LedgerEntry.FreightRevenue] - before;
|
||||
before = 0;
|
||||
year = w.Clock.Year;
|
||||
}
|
||||
revenue += now - before;
|
||||
before = now;
|
||||
return mill.StockOf(goods) == 50;
|
||||
}, 120);
|
||||
Assert.True(arrived, "la merce arriva all'acciaieria");
|
||||
Assert.True(onBoard, "la merce ha viaggiato sul treno");
|
||||
Assert.Equal(0L, revenue, "nessuna tariffa per la merce propria");
|
||||
Assert.Equal(0, TradingMath.ReservedByStation(w)[mill.Id.Value]);
|
||||
Assert.False(mill.Waiting.Any(p => p.Owned) || train.Cargo.Any(p => p.Owned), "nessun pacchetto proprio rimasto");
|
||||
AssertInvariants(w, "all'arrivo");
|
||||
|
||||
// il magazzino pieno a destinazione rifiuta la spedizione a priori
|
||||
Inject(w, mine, goods, 10);
|
||||
Inject(w, mill, goods, w.Data.Balance.Trading.WarehouseCapacity - 50);
|
||||
Assert.Equal(CommandError.Blocked, f.Do(new ShipGoodsCommand(mine.Id, mill.Id, "goods", 10)).Error);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Un anno di commercio sulla rete merci di Valdoria (treno a tramogge): ogni mese si compra
|
||||
/// minerale dalla miniera, lo si spedisce all'acciaieria e si vende quello arrivato; restituisce il mondo.
|
||||
/// </summary>
|
||||
private static World TradingYear(Func<World, World>? midway = null, Action<string>? log = null)
|
||||
{
|
||||
var f = Valdoria();
|
||||
var (mineId, millId, depot) = f.BuildFreightNetwork();
|
||||
int portId = f.Ok(new BuildStationCommand(K(14.5, 6.3), 2, "Porto di Levante"));
|
||||
int train = f.Train(depot, "Merci 1", ("loco_steam_1850", 1), ("wagon_hopper", 4));
|
||||
int line = f.Ok(new CreateLineCommand("Linea 1", "#e0a526", new[] { new LineStop(new StationId(mineId)), new LineStop(new StationId(millId)) }));
|
||||
f.Ok(new AssignTrainCommand(new TrainId(train), new LineId(line)));
|
||||
Unlock(f.W);
|
||||
var w = f.W;
|
||||
int dpm = w.Calendar.DaysPerMonth;
|
||||
for (int month = 0; month < 12; month++)
|
||||
{
|
||||
var mine = w.Network.Stations[mineId];
|
||||
var mill = w.Network.Stations[millId];
|
||||
Enqueue(w, new BuyGoodsCommand(mine.Id, "iron_ore", 30, Money.FromLire(1000)));
|
||||
Enqueue(w, new ShipGoodsCommand(mine.Id, mill.Id, "iron_ore", 30));
|
||||
Enqueue(w, new SellGoodsCommand(mill.Id, "iron_ore", 25, Money.FromLire(1)));
|
||||
Enqueue(w, new BuyGoodsCommand(mill.Id, "steel", 5, Money.FromLire(1000)));
|
||||
// al porto: importazione e rivendita all'hub di metà del carbone comprato
|
||||
var port = w.Network.Stations[portId];
|
||||
Enqueue(w, new BuyGoodsCommand(port.Id, "coal", 40, Money.FromLire(1000)));
|
||||
Enqueue(w, new SellGoodsCommand(port.Id, "coal", 20, Money.FromLire(1)));
|
||||
if (month == 6 && midway is not null)
|
||||
{
|
||||
// salvataggio a due giorni dai comandi: la merce spedita è ancora in viaggio
|
||||
w.RunDays(2);
|
||||
foreach (var r in w.DrainResults()) log?.Invoke($"{r.Type}: {r.Error} {r.Message}");
|
||||
w = midway(w);
|
||||
w.RunDays(dpm - 2);
|
||||
}
|
||||
else
|
||||
{
|
||||
w.RunDays(dpm);
|
||||
}
|
||||
foreach (var r in w.DrainResults()) log?.Invoke($"{r.Type}: {r.Error} {r.Message}");
|
||||
for (int g = 0; g < w.Data.GoodCount; g++)
|
||||
Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"merce {w.Data.Goods[g].Id} al mese {month}");
|
||||
Assert.Equal(0L, w.MoneyBalanceSum(), $"denaro al mese {month}");
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
private static void Enqueue(World w, GameCommand c) => w.Enqueue(c with { Issuer = w.Player.Id });
|
||||
|
||||
[Test(Slow = true, Description = "Un anno di compravendita e spedizioni: invarianti di denaro e merci sempre veri, giacenze addebitate")]
|
||||
public static void InvariantsHoldThroughAYearOfTrading()
|
||||
{
|
||||
var lines = new List<string>();
|
||||
var w = TradingYear(log: lines.Add);
|
||||
int Ok(string type) => lines.Count(l => l.StartsWith(type + ": None", StringComparison.Ordinal));
|
||||
Console.WriteLine($" riusciti: acquisti {Ok("BuyGoods")}, spedizioni {Ok("ShipGoods")}, vendite {Ok("SellGoods")} su {lines.Count} comandi");
|
||||
Assert.True(Ok("BuyGoods") >= 12 && Ok("ShipGoods") >= 6 && Ok("SellGoods") >= 6, string.Join(Environment.NewLine, lines));
|
||||
Assert.True(w.Player.YearEntries[(int)LedgerEntry.Trading] != 0 || w.Player.LastYearEntries[(int)LedgerEntry.Trading] != 0, "voce «Commercio» movimentata");
|
||||
var steel = w.Industries.First(i => i.Def.Id == "steel_mill");
|
||||
Assert.True(steel.LastServedDay >= 0, "l'acciaieria è stata servita");
|
||||
}
|
||||
|
||||
[Test(Slow = true, Description = "Determinismo e salvataggi: stessi comandi di commercio → stesso hash, anche passando da un salvataggio con merce in magazzino e in viaggio")]
|
||||
public static void TradingIsDeterministicAndSurvivesSaves()
|
||||
{
|
||||
bool sawStock = false, sawTransit = false;
|
||||
World ThroughSave(World w)
|
||||
{
|
||||
sawStock = w.Network.Stations.Any(s => s.StockTotal > 0);
|
||||
sawTransit = w.Network.Stations.Any(s => s.Waiting.Any(p => p.Owned)) || w.Trains.Any(t => t.Cargo.Any(p => p.Owned));
|
||||
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
||||
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded), "hash subito dopo il caricamento");
|
||||
for (int i = 0; i < w.Network.Stations.Count; i++)
|
||||
{
|
||||
Assert.SequenceEqual(w.Network.Stations[i].Stock, loaded.Network.Stations[i].Stock, $"magazzino della stazione {i}");
|
||||
Assert.SequenceEqual(w.Network.Stations[i].Waiting.Select(p => p.Owned), loaded.Network.Stations[i].Waiting.Select(p => p.Owned));
|
||||
}
|
||||
for (int i = 0; i < w.Trains.Count; i++)
|
||||
Assert.SequenceEqual(w.Trains[i].Cargo.Select(p => p.Owned), loaded.Trains[i].Cargo.Select(p => p.Owned), $"carico del treno {i}");
|
||||
return loaded;
|
||||
}
|
||||
var a = TradingYear();
|
||||
var b = TradingYear();
|
||||
var c = TradingYear(ThroughSave);
|
||||
Assert.Equal(a.LastStateHash, b.LastStateHash, "stesso seme e stessi comandi");
|
||||
Assert.True(sawStock, "il salvataggio contiene merce in magazzino");
|
||||
Assert.True(sawTransit, "il salvataggio contiene merce in viaggio");
|
||||
Assert.Equal(a.LastStateHash, c.LastStateHash, "salvare e ricaricare non cambia il futuro");
|
||||
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(c));
|
||||
}
|
||||
|
||||
[Test(Description = "Un salvataggio della versione 3 (prima del commercio) si carica con i magazzini vuoti e lo stesso stato")]
|
||||
public static void VersionThreeSavesLoadWithEmptyWarehouses()
|
||||
{
|
||||
var (f, _, _, port) = Stations();
|
||||
var w = f.W;
|
||||
w.RunDays(5);
|
||||
var body = new SaveWriter(1 << 20);
|
||||
WorldSerializer.Write(w, body, 3);
|
||||
var loaded = WorldSerializer.Read(TestData.Data, new SaveReader(body.WrittenSpan.ToArray()));
|
||||
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded), "stesso stato dinamico");
|
||||
Assert.True(loaded.Network.Stations.All(s => s.Stock.Length == TestData.Data.GoodCount && s.StockTotal == 0), "magazzini vuoti");
|
||||
|
||||
// la partita caricata commercia normalmente
|
||||
Unlock(loaded);
|
||||
loaded.Enqueue(new BuyGoodsCommand(port.Id, "coal", 10, Money.FromLire(1000)) { Issuer = loaded.Player.Id });
|
||||
loaded.RunTicks(1);
|
||||
Assert.True(loaded.DrainResults().Last().Ok);
|
||||
Assert.Equal(10, loaded.Network.Stations[port.Id.Value].StockOf(GoodIndex(loaded, "coal")));
|
||||
Assert.Throws<ArgumentOutOfRangeException>(() => WorldSerializer.Write(w, new SaveWriter(16), WorldSerializer.BodyVersion + 1));
|
||||
}
|
||||
|
||||
[Test(Description = "Il quadro del mercato porta al client i magazzini della compagnia con giacenze e prezzi locali")]
|
||||
public static void MarketReportCarriesTheWarehouses()
|
||||
{
|
||||
var (f, mine, _, port) = Stations();
|
||||
var w = f.W;
|
||||
Unlock(w);
|
||||
Assert.True(f.Do(new BuyGoodsCommand(port.Id, "coal", 25, Money.FromLire(1000))).Ok);
|
||||
var report = RailEnterprise.Server.Projection.Market(w, f.Me);
|
||||
Assert.Equal(3, report.Warehouses.Count);
|
||||
var house = report.Warehouses.Single(h => h.Station == port.Id.Value);
|
||||
Assert.Equal(w.Data.Balance.Trading.WarehouseCapacity, house.Capacity);
|
||||
int coal = GoodIndex(w, "coal");
|
||||
var g = house.Goods.Single(x => x.Good == coal);
|
||||
Assert.Equal(25, g.Units);
|
||||
Assert.Approx(w.Hubs[0].SellPrice(w.Market.GlobalPrice[coal]), g.BuyPrice, 1e-9);
|
||||
Assert.Approx(w.Hubs[0].BuyPrice(w.Market.GlobalPrice[coal]), g.SellPrice, 1e-9);
|
||||
var ore = report.Warehouses.Single(h => h.Station == mine.Id.Value).Goods.Single(x => x.Good == GoodIndex(w, "iron_ore"));
|
||||
Assert.True(ore.BuyUnits > 0 && ore.BuyPrice > 0, "la miniera vende minerale");
|
||||
|
||||
// round-trip del blocco 1 di MarketReport
|
||||
var decoded = (MarketReport)Frame.Decode(Frame.Encode(report));
|
||||
Assert.Equal(report.Warehouses.Count, decoded.Warehouses.Count);
|
||||
Assert.Equal(25, decoded.Warehouses.Single(h => h.Station == port.Id.Value).Goods.Single(x => x.Good == coal).Units);
|
||||
// la merce in magazzino entra nelle scorte del mercato globale
|
||||
Assert.Equal(MarketOutlook.StockUnits(w, coal), w.Industries.Where(i => !i.Closed && i.InputIndexOf(coal) >= 0).Sum(i => (double)i.InputStock[i.InputIndexOf(coal)])
|
||||
+ w.Industries.Where(i => !i.Closed && i.OutputIndexOf(coal) >= 0).Sum(i => (double)i.OutputStock[i.OutputIndexOf(coal)])
|
||||
+ w.Network.Stations.Where(s => w.Network.IsAlive(s)).Sum(s => s.Waiting.Where(p => p.Kind == PacketKind.Freight && p.Good == coal).Sum(p => (double)p.Units) + s.StockOf(coal)));
|
||||
}
|
||||
|
||||
[Test(Description = "ShipGoods (comando 40) sopravvive al round-trip del protocollo con tutti i campi")]
|
||||
public static void ShipGoodsRoundTrips()
|
||||
{
|
||||
var c = new ShipGoodsCommand(new StationId(3), new StationId(7), "iron_ore", 120);
|
||||
var decoded = (ShipGoodsCommand)((CommandMessage)Frame.Decode(Frame.Encode(new CommandMessage { Seq = 5, Command = c }))).Command;
|
||||
Assert.Equal((ushort)40, (ushort)decoded.Type);
|
||||
Assert.Equal(c.From, decoded.From);
|
||||
Assert.Equal(c.To, decoded.To);
|
||||
Assert.Equal("iron_ore", decoded.Good);
|
||||
Assert.Equal(120, decoded.Units);
|
||||
Assert.Equal(5u, decoded.Seq);
|
||||
}
|
||||
}
|
||||
@@ -148,6 +148,15 @@ public static class ProtocolTests
|
||||
EventGood = 8, EventShock = -0.18f, EventMonths = 5.9f,
|
||||
TradingUnlocked = false, TradingTier = 2, TradingProgress = 0.58f, NetWorth = new Money(23_200_000), NetWorthRequired = new Money(40_000_000),
|
||||
TownsConnected = 1, TownsRequired = 2, TownPopulation = 800, Rating = "BBB", RatingRequired = "BB", RatingMet = true,
|
||||
Warehouses =
|
||||
[
|
||||
new WarehouseInfo
|
||||
{
|
||||
Station = 3, Capacity = 500, Incoming = 40,
|
||||
Goods = [new WarehouseGoodInfo { Good = 8, Units = 120, BuyPrice = 9900.5, BuyUnits = 300, SellPrice = 14200.25, SellUnits = 80 }, new WarehouseGoodInfo { Good = 2, Units = 0 }],
|
||||
},
|
||||
new WarehouseInfo { Station = 5, Capacity = 500 },
|
||||
],
|
||||
};
|
||||
yield return new CommandResultMessage { Seq = 99, Type = (ushort)CommandType.BuildTrack, Error = 10, Message = "Pendenza eccessiva", Created = [1, 2, 3], Tick = 4000 };
|
||||
yield return new Notification { Event = SampleEvent() };
|
||||
@@ -257,6 +266,7 @@ public static class ProtocolTests
|
||||
yield return new FundResearchCommand("electric_traction", Money.FromLire(20000));
|
||||
yield return new DelegateRegionCommand(new RegionId(1), "crescita", Money.FromLire(500000));
|
||||
yield return new MergeCompanyCommand(new CompanyId(2));
|
||||
yield return new ShipGoodsCommand(new StationId(1), new StationId(4), "iron_ore", 75);
|
||||
}
|
||||
|
||||
[Test(Description = "Ogni messaggio del protocollo ha un esemplare e sopravvive a codifica e decodifica byte per byte")]
|
||||
|
||||
Reference in new issue
Block a user