Il progetto adotta il nome «Rail Enterprise» ovunque (codice RailEnterprise.*, variabili RE_*, intestazioni RESV/RECL, immagine rail-enterprise-server) per allinearsi al repository Gitea. Aggiunge Gitea Actions sul modello di Chronos: CI su PR e main, rilascio da tag con gioco Windows (client Godot + server in server/), server Windows/Linux e immagine Docker nel registro Gitea, nightly. Aggiunge i riferimenti visivi 06–09, i modelli di PR e issue, l'ADR 0014 e aggiorna README (comandi locali), STATE e CLAUDE.md. 120 test verdi. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
286 lines
14 KiB
C#
286 lines
14 KiB
C#
using RailEnterprise.Core.Commands;
|
||
using RailEnterprise.Core.Common;
|
||
using RailEnterprise.Core.Economy;
|
||
using RailEnterprise.Core.Persistence;
|
||
using RailEnterprise.Core.Simulation;
|
||
using RailEnterprise.Core.Simulation.Systems;
|
||
using RailEnterprise.Tests.Harness;
|
||
|
||
namespace RailEnterprise.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");
|
||
}
|
||
}
|