F5: manutenzione delle industrie, livelli, borsa e scalate, agenti IA

- Sezione 11: usura e recupero degli impianti, fermi e incidenti, ricambi e macchinari come
  domanda esplicita (treno, trasporto locale, trasbordo nel bacino), revisione e ammodernamento,
  acquisto delle industrie dal livello 3, conguaglio mensile con il proprietario (ADR 0011).
- Livelli della compagnia con soglie ritarate e ritaratura economica misurata con le IA.
- Sezione 12.2–12.3: libro dei soci, prezzo con sentiment, quotazione, riacquisto, dividendi,
  controllo e fusione (comando 39), offerte pubbliche con difese, esiti per difficoltà,
  aste delle IA fallite, nuovi concorrenti, fine partita e Cronaca finale (ADR 0012).
- Sezione 12.1: agenti IA con candidati, Dijkstra sulle celle, TrackPreview e ROI, tre
  personalità, linee dei ricambi, rimedio agli stalli, borsa (ADR 0013).
- Salvataggio versione 3, protocollo (messaggi 126–128, blocchi di estensione), server,
  simulate --trace-ai; test di 14.5 su IA e borsa e accettazione F5 (120 test).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_0191R7vXgtbAvSV4V8tj8uzL
This commit is contained in:
Claude committed 2026-10-12 10:36:31 +00:00
1 parent 8d2fdd79e5
commit 7879ac502d
72 files changed
+5851 -122

No files matched your search

