Aggiunge gli eventi della F6: fatti del mondo che cambiano il gioco per un periodo limitato, leggibili nel notiziario e reversibili. - Catalogo data/events.json con schema e validazione: incidente e boom di un'industria, fiera ed epidemia, boom e crollo della domanda di un bene in una zona, maltempo su un'area, sciopero di città o deposito. - Effetti come moltiplicatori letti da un'unica sorgente (World.WorldEvents) dai sistemi esistenti: capacità delle industrie, consumi delle città, presenze dei pendolari, velocità dei treni e usura del binario. A evento finito il moltiplicatore torna 1. - EventSystem tra le IA e l'hash, con flusso Rng dedicato «events», bersaglio in ordine di id, frequenza per mappa scalata dalla difficoltà (eventFrequencyMultiplier), tetto di 6, niente doppioni, notizie di inizio e fine in italiano (EventKind.World). - Salvataggio corpo versione 5 con gli eventi nell'hash; le versioni 1-4 si caricano senza eventi e con la frequenza del preset. - Protocollo: eventi in corso nel DailyDigest e nel MarketReport; client con il riquadro «Eventi in corso», avvisi nelle schede e «evento in corso» nel Mercato globale. - Lo scenario Valdoria disattiva gli eventi: con gli eventi attivi la flotta F4 senza linea dei ricambi non scendeva più sotto 40, e l'accettazione deve misurare la manutenzione, non la fortuna (ADR 0017). Accettazione F4 invariata: 35 / 20 guasti senza linea, 75 / 2 con. Decisioni in docs/adr/0017-eventi-del-mondo.md; 17 test nuovi. Refs #33. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
575 lines
32 KiB
C#
575 lines
32 KiB
C#
using System.Text.Json.Nodes;
|
|
using RailEnterprise.Core.Commands;
|
|
using RailEnterprise.Core.Common;
|
|
using RailEnterprise.Core.Data;
|
|
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.Simulation;
|
|
|
|
/// <summary>Eventi del mondo con effetti temporanei e notizie (F6, issue #33, ADR 0017).</summary>
|
|
public static class EventTests
|
|
{
|
|
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>Copia esatta del mondo (salvataggio e caricamento del corpo): stesso stato e stesso futuro.</summary>
|
|
private static World Clone(World w)
|
|
{
|
|
var s = new SaveWriter(1 << 20);
|
|
WorldSerializer.Write(w, s);
|
|
return WorldSerializer.Read(TestData.Data, new SaveReader(s.WrittenSpan.ToArray()));
|
|
}
|
|
|
|
/// <summary>Mondo generato di 64 km senza IA, con la frequenza degli eventi indicata.</summary>
|
|
private static World Generated(ulong seed, double frequency, int ai = 0) =>
|
|
TestWorlds.Small(seed, "imprenditore", ("eventFrequencyMultiplier", frequency), ("aiCompetitors", ai));
|
|
|
|
private static Town TownNamed(World w, string name) => w.Towns.Single(t => t.Name == name);
|
|
|
|
private static Industry IndustryOfType(World w, string type) => w.Industries.First(i => i.Def.Id == type);
|
|
|
|
private static List<GameEvent> WorldNews(World w) => w.Events.Recent.Where(e => e.Kind == EventKind.World).ToList();
|
|
|
|
// ------------------------------------------------------------------ catalogo
|
|
|
|
[Test(Description = "Il catalogo events.json è valido e copre industria, città, bene, maltempo e sciopero con effetti nel verso atteso")]
|
|
public static void CatalogIsValidAndCoversEveryKind()
|
|
{
|
|
var d = TestData.Data;
|
|
var events = d.Events.Events;
|
|
Assert.True(d.Events.MaxActive > 0, "maxActive positivo");
|
|
foreach (EventTarget t in Enum.GetValues<EventTarget>())
|
|
Assert.True(events.Any(e => e.Target == t), $"manca un evento con bersaglio {t}");
|
|
foreach (var e in events)
|
|
{
|
|
Assert.True(e.DurationDays[0] >= 1 && e.DurationDays[0] <= e.DurationDays[1], $"{e.Id}: durata");
|
|
Assert.True(e.ChancePerYear > 0, $"{e.Id}: probabilità");
|
|
Assert.True(e.NewsIt.Contains("{target}", StringComparison.Ordinal), $"{e.Id}: la notizia nomina il bersaglio");
|
|
Assert.True(e.Effects.All(x => DataValidator.EffectFits(e.Target, x.Kind)), $"{e.Id}: effetti compatibili");
|
|
Assert.Equal(e, d.EventType(e.Id));
|
|
}
|
|
double Primary(string id, bool max) => max ? d.EventType(id)!.Effects[0].Max : d.EventType(id)!.Effects[0].Min;
|
|
Assert.True(Primary("industry_accident", true) < 1 && Primary("industry_accident", false) >= 0, "incidente: capacità ridotta o nulla");
|
|
Assert.True(Primary("industry_boom", false) > 1, "boom: capacità aumentata");
|
|
Assert.True(Primary("town_fair", false) > 1, "fiera: consumi aumentati");
|
|
Assert.True(Primary("epidemic", true) < 1 && d.EventType("epidemic")!.Effects.Any(x => x.Kind == EventEffectKind.Attendance && x.Max < 1), "epidemia: consumi e presenze ridotti");
|
|
Assert.True(Primary("good_demand_boom", false) > 1 && Primary("good_demand_slump", true) < 1, "boom e crollo della domanda di un bene");
|
|
var storm = d.EventType("storm")!;
|
|
Assert.True(storm.Effects.Single(x => x.Kind == EventEffectKind.TrainSpeed).Max < 1 && storm.Effects.Single(x => x.Kind == EventEffectKind.TrackWear).Min > 1, "maltempo: treni lenti e usura");
|
|
Assert.True(Primary("strike_town", true) < 1 && Primary("strike_depot", true) < 1, "scioperi: presenze ridotte");
|
|
Assert.True(d.EventType("good_demand_boom")!.GoodIndices.Length > 0, "beni ammessi risolti");
|
|
Assert.True(d.Difficulty.Presets.All(p => p.EventFrequencyMultiplier > 0), "eventi attivi in ogni preset");
|
|
}
|
|
|
|
[Test(Description = "Il validatore rifiuta un effetto incompatibile con il bersaglio, un bene sconosciuto, min > max, il raggio mancante e un bersaglio fuori elenco")]
|
|
public static void CatalogValidationRejectsInconsistentEvents()
|
|
{
|
|
static IReadOnlyList<string> Errors(Action<JsonNode> mutate)
|
|
{
|
|
var files = MemoryDataSource.Snapshot(TestData.Source);
|
|
var root = JsonNode.Parse(files["events.json"])!;
|
|
mutate(root);
|
|
files["events.json"] = root.ToJsonString();
|
|
try
|
|
{
|
|
GameData.Load(new MemoryDataSource(files));
|
|
}
|
|
catch (DataValidationException ex)
|
|
{
|
|
return ex.Errors;
|
|
}
|
|
Assert.Fail("il catalogo alterato doveva essere rifiutato");
|
|
return [];
|
|
}
|
|
var semantic = Errors(root =>
|
|
{
|
|
var list = root["events"]!.AsArray();
|
|
list[0]!["effects"]![0]!["kind"] = "trainSpeed";
|
|
list[1]!["effects"]![0]!["min"] = 2.0;
|
|
list[1]!["effects"]![0]!["max"] = 1.5;
|
|
list[4]!["goods"] = new JsonArray("unobtainium");
|
|
list[6]!.AsObject().Remove("radiusKm");
|
|
});
|
|
Assert.True(semantic.Any(e => e.Contains("non si applica al bersaglio", StringComparison.Ordinal)), "effetto incompatibile");
|
|
Assert.True(semantic.Any(e => e.Contains("min > max", StringComparison.Ordinal)), "min > max");
|
|
Assert.True(semantic.Any(e => e.Contains("unobtainium", StringComparison.Ordinal)), "bene sconosciuto");
|
|
Assert.True(semantic.Any(e => e.Contains("richiede radiusKm", StringComparison.Ordinal)), "raggio mancante");
|
|
var schema = Errors(root => root["events"]![0]!["target"] = "planet");
|
|
Assert.True(schema.Any(e => e.Contains("events.json", StringComparison.Ordinal)), "bersaglio fuori elenco");
|
|
}
|
|
|
|
// ------------------------------------------------------------------ effetti
|
|
|
|
[Test(Description = "Incidente e boom: la capacità dell'industria segue il moltiplicatore e a evento scaduto torna 1")]
|
|
public static void IndustryEventsScaleCapacityAndThenStop()
|
|
{
|
|
foreach (var (type, intensity, expected) in new[] { ("industry_accident", 0.5, 0.25), ("industry_boom", 1.0, 1.5) })
|
|
{
|
|
var f = Valdoria();
|
|
f.W.RunDays(2);
|
|
var a = f.W;
|
|
var b = Clone(a);
|
|
var mine = IndustryOfType(a, "iron_mine");
|
|
var ev = EventSystem.Force(a, type, mine.Id.Value, durationDays: 5, intensity: intensity);
|
|
Assert.NotNull(ev, $"{type} sulla miniera");
|
|
Assert.Approx(expected, a.WorldEvents.IndustryCapacity(mine.Id), 1e-12, $"{type}: moltiplicatore");
|
|
a.RunDays(1);
|
|
b.RunDays(1);
|
|
var mineB = b.Industries[mine.Id.Value];
|
|
Assert.True(mineB.Efficiency > 0, "la miniera lavora");
|
|
Assert.Approx(expected * mineB.Efficiency, mine.Efficiency, 1e-12, $"{type}: efficienza scalata dalla capacità");
|
|
Assert.Approx(1.0, a.WorldEvents.IndustryCapacity(a.Industries.First(i => i.Def.Id == "coal_mine").Id), 0, "le altre industrie non cambiano");
|
|
a.RunDays(5);
|
|
Assert.Equal(0, a.WorldEvents.Active.Count, $"{type}: scaduto");
|
|
Assert.Approx(1.0, a.WorldEvents.IndustryCapacity(mine.Id), 0, $"{type}: capacità tornata normale");
|
|
Assert.Equal(2, WorldNews(a).Count(e => e.EntityIndex == mine.Id.Value && e.Entity == EntityKind.Industry), $"{type}: notizia d'inizio e di fine");
|
|
AssertInvariants(a, type);
|
|
}
|
|
}
|
|
|
|
[Test(Description = "Fiera ed epidemia: la domanda della città segue il moltiplicatore, l'epidemia riduce anche le presenze dei suoi lavoratori")]
|
|
public static void TownEventsScaleDemandAndAttendance()
|
|
{
|
|
foreach (var (type, intensity) in new[] { ("town_fair", 1.0), ("epidemic", 0.0) })
|
|
{
|
|
var f = Valdoria();
|
|
f.W.RunDays(3);
|
|
var a = f.W;
|
|
var b = Clone(a);
|
|
var town = TownNamed(a, "Valdoria");
|
|
var ev = EventSystem.Force(a, type, town.Id.Value, durationDays: 4, intensity: intensity)!;
|
|
double demand = ev.Effect(EventEffectKind.TownDemand);
|
|
double attendance = ev.Effect(EventEffectKind.Attendance);
|
|
a.RunDays(1);
|
|
b.RunDays(1);
|
|
int goods = 0;
|
|
for (int g = 0; g < a.Data.GoodCount; g++)
|
|
{
|
|
double db = b.Towns[town.Id.Value].DemandToday[g];
|
|
if (db <= 0) continue;
|
|
goods++;
|
|
Assert.Approx(db * demand, town.DemandToday[g], 1e-9 * db, $"{type}: domanda di {a.Data.Goods[g].Id}");
|
|
}
|
|
Assert.True(goods > 0, "la città consuma");
|
|
var other = TownNamed(a, "Borgo Ceresio");
|
|
Assert.SequenceEqual(b.Towns[other.Id.Value].DemandToday, other.DemandToday, "le altre città non cambiano");
|
|
|
|
// presenze: i lavoratori di Valdoria nei posti vicini (a piedi) si presentano in quota
|
|
CheckAttendance(a, b, town, attendance, type);
|
|
a.RunDays(4);
|
|
Assert.Equal(0, a.WorldEvents.Active.Count);
|
|
Assert.Approx(1.0, a.WorldEvents.TownDemand(town, 0), 0, "domanda tornata normale");
|
|
AssertInvariants(a, type);
|
|
}
|
|
}
|
|
|
|
/// <summary>Presenze dei posti di lavoro con pendolari della città: ricalcolate con il moltiplicatore e confrontate con il gemello senza evento.</summary>
|
|
private static void CheckAttendance(World a, World b, Town town, double attendance, string what)
|
|
{
|
|
var ib = a.Data.Balance.Industry;
|
|
int checkedPlaces = 0;
|
|
foreach (var ind in a.Industries)
|
|
{
|
|
if (ind.Closed || ind.Level <= 0) continue;
|
|
var contracts = a.Commutes.Where(c => c.Workplace == ind.Ref && c.Category == PaxClass.Worker).ToList();
|
|
if (!contracts.Any(c => c.Town == town.Id)) continue;
|
|
double expected = EmploymentSystem.OnSite(ind.JobsWorkers, ib.OnSiteWorkerShare);
|
|
foreach (var c in contracts)
|
|
{
|
|
double present = c.Walking ? c.Headcount : c.Headcount * Math.Min(1.0, c.Coverage);
|
|
expected += present * (c.Town == town.Id ? attendance : 1.0);
|
|
}
|
|
expected = Math.Min(expected, ind.JobsWorkers);
|
|
Assert.Approx(expected, ind.WorkersPresent, 1e-9, $"{what}: presenze a {ind.Name}");
|
|
if (attendance < 1) Assert.True(ind.WorkersPresent < b.Industries[ind.Id.Value].WorkersPresent, $"{what}: meno presenti a {ind.Name}");
|
|
checkedPlaces++;
|
|
}
|
|
Assert.True(checkedPlaces > 0, $"{what}: un posto di lavoro con pendolari della città");
|
|
}
|
|
|
|
[Test(Description = "Sciopero dei lavoratori di una città: presenze ridotte solo per chi viene da quella città, poi tutto come prima")]
|
|
public static void TownStrikeCutsAttendanceOfItsWorkers()
|
|
{
|
|
var f = Valdoria();
|
|
f.W.RunDays(3);
|
|
var a = f.W;
|
|
var b = Clone(a);
|
|
var town = TownNamed(a, "Valdoria");
|
|
var ev = EventSystem.Force(a, "strike_town", town.Id.Value, durationDays: 3, intensity: 0)!;
|
|
Assert.Approx(0.2, ev.Primary, 1e-12);
|
|
a.RunDays(1);
|
|
b.RunDays(1);
|
|
CheckAttendance(a, b, town, 0.2, "sciopero");
|
|
var sb = b.Towns[town.Id.Value];
|
|
Assert.SequenceEqual(sb.DemandToday, town.DemandToday, "lo sciopero non cambia i consumi");
|
|
a.RunDays(3);
|
|
Assert.Equal(0, a.WorldEvents.Active.Count);
|
|
Assert.Approx(1.0, a.WorldEvents.Attendance(town.Id, new WorkplaceRef(WorkplaceKind.Industry, 0)), 0);
|
|
}
|
|
|
|
[Test(Description = "Boom e crollo della domanda di un bene: moltiplicano il consumo di quel bene solo nelle città della zona")]
|
|
public static void GoodDemandEventsActOnTheZoneOnly()
|
|
{
|
|
foreach (var (type, intensity, expected) in new[] { ("good_demand_boom", 1.0, 2.0), ("good_demand_slump", 0.0, 0.3) })
|
|
{
|
|
var a = Generated(31, 0);
|
|
a.RunDays(1);
|
|
var b = Clone(a);
|
|
var def = a.Data.EventType(type)!;
|
|
var center = a.Towns.OrderByDescending(t => t.Population).First();
|
|
int good = def.GoodIndices.First(g => DemandSystem.TownDemand(a, center, g, a.Clock.Year) > 0);
|
|
var ev = EventSystem.Force(a, type, center.Id.Value, good, durationDays: 2, intensity: intensity)!;
|
|
Assert.Approx(expected, ev.Primary, 1e-12);
|
|
a.RunDays(1);
|
|
b.RunDays(1);
|
|
double r2 = def.RadiusKm!.Value * 1000 * def.RadiusKm.Value * 1000;
|
|
int inside = 0, outside = 0;
|
|
foreach (var t in a.Towns)
|
|
{
|
|
var tb = b.Towns[t.Id.Value];
|
|
bool zone = (t.Position - center.Position).LengthSquared <= r2;
|
|
for (int g = 0; g < a.Data.GoodCount; g++)
|
|
{
|
|
double f = zone && g == good ? expected : 1.0;
|
|
Assert.Approx(tb.DemandToday[g] * f, t.DemandToday[g], 1e-9 * Math.Max(1, tb.DemandToday[g]), $"{type}: {t.Name}, {a.Data.Goods[g].Id}");
|
|
}
|
|
if (zone) inside++;
|
|
else outside++;
|
|
}
|
|
Assert.True(inside >= 1 && outside >= 1, $"città dentro ({inside}) e fuori ({outside}) dalla zona");
|
|
a.RunDays(2);
|
|
Assert.Equal(0, a.WorldEvents.Active.Count);
|
|
Assert.Approx(1.0, a.WorldEvents.TownDemand(center, good), 0);
|
|
AssertInvariants(a, type);
|
|
}
|
|
}
|
|
|
|
[Test(Description = "Maltempo: gli archi dell'area hanno velocità ridotta e il traffico li consuma di più; fuori dall'area e dopo l'evento nessun effetto")]
|
|
public static void StormSlowsAndWearsTheTrackInItsArea()
|
|
{
|
|
var f = Valdoria();
|
|
f.BuildFreightNetwork();
|
|
var a = f.W;
|
|
var b = Clone(a);
|
|
var town = TownNamed(a, "Valdoria");
|
|
var ev = EventSystem.Force(a, "storm", town.Id.Value, durationDays: 3, intensity: 1.0)!;
|
|
double speed = ev.Effect(EventEffectKind.TrainSpeed), wear = ev.Effect(EventEffectKind.TrackWear);
|
|
Assert.Approx(0.8, speed, 1e-12);
|
|
Assert.Approx(4.0, wear, 1e-12);
|
|
Assert.False(ev.InZone(new Vec2(1e7, 1e7)), "lontano dall'area");
|
|
|
|
// stessa usura del traffico nei due mondi: con il maltempo l'arco perde «wear» volte di più
|
|
var edges = a.Network.Edges.Where(e => e.State == EdgeState.Active).ToList();
|
|
foreach (var e in edges)
|
|
{
|
|
e.WearToday = 2000;
|
|
b.Network.Edges[e.Id.Value].WearToday = 2000;
|
|
}
|
|
a.RunDays(1);
|
|
b.RunDays(1);
|
|
int affected = 0;
|
|
foreach (var e in edges)
|
|
{
|
|
double factor = a.WorldEvents.EdgeWear(e);
|
|
Assert.True(factor == 1.0 || Math.Abs(factor - wear) < 1e-12, "fattore dell'arco");
|
|
Assert.Approx(factor == 1.0 ? 1.0 : speed, a.WorldEvents.EdgeSpeed(e), 1e-12, "velocità dell'arco");
|
|
double dropA = 100 - e.Condition, dropB = 100 - b.Network.Edges[e.Id.Value].Condition;
|
|
Assert.True(dropB > 0, "il traffico consuma il binario");
|
|
Assert.Approx(dropB * factor, dropA, 1e-9, $"usura dell'arco {e.Id.Value}");
|
|
if (factor > 1) affected++;
|
|
}
|
|
Assert.True(affected > 0, "archi nell'area");
|
|
a.RunDays(3);
|
|
Assert.Equal(0, a.WorldEvents.Active.Count);
|
|
Assert.True(edges.All(e => a.WorldEvents.EdgeSpeed(e) == 1.0 && a.WorldEvents.EdgeWear(e) == 1.0), "nessun effetto dopo l'evento");
|
|
}
|
|
|
|
[Test(Description = "Maltempo: un treno nell'area non supera il limite ridotto ed è più lento del gemello senza evento")]
|
|
public static void StormSlowsTheTrains()
|
|
{
|
|
var f = Valdoria();
|
|
var (mine, mill, depot) = f.BuildFreightNetwork();
|
|
int train = f.Train(depot, "loco_steam_1850", 1, "wagon_hopper", 4, "Merci 1");
|
|
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)));
|
|
f.W.RunDays(2);
|
|
var a = f.W;
|
|
var b = Clone(a);
|
|
// intensità 0: velocità al 50 %, su tutta la rete (centro nel mezzo del tracciato)
|
|
var center = a.Towns.OrderBy(t => (t.Position - a.Network.Stations[mine].Position).LengthSquared).First();
|
|
var ev = EventSystem.Force(a, "storm", center.Id.Value, durationDays: 20, intensity: 0)!;
|
|
double factor = ev.Effect(EventEffectKind.TrainSpeed);
|
|
Assert.Approx(0.5, factor, 1e-12);
|
|
double maxA = 0, maxB = 0, maxLimitA = 0;
|
|
int ticks = 6 * a.Calendar.TicksPerDay;
|
|
for (int k = 0; k < ticks; k++)
|
|
{
|
|
a.RunTicks(1);
|
|
b.RunTicks(1);
|
|
if (k < a.Calendar.TicksPerDay) continue; // un giorno per frenare al nuovo limite
|
|
var ta = a.Trains[train];
|
|
var tb = b.Trains[train];
|
|
if (ta.Route.Count > 0 && ta.RouteIndex < ta.Route.Count)
|
|
{
|
|
var e = a.Network.Edges[ta.Route[ta.RouteIndex].Edge.Value];
|
|
if (a.WorldEvents.EdgeSpeed(e) < 1)
|
|
{
|
|
maxA = Math.Max(maxA, ta.Speed * 3.6);
|
|
maxLimitA = Math.Max(maxLimitA, e.SpeedLimitKmh.Max() * factor);
|
|
}
|
|
}
|
|
maxB = Math.Max(maxB, tb.Speed * 3.6);
|
|
}
|
|
Assert.True(maxA > 0, "il treno si muove nell'area");
|
|
Assert.True(maxA <= maxLimitA + 0.5, $"velocità {maxA:F1} km/h oltre il limite ridotto {maxLimitA:F1}");
|
|
Assert.True(maxB > maxA + 1, $"senza maltempo il treno va più forte ({maxB:F1} contro {maxA:F1} km/h)");
|
|
AssertInvariants(a, "maltempo");
|
|
}
|
|
|
|
[Test(Description = "Sciopero in deposito: il personale non si presenta, l'officina resta senza tecnici fino alla fine")]
|
|
public static void DepotStrikeEmptiesTheWorkshop()
|
|
{
|
|
var f = Valdoria();
|
|
var net = f.BuildMaintenanceNetwork(partsLine: false, trainsPerLine: 1);
|
|
var a = f.W;
|
|
var depot = a.Network.Depots[net.Officina];
|
|
Assert.True(f.RunUntil(() => depot.StaffPresent > 0, 120), "personale in officina");
|
|
var b = Clone(a);
|
|
var ev = EventSystem.Force(a, "strike_depot", depot.Id.Value, durationDays: 5, intensity: 0)!;
|
|
Assert.Approx(0.0, ev.Primary, 0);
|
|
a.RunDays(1);
|
|
b.RunDays(1);
|
|
Assert.Equal(0.0, depot.StaffPresent, "nessun tecnico presente durante lo sciopero");
|
|
Assert.True(b.Network.Depots[net.Officina].StaffPresent > 0, "senza sciopero il personale c'è");
|
|
Assert.True(WorldNews(a).Any(e => e.Entity == EntityKind.Depot && e.EntityIndex == depot.Id.Value), "notizia sul deposito");
|
|
a.RunDays(5);
|
|
Assert.Equal(0, a.WorldEvents.Active.Count);
|
|
Assert.True(f.RunUntil(() => depot.StaffPresent > 0, 30), "il personale torna dopo lo sciopero");
|
|
AssertInvariants(a, "sciopero in deposito");
|
|
}
|
|
|
|
// ------------------------------------------------------------------ regole
|
|
|
|
[Test(Description = "La durata è rispettata al giorno: l'evento agisce per i giorni estratti, poi la notizia di fine")]
|
|
public static void DurationIsRespected()
|
|
{
|
|
var f = Valdoria();
|
|
var w = f.W;
|
|
w.RunDays(1);
|
|
var mine = IndustryOfType(w, "iron_mine");
|
|
long start = w.Clock.Day;
|
|
var ev = EventSystem.Force(w, "industry_accident", mine.Id.Value, durationDays: 10, intensity: 0)!;
|
|
Assert.Equal(start, ev.StartDay);
|
|
Assert.Equal(start + 10, ev.EndDay);
|
|
var news = WorldNews(w).Single();
|
|
Assert.Equal(EventSeverity.Warning, news.Severity);
|
|
Assert.Equal(EntityKind.Industry, news.Entity);
|
|
Assert.True(news.Text.Contains(mine.Name, StringComparison.Ordinal) && news.Text.Contains("10 giorni", StringComparison.Ordinal) && news.Text.Contains("0%", StringComparison.Ordinal), news.Text);
|
|
int stoppedDays = 0;
|
|
for (int d = 0; d < 12; d++)
|
|
{
|
|
w.RunDays(1);
|
|
if (mine.Efficiency == 0) stoppedDays++;
|
|
Assert.Equal(d < 9, w.WorldEvents.Active.Contains(ev), $"giorno {d}: evento in corso");
|
|
}
|
|
Assert.Equal(10, stoppedDays, "dieci giorni di produzione nulla");
|
|
var end = WorldNews(w).Last();
|
|
Assert.Equal(start + 9, end.Day, "la notizia di fine arriva la sera dell'ultimo giorno");
|
|
Assert.True(end.Text.Contains("riprende", StringComparison.Ordinal), end.Text);
|
|
Assert.Equal(2, WorldNews(w).Count);
|
|
}
|
|
|
|
[Test(Description = "Niente due eventi dello stesso tipo sullo stesso bersaglio; un bersaglio non ammesso si rifiuta")]
|
|
public static void NoDuplicateOnTheSameTarget()
|
|
{
|
|
var w = Valdoria().W;
|
|
var mine = IndustryOfType(w, "iron_mine");
|
|
Assert.NotNull(EventSystem.Force(w, "industry_accident", mine.Id.Value));
|
|
Assert.True(EventSystem.Force(w, "industry_accident", mine.Id.Value) is null, "doppione rifiutato");
|
|
Assert.NotNull(EventSystem.Force(w, "industry_boom", mine.Id.Value), "un altro tipo sullo stesso bersaglio è ammesso");
|
|
Assert.NotNull(EventSystem.Force(w, "industry_accident", IndustryOfType(w, "coal_mine").Id.Value), "lo stesso tipo su un altro bersaglio è ammesso");
|
|
Assert.True(EventSystem.Force(w, "town_fair", 99) is null, "città inesistente");
|
|
Assert.True(EventSystem.Force(w, "town_fair", TownNamed(w, "Valdoria").Id.Value, durationDays: 0) is null, "durata nulla");
|
|
Assert.True(EventSystem.Force(w, "good_demand_boom", TownNamed(w, "Valdoria").Id.Value, w.Data.GoodIndex("iron_ore")) is null, "bene non di consumo");
|
|
Assert.Throws<ArgumentException>(() => EventSystem.Force(w, "meteor", 0));
|
|
Assert.Equal(3, w.WorldEvents.Active.Count);
|
|
Assert.Approx(0.5 * 1.5, w.WorldEvents.IndustryCapacity(mine.Id), 1e-12, "incidente e boom insieme: la capacità è il prodotto dei due");
|
|
}
|
|
|
|
[Test(Description = "Con la frequenza a zero (scenari di accettazione) non nasce nessun evento; la difficoltà scala la frequenza")]
|
|
public static void FrequencyZeroMeansNoEvents()
|
|
{
|
|
var w = Generated(5, 0);
|
|
w.RunDays(360);
|
|
Assert.Equal(0, w.WorldEvents.NextId, "nessun evento in un anno");
|
|
Assert.Equal(0.0, Valdoria().W.Difficulty.EventFrequencyMultiplier, "valdoria.json disattiva gli eventi");
|
|
var d = TestData.Data;
|
|
Assert.True(d.DifficultyPreset("apprendista").EventFrequencyMultiplier < d.DifficultyPreset("ferro_e_sangue").EventFrequencyMultiplier, "più eventi alle difficoltà alte");
|
|
}
|
|
|
|
// ------------------------------------------------------------------ determinismo e salvataggi
|
|
|
|
private static (World World, List<string> News) FrequentYear(ulong seed, int days, Func<World, World>? midway = null)
|
|
{
|
|
var w = Generated(seed, 10);
|
|
w.RunDays(days / 2);
|
|
if (midway is not null) w = midway(w);
|
|
w.RunDays(days - days / 2);
|
|
return (w, w.Events.Recent.Where(e => e.Kind == EventKind.World).Select(e => $"{e.Day} {e.Text}").ToList());
|
|
}
|
|
|
|
[Test(Description = "Determinismo: stesso seme, stessi eventi e stesso hash; un altro seme dà altri eventi")]
|
|
public static void SameSeedSameEvents()
|
|
{
|
|
var (a, newsA) = FrequentYear(11, 180);
|
|
var (b, newsB) = FrequentYear(11, 180);
|
|
var (_, newsC) = FrequentYear(12, 180);
|
|
Assert.True(newsA.Count >= 10, $"eventi frequenti: {newsA.Count} notizie");
|
|
Assert.SequenceEqual(newsA, newsB, "stesse notizie");
|
|
Assert.Equal(a.LastStateHash, b.LastStateHash, "stesso hash");
|
|
Assert.Equal(StateHasher.Compute(a), StateHasher.Compute(b));
|
|
Assert.False(newsA.SequenceEqual(newsC), "un altro seme cambia gli eventi");
|
|
}
|
|
|
|
[Test(Description = "Salvataggio e caricamento con eventi in corso: stessi eventi, stesso hash e stesso futuro")]
|
|
public static void SaveAndLoadWithActiveEvents()
|
|
{
|
|
int activeAtSave = 0;
|
|
World ThroughSave(World w)
|
|
{
|
|
if (w.WorldEvents.Active.Count == 0) EventSystem.Force(w, "town_fair", w.Towns.OrderByDescending(t => t.Population).First().Id.Value, durationDays: 30);
|
|
activeAtSave = w.WorldEvents.Active.Count;
|
|
var loaded = SaveFile.Load(TestData.Data, SaveFile.Save(w, "test"));
|
|
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(loaded), "stesso stato dinamico");
|
|
Assert.SequenceEqual(w.WorldEvents.Active.Select(e => (e.Id, e.Def.Id, e.Target, e.Good, e.StartDay, e.EndDay, e.Intensity)),
|
|
loaded.WorldEvents.Active.Select(e => (e.Id, e.Def.Id, e.Target, e.Good, e.StartDay, e.EndDay, e.Intensity)), "eventi ricaricati");
|
|
Assert.Equal(w.WorldEvents.NextId, loaded.WorldEvents.NextId);
|
|
Assert.Equal(w.Difficulty.EventFrequencyMultiplier, loaded.Difficulty.EventFrequencyMultiplier, "frequenza salvata");
|
|
foreach (var e in loaded.WorldEvents.Active.Where(e => e.Def.Target is EventTarget.Area or EventTarget.TownGood))
|
|
Assert.True(e.RadiusSquaredM > 0, "zona ricostruita");
|
|
return loaded;
|
|
}
|
|
var (direct, newsDirect) = FrequentYear(17, 120, w =>
|
|
{
|
|
if (w.WorldEvents.Active.Count == 0) EventSystem.Force(w, "town_fair", w.Towns.OrderByDescending(t => t.Population).First().Id.Value, durationDays: 30);
|
|
return w;
|
|
});
|
|
var (saved, newsSaved) = FrequentYear(17, 120, ThroughSave);
|
|
Assert.True(activeAtSave > 0, "eventi in corso al salvataggio");
|
|
Assert.Equal(direct.LastStateHash, saved.LastStateHash, "salvare e ricaricare non cambia il futuro");
|
|
Assert.SequenceEqual(newsDirect, newsSaved, "stesse notizie");
|
|
}
|
|
|
|
[Test(Description = "Un salvataggio della versione 4 si carica senza eventi attivi e con la frequenza del preset; la partita prosegue con gli invarianti")]
|
|
public static void VersionFourSavesLoadWithoutEvents()
|
|
{
|
|
var w = Generated(23, 1);
|
|
w.RunDays(3);
|
|
if (w.WorldEvents.NextId == 0)
|
|
{
|
|
var body = new SaveWriter(1 << 20);
|
|
WorldSerializer.Write(w, body, 4);
|
|
var same = WorldSerializer.Read(TestData.Data, new SaveReader(body.WrittenSpan.ToArray()));
|
|
Assert.Equal(StateHasher.Compute(w), StateHasher.Compute(same), "senza eventi lo stato è identico");
|
|
}
|
|
EventSystem.Force(w, "town_fair", w.Towns[0].Id.Value, durationDays: 20);
|
|
var v4 = new SaveWriter(1 << 20);
|
|
WorldSerializer.Write(w, v4, 4);
|
|
var loaded = WorldSerializer.Read(TestData.Data, new SaveReader(v4.WrittenSpan.ToArray()));
|
|
Assert.Equal(0, loaded.WorldEvents.Active.Count, "nessun evento attivo dopo la migrazione");
|
|
Assert.Equal(0, loaded.WorldEvents.NextId);
|
|
Assert.Equal(TestData.Data.DifficultyPreset("imprenditore").EventFrequencyMultiplier, loaded.Difficulty.EventFrequencyMultiplier, "frequenza dal preset");
|
|
Assert.Approx(1.0, loaded.WorldEvents.TownDemand(loaded.Towns[0], 0), 0);
|
|
loaded.RunDays(60);
|
|
AssertInvariants(loaded, "dopo la migrazione");
|
|
}
|
|
|
|
[Test(Slow = true, Description = "Un anno con eventi frequenti (e IA): invarianti di denaro e merci, mai doppioni né oltre maxActive, quasi tutti i tipi")]
|
|
public static void InvariantsHoldThroughAYearOfFrequentEvents()
|
|
{
|
|
var w = Generated(3, 10, ai: 2);
|
|
var types = new HashSet<string>(StringComparer.Ordinal);
|
|
int max = 0;
|
|
for (int d = 0; d < w.Calendar.DaysPerYear; d++)
|
|
{
|
|
w.RunDays(1);
|
|
var active = w.WorldEvents.Active;
|
|
max = Math.Max(max, active.Count);
|
|
Assert.True(active.Count <= w.Data.Events.MaxActive, $"giorno {d}: {active.Count} eventi");
|
|
var keys = active.Select(e => (e.Def.Id, e.TargetKind, e.Target)).ToList();
|
|
Assert.Equal(keys.Count, keys.Distinct().Count(), $"giorno {d}: doppioni");
|
|
foreach (var e in active)
|
|
{
|
|
types.Add(e.Def.Id);
|
|
Assert.True(e.DurationDays >= e.Def.DurationDays[0] && e.DurationDays <= e.Def.DurationDays[1], $"{e.Def.Id}: durata");
|
|
Assert.True(e.StartDay <= w.Clock.Day && w.Clock.Day < e.EndDay, $"{e.Def.Id}: in corso oggi");
|
|
Assert.InRange(e.Intensity, 0, 1, "intensità");
|
|
}
|
|
if (d % 30 == 29) AssertInvariants(w, $"giorno {d}");
|
|
}
|
|
Console.WriteLine($" {w.WorldEvents.NextId} eventi in un anno, al massimo {max} insieme, tipi: {string.Join(", ", types.Order(StringComparer.Ordinal))}");
|
|
Assert.True(types.Count >= 7, $"tipi visti: {string.Join(", ", types)}");
|
|
Assert.Equal(max, w.Data.Events.MaxActive, "con la frequenza alta si arriva al tetto");
|
|
Assert.True(w.Events.Recent.Count(e => e.Kind == EventKind.World) >= Math.Min(w.WorldEvents.NextId, 250), "notizie degli eventi");
|
|
}
|
|
|
|
// ------------------------------------------------------------------ protocollo e mercato
|
|
|
|
[Test(Description = "Protocollo: gli eventi in corso arrivano nel resoconto giornaliero e quelli sul bene nel quadro del mercato, con round-trip")]
|
|
public static void EventsReachTheClient()
|
|
{
|
|
var f = Valdoria();
|
|
var w = f.W;
|
|
var town = TownNamed(w, "Valdoria");
|
|
var def = w.Data.EventType("good_demand_boom")!;
|
|
int good = def.GoodIndices.First(g => DemandSystem.TownDemand(w, town, g, w.Clock.Year) > 0);
|
|
var boom = EventSystem.Force(w, "good_demand_boom", town.Id.Value, good, durationDays: 90, intensity: 0.5)!;
|
|
var storm = EventSystem.Force(w, "storm", town.Id.Value, durationDays: 5, intensity: 0.25)!;
|
|
|
|
var digest = RailEnterprise.Server.Projection.Digest(w, w.Player, [], false, 1, 0);
|
|
Assert.Equal(2, digest.WorldEvents.Count);
|
|
var decoded = (DailyDigest)Frame.Decode(Frame.Encode(digest));
|
|
Assert.Equal(2, decoded.WorldEvents.Count);
|
|
var s = decoded.WorldEvents.Single(e => e.Type == "storm");
|
|
Assert.Equal(storm.Id, s.Id);
|
|
Assert.Equal((byte)EntityKind.Town, s.Entity);
|
|
Assert.Equal(town.Id.Value, s.EntityIndex);
|
|
Assert.Equal(-1, s.Good);
|
|
Assert.Equal(storm.StartDay, s.StartDay);
|
|
Assert.Equal(storm.EndDay, s.EndDay);
|
|
Assert.Equal((byte)NewsSeverity.Warning, s.Severity);
|
|
Assert.Equal(2, s.Effects.Length);
|
|
Assert.Approx(storm.Effect(EventEffectKind.TrainSpeed), s.Effects[0], 1e-6);
|
|
Assert.Approx(storm.Effect(EventEffectKind.TrackWear), s.Effects[1], 1e-6);
|
|
var g = decoded.WorldEvents.Single(e => e.Type == "good_demand_boom");
|
|
Assert.Equal(good, g.Good);
|
|
Assert.Approx(1.7, g.Effects[0], 1e-6);
|
|
|
|
// il quadro del mercato mostra l'evento sul bene come «evento in corso»
|
|
var outlook = MarketOutlook.Build(w, f.Me);
|
|
Assert.Equal(boom, outlook.GoodEvents.Single());
|
|
var report = RailEnterprise.Server.Projection.Market(w, f.Me);
|
|
var back = (MarketReport)Frame.Decode(Frame.Encode(report));
|
|
Assert.Equal(boom.Id, back.GoodEvents.Single().Id);
|
|
Assert.Equal(good, back.GoodEvents.Single().Good);
|
|
Assert.Equal(report.Warehouses.Count, back.Warehouses.Count);
|
|
|
|
// senza eventi i blocchi non viaggiano e il resoconto resta compatibile
|
|
var empty = RailEnterprise.Server.Projection.Digest(Valdoria().W, w.Player, [], false, 1, 0);
|
|
Assert.Equal(0, ((DailyDigest)Frame.Decode(Frame.Encode(empty))).WorldEvents.Count);
|
|
}
|
|
}
|