+87
View File
@@ -0,0 +1,87 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Persistence;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Ai;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Economy;
/// <summary>Concorrenti IA (guida 12.1, test di 14.5): comandi validi, crescita, determinismo.</summary>
public static class AiTests
{
[Test(Slow = true, Description = "Le IA agiscono solo con i comandi e ne vedono rifiutati al massimo il 5 %")]
public static void AiCommandsAreRarelyRejected()
{
var w = TestWorlds.Small(42);
w.RunYears(5);
Assert.True(w.AiStates.Count >= 2, "uno stato per ogni IA");
long issued = 0;
foreach (var s in w.AiStates)
{
issued += s.Issued;
Assert.True(s.RejectedShare <= w.Data.Ai.Planning.MaxRejectedShare,
$"{w.Company(s.Company).Name}: {s.Rejected} rifiutati su {s.Issued}");
}
Assert.True(issued > 20, $"le IA costruiscono e gestiscono la rete ({issued} comandi)");
Assert.True(w.AiStates.Any(s => s.Projects.Any(p => p.Stage == AiProjectStage.Running)), "almeno una linea in esercizio");
// i binari, i treni e le stazioni delle IA esistono davvero nel mondo
foreach (var s in w.AiStates)
{
foreach (var p in s.Projects.Where(p => p.Stage == AiProjectStage.Running))
{
Assert.True(w.Network.IsAlive(w.Network.Stations[p.StationA.Value]) || w.Company(s.Company).Defunct);
Assert.True(p.Trains.All(t => w.Trains[t.Value].Owner == s.Company || w.Company(s.Company).Merged));
}
}
}
[Test(Slow = true, Description = "Un'IA con capitale ×2 supera il giocatore passivo in 10 anni")]
public static void AiWithDoubleCapitalBeatsAPassivePlayer()
{
var w = TestWorlds.Small(42, "imprenditore", ("aiCapitalMultiplier", 2));
w.RunYears(10);
var player = w.Player;
var best = w.Companies.Where(c => !c.IsPlayer).MaxBy(c => c.NetWorth.Cents)!;
Assert.True(best.NetWorth > player.NetWorth, $"{best.Name}: {best.NetWorth} contro {player.NetWorth}");
Assert.True(best.NetWorth.Cents > w.Difficulty.InitialCapital * 2, $"{best.Name} ha fatto crescere il capitale: {best.NetWorth}");
}
[Test(Slow = true, Description = "Determinismo con le IA: stesso seme e stessi comandi, stesso hash dopo 5 anni (anche passando da un salvataggio)")]
public static void SameSeedWithAiGivesSameHash()
{
static World Make()
{
var w = TestWorlds.Small(77, "magnate");
w.Enqueue(new TakeLoanCommand(Money.FromLire(50_000)) { Issuer = w.Player.Id, Seq = 1 });
return w;
}
var a = Make();
var b = Make();
a.RunYears(2);
b.RunYears(2);
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(b));
var c = SaveFile.Load(TestData.Data, SaveFile.Save(b, "test"));
a.RunYears(3);
c.RunYears(3);
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(c));
Assert.True(a.AiStates.Sum(s => s.Issued) > 0, "le IA hanno agito");
}
[Test(Slow = true, Description = "Accettazione F5: in «Magnate», con il giocatore passivo, almeno un'IA raggiunge il livello 3 in 15 anni")]
public static void OnMagnateAnAiReachesTierThreeIn15Years()
{
var w = WorldFactory.Create(TestData.Data, new NewGameSettings { Seed = 7, SizeKm = 128, DifficultyId = "magnate" });
int best = 1;
for (int y = 0; y < 15 && best < 3; y++)
{
w.RunYears(1);
best = w.Companies.Where(c => !c.IsPlayer).Max(c => c.Tier);
}
var leader = w.Companies.Where(c => !c.IsPlayer).MaxBy(c => (c.Tier, c.NetWorth.Cents))!;
Console.WriteLine($" {leader.Name}: livello {leader.Tier} nel {w.Clock.Year}, patrimonio {leader.NetWorth}, rating {leader.Rating}, " +
$"città collegate {Core.Simulation.Systems.Tiers.ConnectedTowns(w, leader.Id, 1000)}");
Assert.True(best >= 3, $"livello massimo delle IA: {best}");
Assert.Equal(1, w.Player.Tier, "il giocatore passivo resta al livello 1");
}
}
@@ -66,9 +66,9 @@ public static class EconomyTests
public static void FreightAndPassengerTariffsFollowFormulas()
{
var t = TestData.Data.Balance.Tariffs;
// a prezzo base: 40 t × 150 × 1 × 20^0,9 centesimi
// a prezzo base: 40 t × tariffa base × 1 × 20^0,9 centesimi
var freight = Tariffs.Freight(40, 20, 3800, 3800, 1, 1, t, 1.0);
Assert.Equal(Money.FromCentsRounded(40 * 150 * DMath.Pow(20, 0.9)), freight);
Assert.Equal(Money.FromCentsRounded(40 * t.FreightBaseRate * DMath.Pow(20, 0.9)), freight);
// consegna con il doppio del tempo atteso: oltre la soglia del 50 % la tariffa cala
var late = Tariffs.Freight(40, 20, 3800, 3800, 2, 1, t, 1.0);
Assert.True(late < freight && late.Cents >= freight.Cents / 2);
@@ -182,7 +182,7 @@ public static class EconomyTests
{
var w = TestWorlds.Small(108);
ulong before = ViaFerrea.Core.Persistence.StateHasher.Compute(w);
w.Enqueue(new OverhaulIndustryCommand(new IndustryId(0)) { Issuer = w.Player.Id, Seq = 9 });
w.Enqueue(new BuyConcessionCommand(new RegionId(0)) { Issuer = w.Player.Id, Seq = 9 });
w.Enqueue(new TakeLoanCommand(Money.FromLire(1)) { Issuer = new CompanyId(99), Seq = 10 });
w.Pipeline.Get<CommandSystem>().Step(w.Context);
var results = w.DrainResults();
@@ -0,0 +1,206 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Data;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Systems;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Economy;
/// <summary>Manutenzione degli impianti (guida, sezione 11) e industrie possedute dal giocatore.</summary>
public static class IndustryMaintenanceTests
{
private static Industry Pick(World w, IndustryKind kind) =>
w.Industries.First(i => !i.Closed && i.Level > 0 && i.Def.Kind == kind);
private static CommandResult Do(World w, GameCommand c)
{
w.Enqueue(c with { Issuer = w.Player.Id });
w.RunTicks(1);
return w.DrainResults().Last();
}
[Test]
public static void EfficiencyMultiplierFollowsTheGuide()
{
var m = TestData.Data.Balance.IndustryMaintenance;
Assert.Approx(1.0, IndustryMath.ConditionMultiplier(100, m), 1e-9);
Assert.Approx(1.0, IndustryMath.ConditionMultiplier(70, m), 1e-9);
Assert.Approx(0.75, IndustryMath.ConditionMultiplier(45, m), 1e-9);
Assert.Approx(0.5, IndustryMath.ConditionMultiplier(20, m), 1e-9);
Assert.Approx(0.3, IndustryMath.ConditionMultiplier(10, m), 1e-9);
}
[Test(Description = "Usura con l'utilizzo; il budget Alto recupera; senza ricambi il recupero si dimezza")]
public static void WearFollowsUseAndBudgetRecovers()
{
var w = TestWorlds.NoAi(301);
var m = w.Data.Balance.IndustryMaintenance;
var ind = Pick(w, IndustryKind.Primary);
w.RunDays(5);
// senza manutenzione la condizione scende con l'utilizzo
ind.Budget = IndustryBudget.None;
ind.Condition = 80;
w.RunDays(60);
double dropped = 80 - ind.Condition;
Assert.True(dropped > 0, $"usura senza budget: {dropped:F3}");
Assert.True(dropped <= m.WearPerDay * 1.2 * ind.Def.WearIntensity * w.Difficulty.WearMultiplier * 60 + 1e-6, "usura entro il massimo della formula");
// budget alto con ricambi: il recupero (0,12 al giorno) supera l'usura; senza ricambi si dimezza.
// Due finestre di 10 giorni nello stesso mese (il consumo mensile ricalcola la mancanza di ricambi).
int dpm = w.Calendar.DaysPerMonth;
w.RunDays(dpm - (int)(w.Clock.Day % dpm) + 1);
ind.Budget = IndustryBudget.High;
ind.Condition = 60;
ind.PartsShort = false;
w.RunDays(10);
double withParts = ind.Condition - 60;
Assert.True(withParts > 0, $"recupero con budget alto: {withParts:F3}");
ind.Condition = 60;
ind.PartsShort = true;
w.RunDays(10);
double withoutParts = ind.Condition - 60;
var budget = m.For(IndustryBudget.High);
Assert.Approx(budget.RecoveryPerDay * (1 - m.NoPartsRecoveryFactor) * 10, withParts - withoutParts, 0.05,
$"senza ricambi il recupero si dimezza: {withoutParts:F3} contro {withParts:F3}");
Assert.Equal(0L, w.MoneyBalanceSum());
for (int g = 0; g < w.Data.GoodCount; g++) Assert.Equal(w.Goods.ExpectedStock(g), w.TotalStock(g), $"bene {w.Data.Goods[g].Id}");
}
[Test(Description = "Sotto 40 arrivano i fermi: niente produzione, storico, città colpita; sotto 10 l'incidente grave")]
public static void LowConditionBringsStopsAndAccidents()
{
var w = TestWorlds.NoAi(302);
var m = w.Data.Balance.IndustryMaintenance;
var ind = Pick(w, IndustryKind.Processing);
ind.Budget = IndustryBudget.None;
ind.Condition = 5;
bool stopped = false;
for (int d = 0; d < 720 && !stopped; d++)
{
ind.Condition = 5;
w.RunDays(1);
stopped = ind.IsStopped(w.Clock.Day);
}
Assert.True(stopped, "con condizione 5 un fermo arriva");
Assert.Equal(IndustryStop.Accident, ind.StopKind, "un'industria di trasformazione sotto 10 ha un incidente grave");
Assert.Equal(m.AccidentDays, ind.StopHistory[^1].Days);
w.RunDays(2);
Assert.Equal(0, ind.ProducedToday.Sum(), "nessuna produzione durante il fermo");
Assert.Approx(0.0, ind.Efficiency, 1e-9);
// un'industria primaria a 25 ha solo fermi per guasto da 5 a 20 giorni
var mine = Pick(w, IndustryKind.Primary);
mine.Budget = IndustryBudget.None;
bool broke = false;
for (int d = 0; d < 2000 && !broke; d++)
{
mine.Condition = 25;
w.RunDays(1);
broke = mine.IsStopped(w.Clock.Day);
}
Assert.True(broke, "a 25 il rischio giornaliero produce un fermo");
Assert.Equal(IndustryStop.Breakdown, mine.StopKind);
Assert.InRange(mine.StopHistory[^1].Days, m.BreakdownDays[0], m.BreakdownDays[1]);
// il rischio cresce al calare della condizione
Assert.True(m.BreakdownBase * DMath.Exp((m.BreakdownPivot - 10) / m.BreakdownScale) > m.BreakdownBase * DMath.Exp((m.BreakdownPivot - 30) / m.BreakdownScale));
}
[Test(Description = "Acquisto (livello 3, offerta ≥ valore), revisione che aspetta i macchinari e riporta la condizione a 100, ammodernamento di livello")]
public static void OwnedIndustryOverhaulAndUpgrade()
{
var w = TestWorlds.NoAi(303);
var m = w.Data.Balance.IndustryMaintenance;
var player = w.Player;
w.Money.Transfer(Account.External, Account.Of(player.Id), Money.FromLire(10_000_000), LedgerEntry.Other);
var ind = Pick(w, IndustryKind.Processing);
w.RunDays(3);
var locked = Do(w, new BuyIndustryCommand(ind.Id, Money.FromLire(9_000_000)));
Assert.Equal(CommandError.TierLocked, locked.Error, "l'acquisto si sblocca al livello 3");
player.Tier = 3;
var price = IndustryMath.Valuation(w, ind);
var low = Do(w, new BuyIndustryCommand(ind.Id, price - Money.FromLire(1)));
Assert.Equal(CommandError.InvalidArgument, low.Error, "offerta sotto il valore");
price = IndustryMath.Valuation(w, ind);
var cash = player.Cash;
var ok = Do(w, new BuyIndustryCommand(ind.Id, price + Money.FromLire(100)));
Assert.True(ok.Ok, ok.Message);
Assert.Equal(player.Id, ind.Owner);
Assert.True(player.Cash < cash, "l'acquisto si paga");
// revisione: aspetta i macchinari (e il personale), poi 30 giorni di fermo e condizione 100
ind.Condition = 30;
Assert.True(Do(w, new OverhaulIndustryCommand(ind.Id)).Ok);
Assert.Equal(IndustryWork.Overhaul, ind.PendingWork);
w.RunDays(5);
Assert.False(ind.IsStopped(w.Clock.Day), "senza macchinari la revisione non parte");
int need = IndustryMath.MachineryRequired(ind, m);
ind.Machinery += need;
w.Goods.Produced[w.Data.MachineryGood] += need;
ind.CovStaff = 1;
w.RunDays(2);
Assert.True(ind.IsStopped(w.Clock.Day), "con macchinari e personale la revisione parte");
Assert.Equal(IndustryStop.Overhaul, ind.StopKind);
w.RunDays(m.OverhaulDays + 1);
Assert.False(ind.IsStopped(w.Clock.Day));
Assert.True(ind.Condition > 99, $"condizione dopo la revisione: {ind.Condition:F1}");
// ammodernamento: costo in capitale e macchinari, 60 giorni, livello + 1
int level = ind.Level;
if (level < w.Data.Balance.Growth.MaxLevel)
{
Assert.True(Do(w, new UpgradeIndustryCommand(ind.Id)).Ok);
int machinery = IndustryMath.MachineryRequired(ind, m);
ind.Machinery += machinery;
w.Goods.Produced[w.Data.MachineryGood] += machinery;
var before = player.Cash;
w.RunDays(2);
Assert.Equal(IndustryStop.Upgrade, ind.StopKind);
Assert.True(player.Cash < before, "il proprietario paga l'ammodernamento");
w.RunDays(m.UpgradeDays + 1);
Assert.Equal(level + 1, ind.Level);
}
// «Ordina ricambi» crea domanda esplicita oltre la scorta della politica
Assert.True(Do(w, new OrderPartsCommand(DepotId.None, 30) { Industry = ind.Id }).Ok);
Assert.True(IndustryMath.ServiceNeed(w, ind, w.Data.SparePartsGood) >= 30);
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Ogni mese l'industria posseduta trattiene la riserva e versa il resto al proprietario")]
public static void OwnerReceivesTheSurplus()
{
var w = TestWorlds.NoAi(304);
var m = w.Data.Balance.IndustryMaintenance;
var ind = Pick(w, IndustryKind.Primary);
ind.Owner = w.Player.Id;
w.Money.Transfer(Account.External, Account.Of(ind.Id), Money.FromLire(500_000), LedgerEntry.Other);
var before = w.Player.Cash;
w.RunDays(w.Calendar.DaysPerMonth + 1);
Assert.Equal(m.OwnerCashReserve, ind.Cash.Cents, "l'industria trattiene la riserva");
Assert.True(w.Player.Cash > before, "il surplus va al proprietario");
Assert.True(w.Player.YearEntries[(int)LedgerEntry.Industries] > 0);
}
[Test(Description = "Proprietari privati: budget dal margine e revisione sotto 35 se la cassa basta")]
public static void NpcOwnersFollowTheirRules()
{
var w = TestWorlds.NoAi(305);
var ind = Pick(w, IndustryKind.Primary);
ind.RevenueEma = 10_000;
ind.CostEma = 5_000;
ind.Condition = 30;
w.Money.Transfer(Account.External, Account.Of(ind.Id), Money.FromLire(1_000_000), LedgerEntry.Other);
w.RunDays(w.Calendar.DaysPerMonth + 1);
Assert.Equal(IndustryWork.Overhaul, ind.PendingWork, "sotto 35 il privato programma la revisione");
// margine negativo: nessun budget
var other = w.Industries.First(i => !i.Closed && i.Level > 0 && i != ind && i.Def.Kind == IndustryKind.Primary);
other.RevenueEma = 1_000;
other.CostEma = 5_000;
w.RunDays(w.Calendar.DaysPerMonth);
Assert.True(other.Margin < 0);
Assert.Equal(IndustryBudget.None, other.Budget);
}
}
@@ -0,0 +1,285 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Economy;
using ViaFerrea.Core.Persistence;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Systems;
using ViaFerrea.Tests.Harness;
namespace ViaFerrea.Tests.Economy;
/// <summary>Borsa, quotazione, dividendi, scalate e loro esiti (guida 12.2–12.3, test di 14.5).</summary>
public static class StockMarketTests
{
private static CommandResult Do(World w, GameCommand c, Company issuer)
{
w.Enqueue(c with { Issuer = issuer.Id });
w.RunTicks(1);
return w.DrainResults().Last();
}
private static void Give(World w, Company c, long lire) =>
w.Money.Transfer(Account.External, Account.Of(c.Id), Money.FromLire(lire), LedgerEntry.Other);
/// <summary>Le IA non devono intervenire: mondo con concorrenti ma senza agenti attivi.</summary>
private static World WithIdleAi(ulong seed, string difficulty = "imprenditore", int competitors = 2)
{
var w = TestWorlds.Small(seed, difficulty, ("aiCompetitors", competitors));
w.AiPaused = true;
return w;
}
[Test(Description = "Prezzo = max(patrimonio, 8 × utile) / azioni × sentiment, con il sentiment tra 0,8 e 1,3")]
public static void PriceFollowsFundamentals()
{
var w = WithIdleAi(401);
var sm = w.Data.Balance.StockMarket;
w.RunDays(40);
foreach (var c in w.Companies)
{
Assert.Equal(sm.Shares, c.Shares.Total);
Assert.Equal(c.Shares.Total, c.Shares.Sum());
Assert.InRange(c.Sentiment, sm.SentimentMin, sm.SentimentMax);
double fundamental = Math.Max(c.NetWorth.Cents, sm.EarningsMultiple * c.AnnualProfit) / c.Shares.Outstanding;
Assert.Approx(fundamental * c.Sentiment, c.SharePrice, fundamental * 0.05 + 0.01, c.Name);
}
Assert.False(w.Player.Listed, "il giocatore parte privato (Imprenditore)");
Assert.True(w.Companies.Where(c => !c.IsPlayer).All(c => c.Listed), "le IA sono quotate");
var iron = WithIdleAi(402, "ferro_e_sangue");
Assert.True(iron.Player.Listed, "Ferro e sangue: quotata dall'inizio");
Assert.Approx(0.6, iron.Player.Shares.FounderFraction, 1e-6);
}
[Test(Description = "Quotazione al livello 4 fino al 40 %, compravendita al prezzo con lo spread, dividendi agli azionisti")]
public static void IpoTradingAndDividends()
{
var w = WithIdleAi(403);
var player = w.Player;
var ai = w.Companies.First(c => !c.IsPlayer);
Give(w, player, 5_000_000);
w.RunDays(2);
Assert.Equal(CommandError.TierLocked, Do(w, new IpoCommand(0.3), player).Error);
player.Tier = 4;
Assert.Equal(CommandError.InvalidArgument, Do(w, new IpoCommand(0.5), player).Error, "oltre il 40 %");
var cash = player.Cash;
Assert.True(Do(w, new IpoCommand(0.3), player).Ok);
Assert.True(player.Listed);
Assert.True(player.Cash > cash, "la quotazione porta capitale");
Assert.Approx(0.7, player.Shares.FounderFraction, 1e-6);
// acquisto di azioni di un'IA: lettera = prezzo × (1 + spread/2)
long n = 20_000;
double ask = Corporate.Ask(w, ai);
cash = player.Cash;
long free = ai.Shares.Public;
var buy = Do(w, new BuySharesCommand(ai.Id, n, Money.Zero), player);
Assert.True(buy.Ok, buy.Message);
Assert.Equal(n, ai.Shares.Of(player.Id));
Assert.Equal(free - n, ai.Shares.Public);
Assert.Approx(n * ask, (cash - player.Cash).Cents, n * ask * 0.02 + 2);
w.RunDays(1);
Assert.True(player.PortfolioValue.Cents > 0, "le partecipazioni contano nel patrimonio");
var sell = Do(w, new SellSharesCommand(ai.Id, n / 2, Money.Zero), player);
Assert.True(sell.Ok, sell.Message);
Assert.Equal(n / 2, ai.Shares.Of(player.Id));
// dividendo: ogni azione in circolazione riceve l'importo; le compagnie azioniste lo incassano
var aiCash = ai.Cash;
Give(w, ai, 1_000_000);
aiCash = ai.Cash;
var holderCash = player.Cash;
Assert.True(Do(w, new PayDividendCommand(new Money(10)), ai).Ok);
Assert.Equal(aiCash.Cents - 10 * ai.Shares.Outstanding, ai.Cash.Cents);
Assert.Equal(holderCash.Cents + 10 * (n / 2), player.Cash.Cents);
Assert.True(ai.DividendRing.Sum() > 0, "i dividendi entrano nel sentiment");
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Scalata ostile completata quando il flottante lo consente (14.5); fallita quando non basta")]
public static void HostileTakeoverCompletesWhenTheFloatAllows()
{
var w = WithIdleAi(404);
var player = w.Player;
var target = w.Companies.First(c => !c.IsPlayer);
Give(w, player, 50_000_000);
w.RunDays(2);
// flottante del 70 %: il fondatore privato non aderisce (premio sotto la sua soglia)
long moved = target.Shares.Founder - (long)(target.Shares.Total * 0.3);
target.Shares.Founder -= moved;
target.Shares.Public += moved;
Assert.Equal(CommandError.TierLocked, Do(w, new LaunchBidCommand(target.Id, new Money(1), 0.51), player).Error);
player.Tier = 5;
long price = (long)Math.Ceiling(target.SharePrice * 1.3);
var bid = Do(w, new LaunchBidCommand(target.Id, new Money(price), 0.51), player);
Assert.True(bid.Ok, bid.Message);
bool done = false;
for (int d = 0; d < 100 && !done; d++)
{
w.RunDays(1);
done = w.Bids.Any(b => b.State != BidState.Open);
}
Assert.Equal(BidState.Succeeded, w.Bids.Single().State);
Assert.True(target.Shares.FractionOf(player.Id) >= 0.51, $"quota {target.Shares.FractionOf(player.Id):P1}");
w.RunDays(1);
Assert.Equal(player.Id, target.ControlledBy, "chi supera il 50 % controlla");
// stessa offerta su un'IA con il 30 % di flottante: le adesioni non bastano, l'offerta scade
var other = w.Companies.Last(c => !c.IsPlayer);
long p2 = (long)Math.Ceiling(other.SharePrice * 1.3);
Assert.True(Do(w, new LaunchBidCommand(other.Id, new Money(p2), 0.51), player).Ok);
w.RunDays(w.Data.Balance.StockMarket.BidDurationDays + 2);
var second = w.Bids.Single(b => b.Target == other.Id);
Assert.Equal(BidState.Failed, second.State);
Assert.Equal(0L, other.Shares.Of(player.Id));
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Difese del bersaglio: il riacquisto toglie flottante all'offerente, il cavaliere bianco lo compra")]
public static void TargetsCanDefend()
{
var w = WithIdleAi(405, competitors: 3);
var player = w.Player;
var target = w.Companies[1];
var knight = w.Companies[2];
Give(w, player, 50_000_000);
Give(w, knight, 50_000_000);
Give(w, target, 5_000_000);
player.Tier = 5;
w.RunDays(2);
long price = (long)Math.Ceiling(target.SharePrice * 1.3);
Assert.True(Do(w, new LaunchBidCommand(target.Id, new Money(price), 0.51), player).Ok);
var bid = w.Bids.Single();
long floatBefore = Corporate.FreeFloat(w, target);
var buyback = Do(w, new RespondBidCommand(bid.Id, false) { Defense = BidDefense.Buyback }, target);
Assert.True(buyback.Ok, buyback.Message);
Assert.True(Corporate.FreeFloat(w, target) < floatBefore, "il riacquisto riduce il flottante");
var white = Do(w, new RespondBidCommand(bid.Id, false) { Defense = BidDefense.WhiteKnight, Knight = knight.Id }, target);
if (Corporate.FreeFloat(w, target) > 0 || white.Ok) Assert.True(white.Ok || white.Error == CommandError.InsufficientFunds, white.Message);
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "La controllata versa gli utili; dopo un anno di controllo si può fondere")]
public static void SubsidiaryPaysAndCanBeMerged()
{
var w = WithIdleAi(406);
var player = w.Player;
var sub = w.Companies[1];
Give(w, player, 50_000_000);
// il giocatore compra il 60 % dal fondatore privato (come dopo un'offerta riuscita)
long stake = (long)(sub.Shares.Total * 0.6);
sub.Shares.Founder -= stake;
sub.Shares.Add(player.Id, stake);
w.RunDays(2);
Assert.Equal(player.Id, sub.ControlledBy);
Assert.Equal(CommandError.NotAllowed, Do(w, new MergeCompanyCommand(sub.Id), player).Error, "serve un anno di controllo");
w.RunDays(w.Data.Balance.StockMarket.MergeAfterDays + 1);
int trainsBefore = w.Trains.Count(t => t.Owner == player.Id);
var merge = Do(w, new MergeCompanyCommand(sub.Id), player);
Assert.True(merge.Ok, merge.Message);
Assert.True(sub.Merged && sub.Defunct);
Assert.Equal(CommandError.NotAllowed, Do(w, new TakeLoanCommand(Money.FromLire(1000)), sub).Error, "la fusa non dà più comandi");
Assert.True(w.Trains.Count(t => t.Owner == player.Id) >= trainsBefore);
Assert.Equal(0L, w.MoneyBalanceSum());
}
/// <summary>Un'IA prende più del 50 % del giocatore quotato.</summary>
private static (World W, Company Ai) PlayerTakenOver(string difficulty)
{
var w = WithIdleAi(407, difficulty);
var player = w.Player;
var ai = w.Companies[1];
w.RunDays(2);
if (!player.Listed) Corporate.InitShares(w, player, true, 0.45);
long stake = (long)(player.Shares.Total * 0.55);
long fromPublic = Math.Min(stake, player.Shares.Public);
player.Shares.Public -= fromPublic;
player.Shares.Founder -= stake - fromPublic;
player.Shares.Add(ai.Id, stake);
w.RunDays(2);
return (w, ai);
}
[Test(Description = "Se l'IA compra il giocatore: amministrazione controllata (Imprenditore), fine immediata (Ferro e sangue), mai (Apprendista)")]
public static void PlayerTakeoverOutcomesByDifficulty()
{
// Imprenditore: amministrazione controllata per 3 anni, niente prestiti, riscatto possibile
var (w, ai) = PlayerTakenOver("imprenditore");
var player = w.Player;
Assert.True(player.Receivership, "amministrazione controllata");
Assert.True(w.GameOver is null, "la partita continua");
Assert.Equal(w.Clock.Day - 2 + 3L * w.Calendar.DaysPerYear, player.ReceivershipUntilDay, "3 anni per il riscatto");
Assert.Equal(CommandError.NotAllowed, Do(w, new TakeLoanCommand(Money.FromLire(1000)), player).Error);
Give(w, player, 100_000_000);
long max = (long)(player.Shares.Total * w.Data.Balance.StockMarket.MaxDailyTradeShare);
for (int i = 0; i < 40 && player.Receivership; i++)
{
var r = Do(w, new BuySharesCommand(player.Id, max, Money.Zero), player);
Assert.True(r.Ok, r.Message);
w.RunDays(1);
}
Assert.False(player.Receivership, $"riscatto riuscito: fondatore al {player.Shares.FounderFraction:P0}");
// Ferro e sangue: fine immediata, poi si osserva
var (w2, ai2) = PlayerTakenOver("ferro_e_sangue");
Assert.NotNull(w2.GameOver);
Assert.Equal(GameOverReason.Takeover, w2.GameOver!.Reason);
Assert.Equal(ai2.Id, w2.GameOver.Winner);
Assert.Equal(CommandError.NotAllowed, Do(w2, new TakeLoanCommand(Money.FromLire(1000)), w2.Player).Error, "osservatore");
w2.RunDays(10); // il mondo continua
// Apprendista: nessuna IA può superare il 50 % del giocatore
var w3 = WithIdleAi(408, "apprendista");
var p3 = w3.Player;
var ai3 = w3.Companies[1];
Corporate.InitShares(w3, p3, true, 0.3);
Give(w3, ai3, 100_000_000);
w3.RunDays(1);
long chunk = (long)(p3.Shares.Total * w3.Data.Balance.StockMarket.MaxDailyTradeShare);
CommandResult last = null!;
for (int i = 0; i < 20; i++) last = Do(w3, new BuySharesCommand(p3.Id, chunk, Money.Zero), ai3);
Assert.Equal(CommandError.NotAllowed, last.Error);
Assert.True(p3.Shares.FractionOf(ai3.Id) <= 0.5);
Assert.Equal(CommandError.NotAllowed, Do(w3, new LaunchBidCommand(p3.Id, new Money(1), 0.51), ai3).Error);
}
[Test(Description = "Un'IA fallita va all'asta: il giocatore se ne aggiudica gli attivi")]
public static void BankruptAiIsAuctioned()
{
var w = WithIdleAi(409);
var player = w.Player;
var ai = w.Companies[1];
Give(w, player, 10_000_000);
w.RunDays(2);
ai.Bankrupt = true;
w.RunDays(1);
var auction = w.Auctions.Single(a => a.Seller == ai.Id);
long perShare = auction.MinPriceCents / ai.Shares.Total + 1;
var offer = Do(w, new LaunchBidCommand(ai.Id, new Money(perShare), 1), player);
Assert.True(offer.Ok, offer.Message);
w.RunDays(w.Data.Balance.StockMarket.AuctionDays + 1);
Assert.True(ai.Merged, "attivi passati al compratore");
Assert.Equal(player.Id, ai.MergedInto);
Assert.Equal(0L, w.MoneyBalanceSum());
}
[Test(Description = "Offerte, soci, amministrazione controllata e storico sopravvivono al salvataggio")]
public static void CorporateStateSurvivesSaveAndLoad()
{
var w = WithIdleAi(410, "magnate");
var player = w.Player;
Give(w, player, 50_000_000);
player.Tier = 5;
w.RunDays(370);
var target = w.Companies[1];
long price = (long)Math.Ceiling(target.SharePrice * 1.3);
Assert.True(Do(w, new LaunchBidCommand(target.Id, new Money(price), 0.6), player).Ok);
w.RunDays(5);
var bytes = SaveFile.Save(w, "test");
var loaded = SaveFile.Load(TestData.Data, bytes);
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
w.RunDays(30);
loaded.RunDays(30);
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded));
Assert.True(player.History.Count >= 1, "storico annuale");
}
}
@@ -99,8 +99,31 @@ public static class ProtocolTests
yield return new MarketTape
{
Day = 90,
Shares = [new SharePrice { Company = 1, Price = new Money(1234), Change = -0.02f, Listed = true }],
Bids = [new BidInfo { Bid = 1, Bidder = 2, Target = 0, PricePerShare = new Money(1500), TargetShare = 0.51, ExpiresDay = 180 }],
Shares = [new SharePrice { Company = 1, Price = new Money(1234), Change = -0.02f, Listed = true, PriceCents = 1234.25, Outstanding = 990_000, FreeFloat = 300_000, FounderShare = 0.6f, ControlledBy = 2 }],
Bids = [new BidInfo { Bid = 1, Bidder = 2, Target = 0, PricePerShare = new Money(1500), TargetShare = 0.51, ExpiresDay = 180, State = 1, CommittedShare = 0.42, Defenses = 3, Knight = 3, Accepted = true }],
};
yield return new CompanyCard
{
Company = 1, TotalShares = 1_000_000, Treasury = 10_000,
Holdings = [new HoldingInfo { Holder = HoldingInfo.Founder, Shares = 600_000 }, new HoldingInfo { Holder = HoldingInfo.Market, Shares = 290_000 }, new HoldingInfo { Holder = 2, Shares = 100_000 }],
PriceHistory = [12.5, 13.25, 14],
History = [new CompanyYearInfo { Year = 1851, NetWorth = new Money(500), Cash = new Money(-20), Revenue = new Money(900), Profit = new Money(-30), Tier = 2, Trains = 4, TrackKm = 12.5f, SharePrice = new Money(13) }],
AnnualProfit = new Money(-123), DividendsYear = new Money(45), Debt = new Money(678), MarketCap = new Money(9_000_000), ControlDays = 400,
AuctionMin = new Money(10), AuctionBest = new Money(20), AuctionBestBidder = 3, AuctionEndDay = 999,
};
yield return new IndustryCard
{
Industry = 4, Margin = -0.1f, ConditionMultiplier = 0.8f, WearPerDay = 0.05f, RecoveryPerDay = 0.12f, MaintenanceCostPerDay = new Money(77),
MaintenanceSpentYear = new Money(9999), PartsTarget = 9, PartsPerMonth = 3, PartsOrdered = 20, MachineryRequired = 6, UpgradeCost = new Money(3_000_000),
Valuation = new Money(4_500_000), Cash = new Money(2_000_000), BreakdownChancePerYear = 0.3f,
Stops = [new IndustryStopInfo { Day = 300, Days = 12, Kind = 1 }, new IndustryStopInfo { Day = 500, Days = 30, Kind = 3 }],
};
yield return new Chronicle
{
GameOver = true, Reason = 2, Text = "La Predatoria prende il controllo", Winner = 2, Day = 3600, Company = "Società", FoundedYear = 1850, Prestige = 1234,
History = [new CompanyYearInfo { Year = 1850, NetWorth = new Money(1), Tier = 1 }],
Records = [new RecordInfo { Title = "Patrimonio massimo", Value = "₤ 1.000.000", Year = 1855 }],
Highlights = ["Fondata nel 1850", "Livello 3 nel 1858"],
};
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() };
@@ -137,9 +160,18 @@ public static class ProtocolTests
private static EntityLists SampleEntities() => new()
{
Companies = [new CompanyInfo { Id = 0, Name = "Società", Color = "#b3573e", IsPlayer = true, Cash = new Money(100), NetWorth = new Money(200), Rating = "A", Tier = 2, MaintenancePolicy = 2 }],
Companies = [new CompanyInfo
{
Id = 0, Name = "Società", Color = "#b3573e", IsPlayer = true, Cash = new Money(100), NetWorth = new Money(200), Rating = "A", Tier = 2, MaintenancePolicy = 2,
Personality = "predatory", Listed = true, SharePriceCents = 22.75, Sentiment = 1.1f, FounderShare = 0.55f, ControlledBy = 2, Merged = true,
Receivership = true, ReceivershipUntilDay = 777, AnnualProfit = new Money(-5),
}],
Towns = [new TownInfo { Id = 0, Name = "Valdoria", Position = P, Population = 12400, RadiusCells = 4.5, Satisfaction = 0.6f, Services = 3 }],
Industries = [new IndustryInfo { Id = 1, Type = "steel_mill", Name = "Acciaieria", Position = P, FootprintCells = 4, Level = 2, Efficiency = 0.83f, Condition = 97, Owner = -1 }],
Industries = [new IndustryInfo
{
Id = 1, Type = "steel_mill", Name = "Acciaieria", Position = P, FootprintCells = 4, Level = 2, Efficiency = 0.83f, Condition = 97, Owner = -1,
Budget = 2, SpareParts = 5, Machinery = 3, StoppedUntilDay = 1234, StopKind = 3, PendingWork = 2, PartsShort = true,
}],
Hubs = [new HubInfo { Id = 0, Kind = "port", Name = "Porto", Position = P }],
Nodes = [new NodeInfo { Id = 3, Position = P, HeightM = 120.5, Owner = 0, Station = 1, Depot = -1, Edges = [1, 4] }],
Stations = [new StationInfo { Id = 1, Owner = 0, Name = "Acciaieria", Node = 3, Position = P, Platforms = 4, WaitingUnits = 30, Industries = [1], Towns = [0] }],
@@ -178,6 +210,7 @@ public static class ProtocolTests
yield return new SetMaintenancePolicyCommand(MaintenanceScope.Line, 2, "thorough");
yield return new ScheduleServiceCommand(new TrainId(4), "overhaul");
yield return new OrderPartsCommand(new DepotId(1), 30);
yield return new OrderPartsCommand(DepotId.None, 25) { Industry = new IndustryId(4) };
yield return new TakeLoanCommand(Money.FromLire(50000));
yield return new RepayLoanCommand(new LoanId(1), new Money(999));
yield return new AcceptAgreementCommand(new AgreementId(5));
@@ -194,10 +227,12 @@ public static class ProtocolTests
yield return new PayDividendCommand(new Money(12));
yield return new LaunchBidCommand(new CompanyId(1), new Money(2000), 0.51);
yield return new RespondBidCommand(new BidId(1), false);
yield return new RespondBidCommand(new BidId(2), false) { Defense = BidDefense.WhiteKnight, Knight = new CompanyId(3) };
yield return new BuyConcessionCommand(new RegionId(2));
yield return new AcceptContractCommand(new ContractId(8));
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));
}
[Test(Description = "Ogni messaggio del protocollo ha un esemplare e sopravvive a codifica e decodifica byte per byte")]
@@ -1,6 +1,7 @@
using ViaFerrea.Core.Commands;
using ViaFerrea.Core.Common;
using ViaFerrea.Core.Rail;
using ViaFerrea.Core.Simulation;
using ViaFerrea.Core.Simulation.Systems;
using ViaFerrea.Tests.Harness;
using static ViaFerrea.Tests.Rail.RailFixture;
@@ -61,7 +62,9 @@ public static class RailNetworkTests
public static void CrossingForeignTrackBuildsAnOverpass()
{
var f = Valdoria();
var rival = f.W.Companies.First(c => !c.IsPlayer).Id;
// lo scenario non ha concorrenti: se ne aggiunge uno fermo (agenti sospesi)
f.W.AiPaused = true;
var rival = WorldFactory.CreateAiCompany(f.W, f.W.Stream("companies")).Id;
f.Ok(new BuildTrackCommand(new[] { K(11.0, 9.5), K(14.0, 9.5) }), rival);
var r = f.Do(new BuildTrackCommand(new[] { K(12.5, 8.8), K(12.5, 10.2) }));
Assert.True(r.Ok, r.Message);
+11
View File
@@ -9,6 +9,17 @@ public static class TestWorlds
public static World Small(ulong seed = 42, string difficulty = "imprenditore") =>
WorldFactory.Create(TestData.Data, new NewGameSettings { Seed = seed, SizeKm = 64, DifficultyId = difficulty });
/// <summary>Mondo piccolo con i ritocchi di difficoltà indicati (es. nessun concorrente IA).</summary>
public static World Small(ulong seed, string difficulty, params (string Key, double Value)[] overrides) =>
WorldFactory.Create(TestData.Data, new NewGameSettings
{
Seed = seed, SizeKm = 64, DifficultyId = difficulty,
DifficultyOverride = Core.Data.DifficultyOverrides.Apply(TestData.Data.DifficultyPreset(difficulty), overrides),
});
/// <summary>Mondo piccolo senza concorrenti IA.</summary>
public static World NoAi(ulong seed = 42, string difficulty = "imprenditore") => Small(seed, difficulty, ("aiCompetitors", 0));
public static GeneratedMap Map(ulong seed, int sizeKm) =>
MapGenerator.Generate(TestData.Data, new MapSpec(seed, sizeKm, TestData.Data.Balance.Time.DefaultStartYear));
}
@@ -4,6 +4,7 @@
"seed": 1872,
"startYear": 1850,
"difficulty": "imprenditore",
"aiCompetitors": 0,
"terrain": {
"widthCells": 160,
"heightCells": 120,