From 294278e6f8fa05a1e6f334490b4ec6fa7c10fc91 Mon Sep 17 00:00:00 2001 From: Kyler Ramsey Date: Tue, 29 Sep 2026 13:09:58 -0700 Subject: [PATCH 1/5] Global history graphs (F9, F10) show your own colony In a separate-colonies co-op game the batch control window's Global goods (F9) and population (F10) graphs showed both colonies added together. They now draw this player's colony: their own districts' saved histories added day by day on the whole map's days (wellbeing weighted by beavers, as the top bar's). ColonyHistoryView builds these display-only histories on its own lists and hands them to the graph factories in place of the game's global ones, which are only read; they are rebuilt only after a new day's sample or a change of districts, when a graph of the colony's asks. Co-Authored-By: Claude Opus 5.5 --- BeaverBuddies/Colonies/ColonyConfigurator.cs | 2 + BeaverBuddies/Colonies/ColonyHistoryView.cs | 263 +++++++++++++++++++ BeaverBuddies/Colonies/ColonyView.cs | 8 +- RuntimeChecks/ColonyRuntimeChecks.cs | 50 ++++ StabilityTests/Rc27Checks.cs | 37 +++ TWO-COLONIES.md | 12 +- 6 files changed, 362 insertions(+), 10 deletions(-) create mode 100644 BeaverBuddies/Colonies/ColonyHistoryView.cs diff --git a/BeaverBuddies/Colonies/ColonyConfigurator.cs b/BeaverBuddies/Colonies/ColonyConfigurator.cs index 4bc5dd4..d5b0d1c 100644 --- a/BeaverBuddies/Colonies/ColonyConfigurator.cs +++ b/BeaverBuddies/Colonies/ColonyConfigurator.cs @@ -72,6 +72,8 @@ public static void Configure(IContainerDefinition containerDefinition) // A hosted shared save made separate colonies at Start, from its waiting room (1.4.0-rc4). containerDefinition.Bind().AsSingleton(); containerDefinition.Bind().AsSingleton(); + // The batch control window's whole-map history graphs, drawn for this player's colony (1.4.0-rc31). + containerDefinition.Bind().AsSingleton(); containerDefinition.Bind().AsSingleton(); containerDefinition.Bind().AsSingleton(); containerDefinition.Bind().AsSingleton(); diff --git a/BeaverBuddies/Colonies/ColonyHistoryView.cs b/BeaverBuddies/Colonies/ColonyHistoryView.cs new file mode 100644 index 0000000..47bc72f --- /dev/null +++ b/BeaverBuddies/Colonies/ColonyHistoryView.cs @@ -0,0 +1,263 @@ +using HarmonyLib; +using System; +using System.Collections.Generic; +using Timberborn.Common; +using Timberborn.GameDistricts; +using Timberborn.GoodsSampling; +using Timberborn.GoodStatisticsBatchControl; +using Timberborn.GoodStatisticsUI; +using Timberborn.PopulationStatisticsBatchControl; +using Timberborn.PopulationStatisticsSampling; +using Timberborn.SingletonSystem; + +namespace BeaverBuddies.Colonies +{ + /// + /// The batch control window's history graphs with no district chosen (goods statistics, F9; population statistics, + /// F10): the game draws the whole map's history there, both colonies added together. In a separate-colonies co-op + /// game () they draw this player's colony instead: their own districts' saved + /// histories added together day by day, on the whole map's days (a district counts from the day it was first + /// sampled; the days before it, it simply isn't there). + /// + /// Display only. The game's registries (whole map and districts) are only read, never changed: the colony's + /// histories are this computer's own lists, handed to the graphs in place of the whole map's, never saved, and rebuilt + /// only when the graphs ask for them after the game has taken a new day's sample (or this player's districts change). + /// Nothing simulated reads them. + /// + public class ColonyHistoryView : RegisteredSingleton, ILoadableSingleton + { + private readonly GlobalPopulationSamplesRegistry _globalPopulationSamplesRegistry; + private readonly GlobalGoodSamplingRegistry _globalGoodSamplingRegistry; + private readonly ColonyViewService _colonyViewService; + + public ColonyHistoryView(GlobalPopulationSamplesRegistry globalPopulationSamplesRegistry, + GlobalGoodSamplingRegistry globalGoodSamplingRegistry, ColonyViewService colonyViewService) + { + _globalPopulationSamplesRegistry = globalPopulationSamplesRegistry; + _globalGoodSamplingRegistry = globalGoodSamplingRegistry; + _colonyViewService = colonyViewService; + } + + public void Load() { } + + public static ColonyHistoryView Instance => SingletonManager.GetSingleton(); + + /// What a history was last built from: rebuilt only when one of these changes. + private class Built + { + private int samples = -1; + private bool active; + private readonly List districts = new List(); + + public bool Changed(int samples, bool active, List own) + { + bool same = samples == this.samples && active == this.active && (!active || Same(own)); + if (same) return false; + this.samples = samples; + this.active = active; + districts.Clear(); + if (active) districts.AddRange(own); + return true; + } + + private bool Same(List own) + { + if (own.Count != districts.Count) return false; + for (int i = 0; i < own.Count; i++) + if (own[i] != districts[i]) return false; + return true; + } + } + + // ---- population (F10) ---- + + private readonly List populationSamples = new List(); + private PopulationSampleHistory populationHistory; + private readonly Built populationBuilt = new Built(); + private readonly List ownPopulation = new List(); + + /// The whole map's history is swapped for the colony's; any other (a district's) is left as it is. + public void SwapPopulation(ref PopulationSampleHistory history) + { + PopulationSampleHistory global = _globalPopulationSamplesRegistry.PopulationSampleHistory; + if (global == null || !ReferenceEquals(history, global)) return; + if (populationHistory == null) populationHistory = PopulationSampleHistory.CreateFromSave(populationSamples); + RefreshPopulation(); + history = populationHistory; + } + + /// Before a graph reads its history: the colony's is brought up to date (other histories are the game's). + public void BeforePopulationGraphReads(PopulationSampleHistory history) + { + if (populationHistory != null && ReferenceEquals(history, populationHistory)) RefreshPopulation(); + } + + private void RefreshPopulation() + { + ReadOnlyList days = _globalPopulationSamplesRegistry.PopulationSampleHistory.PopulationSamples; + bool active = ColonyViewService.Active; + List own = active ? _colonyViewService.OwnDistricts() : null; + if (!populationBuilt.Changed(days.Count, active, own)) return; + populationSamples.Clear(); + if (!active) + { + // No longer showing one colony (the session ended with the window open): the whole map's, as the game. + for (int i = 0; i < days.Count; i++) populationSamples.Add(days[i]); + return; + } + ownPopulation.Clear(); + foreach (DistrictCenter districtCenter in own) + { + PopulationSampleHistory history = districtCenter.GetComponent()?.PopulationSampleHistory; + if (history != null) ownPopulation.Add(history); + } + for (int i = 0; i < days.Count; i++) + { + // A district is sampled with the whole map on every day it stands, so its latest sample is the map's + // latest day: its days line up from the end. + int back = days.Count - 1 - i; + PopulationSample sum = new PopulationSample(days[i].Day, days[i].Cycle, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + long wellbeing = 0; + int beavers = 0; + foreach (PopulationSampleHistory history in ownPopulation) + { + ReadOnlyList samples = history.PopulationSamples; + if (back >= samples.Count) continue; + PopulationSample sample = samples[samples.Count - 1 - back]; + sum += sample; + // Each district's average weighted by its beavers, as the top bar's (ColonyViewService.ColonyWellbeing). + int count = sample.Adults + sample.Children; + wellbeing += (long)sample.Wellbeing * count; + beavers += count; + } + sum.SetWellbeing(beavers == 0 ? 0 : (int)Math.Round((double)wellbeing / beavers)); + populationSamples.Add(sum); + } + } + + // ---- goods (F9) ---- + + private GoodSamplingRegistry goodsRegistry; + private readonly Dictionary> goodsSamples = new Dictionary>(); + private readonly HashSet goodsHistories = new HashSet(); + private readonly Built goodsBuilt = new Built(); + private readonly List ownGoods = new List(); + + /// The whole map's goods registry is swapped for the colony's; any other (a district's) is left as it is. + public void SwapGoods(ref GoodSamplingRegistry registry) + { + GoodSamplingRegistry global = _globalGoodSamplingRegistry.GoodSamplingRegistry; + if (global == null || !ReferenceEquals(registry, global)) return; + if (goodsRegistry == null) + { + // One history per good the whole map has, each on a list of this view's own. + var histories = new List(); + foreach (GoodSampleHistory all in global.GoodSampleHistories) + { + var samples = new List(); + goodsSamples[all.GoodId] = samples; + GoodSampleHistory history = GoodSampleHistory.CreateFromSave(all.GoodId, samples); + goodsHistories.Add(history); + histories.Add(history); + } + goodsRegistry = GoodSamplingRegistry.CreateFromSave(histories, new List()); + } + RefreshGoods(); + registry = goodsRegistry; + } + + /// Before a chart reads its history: the colony's are brought up to date (other histories are the game's). + public void BeforeGoodChartReads(GoodSampleHistory history) + { + if (goodsRegistry != null && history != null && goodsHistories.Contains(history)) RefreshGoods(); + } + + private void RefreshGoods() + { + ReadOnlyList all = _globalGoodSamplingRegistry.GoodSamplingRegistry.GoodSampleHistories; + // Every good gains a sample each day: the total changes with each new day. + int samples = 0; + foreach (GoodSampleHistory history in all) samples += history.GoodSamples.Count; + bool active = ColonyViewService.Active; + List own = active ? _colonyViewService.OwnDistricts() : null; + if (!goodsBuilt.Changed(samples, active, own)) return; + ownGoods.Clear(); + if (active) + { + foreach (DistrictCenter districtCenter in own) + { + GoodSamplingRegistry registry = districtCenter.GetComponent()?.GoodSamplingRegistry; + if (registry != null) ownGoods.Add(registry); + } + } + foreach (GoodSampleHistory global in all) + { + if (!goodsSamples.TryGetValue(global.GoodId, out List summed)) continue; + summed.Clear(); + ReadOnlyList days = global.GoodSamples; + if (!active) + { + for (int i = 0; i < days.Count; i++) summed.Add(days[i]); + continue; + } + for (int i = 0; i < days.Count; i++) + { + // Lined up from the latest day, as the population's (and the top bar's goods chart). + int back = days.Count - 1 - i; + GoodSample sum = new GoodSample(days[i].Cycle, days[i].Day, 0, 0, 0, 0); + foreach (GoodSamplingRegistry registry in ownGoods) + { + if (!registry._goodSampleHistoryMap.TryGetValue(global.GoodId, out GoodSampleHistory history)) continue; + ReadOnlyList district = history.GoodSamples; + if (back < district.Count) sum += district[district.Count - 1 - back]; + } + summed.Add(sum); + } + } + } + } + + // The population statistics tab (F10) builds its graphs for the whole map from the game's saved global history. + // Hand them the colony's instead; a district's graphs are untouched. + [HarmonyPatch(typeof(PopulationStatisticsGraphFactory), nameof(PopulationStatisticsGraphFactory.Create), new[] { typeof(PopulationSampleHistory) })] + static class ColonyHistoryPopulationGraphsPatcher + { + static void Prefix(ref PopulationSampleHistory populationSampleHistory) + { + if (!ColonyViewService.Active) return; + ColonyHistoryView.Instance?.SwapPopulation(ref populationSampleHistory); + } + } + + // A graph redraws after each day's sample: the colony's history catches up first. + [HarmonyPatch(typeof(PopulationStatisticsGraph), nameof(PopulationStatisticsGraph.UpdateItem))] + static class ColonyHistoryPopulationRefreshPatcher + { + static void Prefix(PopulationStatisticsGraph __instance) + { + ColonyHistoryView.Instance?.BeforePopulationGraphReads(__instance._populationSampleHistory); + } + } + + // The goods statistics tab (F9) builds its charts for the whole map from the game's saved global registry. Hand them + // the colony's instead; a district's charts are untouched. + [HarmonyPatch(typeof(GoodStatisticsGroupFactory), nameof(GoodStatisticsGroupFactory.Create))] + static class ColonyHistoryGoodsGroupsPatcher + { + static void Prefix(ref GoodSamplingRegistry goodSamplingRegistry) + { + if (!ColonyViewService.Active) return; + ColonyHistoryView.Instance?.SwapGoods(ref goodSamplingRegistry); + } + } + + // A chart redraws after each day's sample: the colony's histories catch up first (only a chart of theirs asks). + [HarmonyPatch(typeof(GoodSampleHistoryElement), nameof(GoodSampleHistoryElement.Update))] + static class ColonyHistoryGoodsRefreshPatcher + { + static void Prefix(GoodSampleHistoryElement __instance) + { + ColonyHistoryView.Instance?.BeforeGoodChartReads(__instance._goodSampleHistory); + } + } +} diff --git a/BeaverBuddies/Colonies/ColonyView.cs b/BeaverBuddies/Colonies/ColonyView.cs index 403c101..46e5cbf 100644 --- a/BeaverBuddies/Colonies/ColonyView.cs +++ b/BeaverBuddies/Colonies/ColonyView.cs @@ -31,8 +31,8 @@ namespace BeaverBuddies.Colonies /// /// What each player sees: their own colony, never both added together. Timberborn's interface shows the whole /// settlement whenever no district is selected (the top bar's goods and their stock history, population, wellbeing, - /// the wellbeing window, the batch control window's lists and district choices, the alert panel, the notification - /// journal); in a separate-colonies session "the whole + /// the wellbeing window, the batch control window's lists, history graphs (ColonyHistoryView) and district choices, + /// the alert panel, the notification journal); in a separate-colonies session "the whole /// settlement" becomes "your colony". Display only: everything here reads the game and changes nothing that is /// simulated, so each computer may show something different without any risk to the shared game. /// @@ -447,8 +447,8 @@ static bool Prefix(BatchControlRowGroup __instance, DistrictCenter selectedDistr } } - // The window opens on the district the interface shows; with none, it would open on the whole settlement, whose - // graphs (goods, population) add both colonies together. Open on this player's biggest district instead. + // The window opens on the district the interface shows; with none, it would open on the whole settlement (whose + // lists and graphs show this player's colony, ColonyHistoryView). Open on this player's biggest district instead. [HarmonyPatch(typeof(BatchControlBoxDistrictController), nameof(BatchControlBoxDistrictController.Show))] static class ColonyViewBatchControlShowPatcher { diff --git a/RuntimeChecks/ColonyRuntimeChecks.cs b/RuntimeChecks/ColonyRuntimeChecks.cs index 8e24a4d..b3e841c 100644 --- a/RuntimeChecks/ColonyRuntimeChecks.cs +++ b/RuntimeChecks/ColonyRuntimeChecks.cs @@ -335,6 +335,21 @@ public static void Run(Assembly mod, Action test) ("Timberborn.StockpilesUI.GoodStockpilesTooltipFactory", "Timberborn.StockpilesUI", "GetGoodSamplingRegistry"), ("Timberborn.GoodsSampling.GoodSamplingRegistry", "Timberborn.GoodsSampling", "CreateFromSave"), ("Timberborn.GoodsSampling.GoodSampleHistory", "Timberborn.GoodsSampling", "CreateFromSave"), + // The batch control window's whole-map history graphs, drawn for this player's colony (ColonyHistoryView): + // the graphs are handed the colony's history instead of the saved global one, which is only read. + ("Timberborn.PopulationStatisticsBatchControl.PopulationStatisticsGraphFactory", "Timberborn.PopulationStatisticsBatchControl", "Create"), + ("Timberborn.PopulationStatisticsBatchControl.PopulationStatisticsGraph", "Timberborn.PopulationStatisticsBatchControl", "UpdateItem"), + ("Timberborn.PopulationStatisticsSampling.GlobalPopulationSamplesRegistry", "Timberborn.PopulationStatisticsSampling", "get_PopulationSampleHistory"), + ("Timberborn.PopulationStatisticsSampling.DistrictPopulationSamplesRegistry", "Timberborn.PopulationStatisticsSampling", "get_PopulationSampleHistory"), + ("Timberborn.PopulationStatisticsSampling.PopulationSampleHistory", "Timberborn.PopulationStatisticsSampling", "CreateFromSave"), + ("Timberborn.PopulationStatisticsSampling.PopulationSampleHistory", "Timberborn.PopulationStatisticsSampling", "get_PopulationSamples"), + ("Timberborn.PopulationStatisticsSampling.PopulationSample", "Timberborn.PopulationStatisticsSampling", "SetWellbeing"), + ("Timberborn.PopulationStatisticsSampling.PopulationSample", "Timberborn.PopulationStatisticsSampling", "op_Addition"), + ("Timberborn.GoodStatisticsBatchControl.GoodStatisticsGroupFactory", "Timberborn.GoodStatisticsBatchControl", "Create"), + ("Timberborn.GoodStatisticsUI.GoodSampleHistoryElement", "Timberborn.GoodStatisticsUI", "Update"), + ("Timberborn.GoodsSampling.GlobalGoodSamplingRegistry", "Timberborn.GoodsSampling", "get_GoodSamplingRegistry"), + ("Timberborn.GoodsSampling.DistrictGoodSamplingRegistry", "Timberborn.GoodsSampling", "get_GoodSamplingRegistry"), + ("Timberborn.GoodsSampling.GoodSample", "Timberborn.GoodsSampling", "op_Addition"), ("Timberborn.BatchControl.DistrictDropdownProvider", "Timberborn.BatchControl", "UpdateDistrictsList"), ("Timberborn.GameDistrictsMigrationBatchControl.ManualMigrationDistrictDropdownProvider", "Timberborn.GameDistrictsMigrationBatchControl", "UpdateDistrictsList"), // Cutting marks: the trees in the area, a new tree's highlight, the redraw, and the marking preview left alone. @@ -494,6 +509,10 @@ public static void Run(Assembly mod, Action test) ("Timberborn.DistributionSystem.DistrictDistributableGoodProvider", "Timberborn.DistributionSystem", "_importCache"), ("Timberborn.DistributionSystem.DistrictDistributableGoodProvider", "Timberborn.DistributionSystem", "_exportCache"), ("Timberborn.Population.PopulationService", "Timberborn.Population", "_populationDataCollector"), + // The history graphs (ColonyHistoryView): which history a graph or chart draws, and a district's goods. + ("Timberborn.PopulationStatisticsBatchControl.PopulationStatisticsGraph", "Timberborn.PopulationStatisticsBatchControl", "_populationSampleHistory"), + ("Timberborn.GoodStatisticsUI.GoodSampleHistoryElement", "Timberborn.GoodStatisticsUI", "_goodSampleHistory"), + ("Timberborn.GoodsSampling.GoodSamplingRegistry", "Timberborn.GoodsSampling", "_goodSampleHistoryMap"), ("Timberborn.ConstructionSitesUI.ConstructionSiteDebugFragment", "Timberborn.ConstructionSitesUI", "_constructionSite"), // The journal is listed again, through the colony filter, once this player is seated (ColonyJournal). ("Timberborn.NotificationSystemUI.NotificationPanel", "Timberborn.NotificationSystemUI", "_notifications"), @@ -509,6 +528,37 @@ public static void Run(Assembly mod, Action test) }); } + // ColonyHistoryView swaps the history argument by its name, and recognises the whole map's by the object the + // game's global row reads: both must still be so, or the patch would not apply or would never swap. + test("Colony: the history graphs are still built from the global registries, through the arguments the view swaps", () => + { + foreach (var (typeName, assemblyName, method, parameter, parameterType) in new[] + { + ("Timberborn.PopulationStatisticsBatchControl.PopulationStatisticsGraphFactory", "Timberborn.PopulationStatisticsBatchControl", "Create", + "populationSampleHistory", "Timberborn.PopulationStatisticsSampling.PopulationSampleHistory"), + ("Timberborn.GoodStatisticsBatchControl.GoodStatisticsGroupFactory", "Timberborn.GoodStatisticsBatchControl", "Create", + "goodSamplingRegistry", "Timberborn.GoodsSampling.GoodSamplingRegistry"), + }) + { + Type type = Assembly.Load(assemblyName).GetType(typeName, true)!; + if (!type.GetMethods(all).Any(m => m.Name == method && m.GetParameters().Any(p => p.Name == parameter && p.ParameterType.FullName == parameterType))) + throw new Exception($"{type.Name}.{method} no longer takes {parameter}"); + } + foreach (var (typeName, assemblyName, registry, getter) in new[] + { + ("Timberborn.PopulationStatisticsBatchControl.PopulationStatisticsRowItemFactory", "Timberborn.PopulationStatisticsBatchControl", + "Timberborn.PopulationStatisticsSampling.GlobalPopulationSamplesRegistry", "get_PopulationSampleHistory"), + ("Timberborn.GoodStatisticsBatchControl.GoodStatisticsRowItemFactory", "Timberborn.GoodStatisticsBatchControl", + "Timberborn.GoodsSampling.GlobalGoodSamplingRegistry", "get_GoodSamplingRegistry"), + }) + { + Type type = Assembly.Load(assemblyName).GetType(typeName, true)!; + MethodInfo createGlobal = type.GetMethod("CreateGlobal", all) ?? throw new Exception(type.Name + ".CreateGlobal is gone"); + if (!IlScan.Names(IlScan.Members(createGlobal), registry, getter)) + throw new Exception($"{type.Name}.CreateGlobal no longer draws {registry.Split('.').Last()}'s history"); + } + }); + test("Colony: the game still marks crossing halves and backs them onto each other", () => { var distribution = Assembly.Load("Timberborn.DistributionSystem"); diff --git a/StabilityTests/Rc27Checks.cs b/StabilityTests/Rc27Checks.cs index 3d5dad6..869bc9c 100644 --- a/StabilityTests/Rc27Checks.cs +++ b/StabilityTests/Rc27Checks.cs @@ -208,5 +208,42 @@ static string Source(params string[] parts) Check(source.Contains("int[] before = (int[])records.Clone();") && source.Contains("&& WellbeingRecords.Announces(before[slot])) Announce(records[slot]);"), "the first record is announced"); }); + yield return ("rc31: the Global history graphs (F9, F10) show your colony, built for the display and never saved", () => + { + string history = Source("BeaverBuddies", "Colonies", "ColonyHistoryView.cs"); + // The graphs are handed the colony's history in place of the whole map's, only while one colony is shown. + Check(history.Contains("[HarmonyPatch(typeof(PopulationStatisticsGraphFactory), nameof(PopulationStatisticsGraphFactory.Create), new[] { typeof(PopulationSampleHistory) })]") + && history.Contains("ColonyHistoryView.Instance?.SwapPopulation(ref populationSampleHistory);"), "the population graphs are the whole map's"); + Check(history.Contains("[HarmonyPatch(typeof(GoodStatisticsGroupFactory), nameof(GoodStatisticsGroupFactory.Create))]") + && history.Contains("ColonyHistoryView.Instance?.SwapGoods(ref goodSamplingRegistry);"), "the goods charts are the whole map's"); + Check(System.Text.RegularExpressions.Regex.Matches(history, @"if \(!ColonyViewService\.Active\) return;\n ColonyHistoryView\.Instance\?\.Swap").Count == 2, + "the graphs are swapped alone or in a shared game"); + // Only the whole map's history is swapped: a district's graphs stay the game's. + Check(history.Contains("if (global == null || !ReferenceEquals(history, global)) return;") + && history.Contains("if (global == null || !ReferenceEquals(registry, global)) return;"), "a district's graphs could be swapped"); + // The game's registries are only read: nothing is added to them, and the colony's lists are this view's own. + Check(!history.Contains(".AddSample(") && !history.Contains(".Add(sample") && !history.Contains(".PopulationSampleHistory =") + && !history.Contains(".GoodSamplingRegistry ="), "a game registry could be written"); + Check(history.Contains("PopulationSampleHistory.CreateFromSave(populationSamples)") && history.Contains("GoodSampleHistory.CreateFromSave(all.GoodId, samples)"), + "the colony's history is not a list of its own"); + // Summed day by day from the latest; wellbeing weighted by beavers, as the top bar's. + Check(history.Contains("if (back >= samples.Count) continue;") && history.Contains("if (back < district.Count) sum += district[district.Count - 1 - back];") + && history.Contains("wellbeing += (long)sample.Wellbeing * count;"), "the colony's days are not lined up, or wellbeing is not weighted by beavers"); + // Rebuilt only for a new day or a change of districts, and only when a graph of the colony's asks. + Check(history.Contains("if (!populationBuilt.Changed(days.Count, active, own)) return;") && history.Contains("if (!goodsBuilt.Changed(samples, active, own)) return;") + && history.Contains("ReferenceEquals(history, populationHistory)) RefreshPopulation();") && history.Contains("goodsHistories.Contains(history)) RefreshGoods();"), + "the colony's histories are rebuilt on every redraw"); + Check(Source("BeaverBuddies", "Colonies", "ColonyConfigurator.cs").Contains("containerDefinition.Bind().AsSingleton();"), "the history view is not bound"); + string checks = Source("RuntimeChecks", "ColonyRuntimeChecks.cs"); + foreach (string method in new[] { "PopulationStatisticsGraphFactory\", \"Timberborn.PopulationStatisticsBatchControl\", \"Create\"),", + "PopulationStatisticsGraph\", \"Timberborn.PopulationStatisticsBatchControl\", \"UpdateItem\"),", + "GoodStatisticsGroupFactory\", \"Timberborn.GoodStatisticsBatchControl\", \"Create\"),", + "GoodSampleHistoryElement\", \"Timberborn.GoodStatisticsUI\", \"Update\"),", "\"_populationSampleHistory\"),", "\"_goodSampleHistory\"),", + "\"populationSampleHistory\", \"Timberborn.PopulationStatisticsSampling.PopulationSampleHistory\"),", + "\"goodSamplingRegistry\", \"Timberborn.GoodsSampling.GoodSamplingRegistry\")," }) + Check(checks.Contains(method), "RuntimeChecks does not list " + method); + string rules = System.Text.RegularExpressions.Regex.Replace(Source("TWO-COLONIES.md"), @"\s+", " "); + Check(!rules.Contains("*Global* history graphs") && rules.Contains("Faction unlocks still cover the whole map."), "TWO-COLONIES.md says the Global graphs are the whole map's"); + }); } } diff --git a/TWO-COLONIES.md b/TWO-COLONIES.md index 5414625..d5c18cc 100644 --- a/TWO-COLONIES.md +++ b/TWO-COLONIES.md @@ -285,12 +285,12 @@ A tile marked by one colony can't be marked or unmarked by another. Unmarking an ## What you see In co-op, your interface shows **your own colony**: the top bar (goods, population, housing, workplaces, wellbeing, -science, and a good's 10-day stock chart) and the wellbeing window it opens, the batch control lists and district -lists (F1 to F10), alerts, the status icons over beavers and buildings, the notification journal and the trees marked -for cutting. Each colony has its own wellbeing high score, and only its player hears of a new one. Achievements count -your own colony's buildings and beavers, except those whose progress is kept in the save, which count every colony. -You can open another colony's buildings; your figures stay yours. The *Global* history graphs (F9, F10) and faction -unlocks still cover the whole map. +science, and a good's 10-day stock chart) and the wellbeing window it opens, the batch control lists, history graphs +and district lists (F1 to F10), alerts, the status icons over beavers and buildings, the notification journal and the +trees marked for cutting. Each colony has its own wellbeing high score, and only its player hears of a new one. +Achievements count your own colony's buildings and beavers, except those whose progress is kept in the save, which +count every colony. You can open another colony's buildings; your figures stay yours. Faction unlocks still cover the +whole map. ## The road rule From 73d748ee0db238be2e5c9016ad58c43863d26057 Mon Sep 17 00:00:00 2001 From: Kyler Ramsey Date: Tue, 29 Sep 2026 13:14:00 -0700 Subject: [PATCH 2/5] Trades are typed whole, never refused, and carried exactly in rounds the game picks Kyler (rc30 play): "No trade offer should be refused, the game should just take of those details without concerning the player." A player types the whole trade (101 Logs for 2 Gears). The game carries it in one round per 100 of the larger side (ExchangeTerms.RoundsFor), each side spread as evenly as it goes, larger rounds first (ExchangeTerms.ShareOf: 51 then 50 Logs, 1 and 1 Gear), so exactly what was typed crosses. CrossingExchange saves the side's Whole; Total is the current round's share, set again as each round crosses. Offers, answers and the colonies window say only the whole trade; the ledger shows each round as it crossed. The Rounds box is display-only (greyed, showing the count, or infinity for a repeating deal, whose amounts stay each round's, up to 100). The site's Trading Post demo plays by the same rules. Both players need this build: an offer's amounts now mean the whole trade. Co-Authored-By: Claude Opus 5.5 --- BeaverBuddies/Colonies/ExchangeTerms.cs | 35 +- BeaverBuddies/Colonies/TradeOfferForm.cs | 300 +++++++----------- BeaverBuddies/Colonies/TradeOverviewPanel.cs | 5 +- BeaverBuddies/Colonies/TradingPostExchange.cs | 83 +++-- BeaverBuddies/Colonies/TradingPostFragment.cs | 123 +++---- .../Localizations/enUS_BeaverBuddie.csv | 18 +- CLAUDE.md | 4 +- README.md | 8 +- RuntimeChecks/RcTradingRuntimeChecks.cs | 6 +- StabilityTests/ColonyChecks.cs | 182 +++++------ StabilityTests/FactionChecks.cs | 6 +- StabilityTests/FeatureChecks.cs | 4 +- StabilityTests/Rc15Checks.cs | 2 +- StabilityTests/Rc22Checks.cs | 14 +- StabilityTests/RcTradingChecks.cs | 32 +- TWO-COLONIES.md | 21 +- docs/assets/trade-demo.js | 119 +++---- docs/index.html | 4 +- 18 files changed, 439 insertions(+), 527 deletions(-) diff --git a/BeaverBuddies/Colonies/ExchangeTerms.cs b/BeaverBuddies/Colonies/ExchangeTerms.cs index 423f685..870baa9 100644 --- a/BeaverBuddies/Colonies/ExchangeTerms.cs +++ b/BeaverBuddies/Colonies/ExchangeTerms.cs @@ -143,6 +143,38 @@ public static class ExchangeTerms public const int MaxRounds = 99; /// The most a side can say it keeps back (see ). public const int MaxKeep = 9999; + /// The most one side gives over a whole exchange: a full round every round. + public const int MaxWhole = MaxAmount * MaxRounds; + + /// + /// The rounds a whole exchange takes: one for each of its larger side (300 for 300 is 3, + /// 301 for 300 is 4). The players never choose them; they follow from what a Trading Post carries. + /// + public static int RoundsFor(int wholeGive, int wholeGet) => + Math.Max(1, (Math.Max(Math.Max(0, wholeGive), Math.Max(0, wholeGet)) + MaxAmount - 1) / MaxAmount); + + /// + /// What a side gives in round (from 0) of : the whole spread as + /// evenly as it goes, the larger rounds first (101 over 2 rounds is 51, then 50; 1 over 5 is 1, then 0). The + /// rounds add up to exactly the whole, and none carries more than when + /// is . + /// + public static int ShareOf(int whole, int rounds, int index) + { + if (whole <= 0 || rounds <= 0 || index < 0 || index >= rounds) return 0; + return whole / rounds + (index < whole % rounds ? 1 : 0); + } + + /// + /// Whole exchange terms: amounts from 0 to (a repeating exchange's are each round's, up to + /// ), not both 0, each with its item, two different items. + /// + public static bool AreValidTerms(string giveGood, int giveAmount, string getGood, int getAmount, bool repeat) + { + int most = repeat ? MaxAmount : MaxWhole; + if (giveAmount > most || getAmount > most) return false; + return AreValid(giveGood, Math.Min(giveAmount, MaxAmount), getGood, Math.Min(getAmount, MaxAmount)); + } /// Science points as an exchange item: moved from pool to pool, with separate science. public const string Science = "BeaverBuddies.Science"; @@ -207,7 +239,8 @@ public static bool TryDecodeTerms(string text, out string giveGood, out int give giveGood = GoodOf(parts[0], giveAmount); getGood = GoodOf(parts[2], getAmount); repeat = parts[5] == "1"; - return AreValid(giveGood, giveAmount, getGood, getAmount) && (repeat || AreValidRounds(rounds)) && IsValidKeep(keep); + return AreValidTerms(giveGood, giveAmount, getGood, getAmount, repeat) + && (repeat || rounds == RoundsFor(giveAmount, getAmount)) && IsValidKeep(keep); } /// The good a side gives, or null for a side that gives nothing. diff --git a/BeaverBuddies/Colonies/TradeOfferForm.cs b/BeaverBuddies/Colonies/TradeOfferForm.cs index 339d968..867bf69 100644 --- a/BeaverBuddies/Colonies/TradeOfferForm.cs +++ b/BeaverBuddies/Colonies/TradeOfferForm.cs @@ -1,184 +1,116 @@ -using System; -using System.Globalization; - -namespace BeaverBuddies.Colonies -{ - /// - /// The trading post's offer form, kept free of the game so it can be checked headless: reading its boxes, what one - /// click of − or + does, and which of the form's messages applies. An offer the form calls an exchange, a gift or a - /// request is exactly one and accept. - /// A post carries at most of each side a round, but a player may type more: - /// what they type is then the whole trade, split into the fewest rounds that carry it (), and the - /// rounds box is not read. - /// - public static class TradeOfferForm - { - public enum Verdict - { - /// Something each way. - Exchange, - /// The offering colony gives and asks nothing back. - Gift, - /// The offering colony asks and gives nothing. - Request, - /// An amount box does not hold a whole number from 0 to . - BadAmount, - /// The rounds box does not hold a whole number from 1 to . - BadRounds, - /// Both amounts are 0. - NothingEitherWay, - /// A side with an amount has no item chosen. - NoItem, - /// Both sides give the same item. - SameItem, - /// A mixed-factions game: what the offering colony gives may not go to the other colony's faction. - GiveNotAllowed, - /// A mixed-factions game: what the offering colony asks for may not come to its own faction. - GetNotAllowed, - /// More than a round carries, and the two amounts don't split into equal rounds. - Uneven, - } - - public static bool IsOffer(Verdict verdict) => - verdict == Verdict.Exchange || verdict == Verdict.Gift || verdict == Verdict.Request; - - /// The most an amount box takes: a whole exchange's worth, a full round every round. - public const int MaxTyped = ExchangeTerms.MaxAmount * ExchangeTerms.MaxRounds; - - /// - /// An amount box: empty means 0; otherwise digits only, up to . More than - /// is split into rounds by . - /// - public static bool TryReadAmount(string text, out int amount) - { - text = text?.Trim(); - if (string.IsNullOrEmpty(text)) - { - amount = 0; - return true; - } - return int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out amount) && amount <= MaxTyped; - } - - /// The "keep at least" box: empty means 0; otherwise digits only, up to . - public static bool TryReadKeep(string text, out int keep) - { - text = text?.Trim(); - if (string.IsNullOrEmpty(text)) - { - keep = 0; - return true; - } - return int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out keep) && keep <= ExchangeTerms.MaxKeep; - } - - /// How far one click of − or + moves the reserve: fifty at a time (Shift: ten). - public static int KeepStep(bool shift) => shift ? 10 : 50; - - /// The rounds box: digits only, from 1 to . - public static bool TryReadRounds(string text, out int rounds) => - int.TryParse(text?.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out rounds) && ExchangeTerms.AreValidRounds(rounds); - - /// - /// The form as a whole. A repeating offer does not read the rounds box (it counts as 1 and is ignored). In a - /// mixed-factions game and say what the factions let - /// cross each way (FactionTrade); without them everything may. An offer comes back as each round's amounts - /// and the rounds, already split when a box held more than a round carries. - /// - public static Verdict Judge(string giveItem, string giveText, string getItem, string getText, string roundsText, bool repeat, - out int give, out int get, out int rounds, Func giveAllowed = null, Func getAllowed = null) => - Judge(giveItem, giveText, getItem, getText, roundsText, repeat, out give, out get, out rounds, out _, giveAllowed, getAllowed); - - /// - /// , - /// and whether the boxes were split into rounds (). - /// - public static Verdict Judge(string giveItem, string giveText, string getItem, string getText, string roundsText, bool repeat, - out int give, out int get, out int rounds, out bool split, Func giveAllowed = null, Func getAllowed = null) - { - split = false; - bool amountsRead = TryReadAmount(giveText, out give) & TryReadAmount(getText, out get); - rounds = 1; - if (!amountsRead) return Verdict.BadAmount; - if (give == 0 && get == 0) return Verdict.NothingEitherWay; - if ((give > 0 && string.IsNullOrEmpty(giveItem)) || (get > 0 && string.IsNullOrEmpty(getItem))) return Verdict.NoItem; - if (give > 0 && get > 0 && string.Equals(giveItem, getItem, StringComparison.Ordinal)) return Verdict.SameItem; - if (give > 0 && giveAllowed != null && !giveAllowed(giveItem)) return Verdict.GiveNotAllowed; - if (get > 0 && getAllowed != null && !getAllowed(getItem)) return Verdict.GetNotAllowed; - // More than a round carries is the whole trade: it is split into rounds, and the rounds box is not read. - bool whole = give > ExchangeTerms.MaxAmount || get > ExchangeTerms.MaxAmount; - if (!repeat && !whole && !TryReadRounds(roundsText, out rounds)) - { - rounds = 1; - return Verdict.BadRounds; - } - if (whole) - { - if (!Split(give, get, 1, repeat, out int eachGive, out int eachGet, out int splitRounds)) - return Needed(give, get) > ExchangeTerms.MaxRounds ? Verdict.BadAmount : Verdict.Uneven; - give = eachGive; - get = eachGet; - rounds = splitRounds; - split = true; - } - if (get == 0) return Verdict.Gift; - if (give == 0) return Verdict.Request; - return Verdict.Exchange; - } - - /// - /// Splits for a round, over rounds, into - /// the fewest equal rounds that carry exactly the whole: 300 for 300 once is 3 rounds of 100 for 100, and 250 for - /// 50 is 5 rounds of 50 for 10. The whole is never changed: false when no number of rounds up to - /// divides both amounts (500 for 1). A repeating offer keeps repeating, with - /// its round cut down to one such equal part. - /// - public static bool Split(int give, int get, int rounds, bool repeat, out int eachGive, out int eachGet, out int splitRounds) - { - if (repeat) rounds = 1; - long wholeGive = (long)Math.Max(0, give) * Math.Max(1, rounds), wholeGet = (long)Math.Max(0, get) * Math.Max(1, rounds); - eachGive = eachGet = 0; - splitRounds = 1; - for (long n = Needed(wholeGive, wholeGet); n <= ExchangeTerms.MaxRounds; n++) - { - if (wholeGive % n != 0 || wholeGet % n != 0) continue; - eachGive = (int)(wholeGive / n); - eachGet = (int)(wholeGet / n); - splitRounds = repeat ? 1 : (int)n; - return true; - } - return false; - } - - // The fewest rounds that could carry the whole: one per round's worth of the larger side. - private static long Needed(long wholeGive, long wholeGet) => - Math.Max(1, (Math.Max(wholeGive, wholeGet) + ExchangeTerms.MaxAmount - 1) / ExchangeTerms.MaxAmount); - - /// - /// How far one click of − or + moves an amount: ten at a time (Shift: one), beavers one at a time (Shift: ten). - /// - public static int Step(string item, bool shift) => item == ExchangeTerms.Beavers ? (shift ? 10 : 1) : (shift ? 1 : 10); - - /// How far one click moves the rounds: one (Shift: ten). - public static int RoundsStep(bool shift) => shift ? 10 : 1; - - /// - /// A number after one click: on to the next whole step (from 95, + gives 100 and − gives 90), within - /// and . - /// - public static int Stepped(int value, int step, bool up, int min, int max) - { - if (step <= 0) step = 1; - value = Math.Max(min, Math.Min(max, value)); - long next = up ? ((long)value / step + 1) * step : ((long)value + step - 1) / step * step - step; - return (int)Math.Max(min, Math.Min(max, next)); - } - - /// - /// An amount after one click, within 0 and ; an amount already typed above - /// that steps on within , so − and + never jump it back to one round's worth. - /// - public static int Stepped(int amount, int step, bool up) => - Stepped(amount, step, up, 0, amount > ExchangeTerms.MaxAmount ? MaxTyped : ExchangeTerms.MaxAmount); - } -} +using System; +using System.Globalization; + +namespace BeaverBuddies.Colonies +{ + /// + /// The trading post's offer form, kept free of the game so it can be checked headless: reading its boxes, what one + /// click of − or + does, and which of the form's messages applies. A player types the whole trade ("101 Logs for 2 + /// Gears"); an offer the form calls an exchange, a gift or a request is exactly one + /// accepts, and it is never refused for its amounts: the game carries it in + /// rounds of up to each, spread as evenly + /// as it goes. A repeating offer's amounts are each round's, up to . + /// + public static class TradeOfferForm + { + public enum Verdict + { + /// Something each way. + Exchange, + /// The offering colony gives and asks nothing back. + Gift, + /// The offering colony asks and gives nothing. + Request, + /// An amount box does not hold a whole number from 0 to . + BadAmount, + /// Both amounts are 0. + NothingEitherWay, + /// A side with an amount has no item chosen. + NoItem, + /// Both sides give the same item. + SameItem, + /// A mixed-factions game: what the offering colony gives may not go to the other colony's faction. + GiveNotAllowed, + /// A mixed-factions game: what the offering colony asks for may not come to its own faction. + GetNotAllowed, + } + + public static bool IsOffer(Verdict verdict) => + verdict == Verdict.Exchange || verdict == Verdict.Gift || verdict == Verdict.Request; + + /// The most an amount box takes: a whole exchange's worth, a full round every round. + public const int MaxTyped = ExchangeTerms.MaxWhole; + + /// The most an amount box takes for a repeating offer (each round's) or a whole one. + public static int MaxFor(bool repeat) => repeat ? ExchangeTerms.MaxAmount : MaxTyped; + + /// An amount box: empty means 0; otherwise digits only, up to . + public static bool TryReadAmount(string text, out int amount) + { + text = text?.Trim(); + if (string.IsNullOrEmpty(text)) + { + amount = 0; + return true; + } + return int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out amount) && amount <= MaxTyped; + } + + /// The "keep at least" box: empty means 0; otherwise digits only, up to . + public static bool TryReadKeep(string text, out int keep) + { + text = text?.Trim(); + if (string.IsNullOrEmpty(text)) + { + keep = 0; + return true; + } + return int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out keep) && keep <= ExchangeTerms.MaxKeep; + } + + /// How far one click of − or + moves the reserve: fifty at a time (Shift: ten). + public static int KeepStep(bool shift) => shift ? 10 : 50; + + /// + /// The form as a whole: the whole trade as typed, and the rounds the game carries it in (a repeating offer: 1, + /// each round the same). In a mixed-factions game and + /// say what the factions let cross each way (FactionTrade); without them everything may. + /// + public static Verdict Judge(string giveItem, string giveText, string getItem, string getText, bool repeat, + out int give, out int get, out int rounds, Func giveAllowed = null, Func getAllowed = null) + { + bool amountsRead = TryReadAmount(giveText, out give) & TryReadAmount(getText, out get); + rounds = 1; + if (!amountsRead || give > MaxFor(repeat) || get > MaxFor(repeat)) return Verdict.BadAmount; + if (give == 0 && get == 0) return Verdict.NothingEitherWay; + if ((give > 0 && string.IsNullOrEmpty(giveItem)) || (get > 0 && string.IsNullOrEmpty(getItem))) return Verdict.NoItem; + if (give > 0 && get > 0 && string.Equals(giveItem, getItem, StringComparison.Ordinal)) return Verdict.SameItem; + if (give > 0 && giveAllowed != null && !giveAllowed(giveItem)) return Verdict.GiveNotAllowed; + if (get > 0 && getAllowed != null && !getAllowed(getItem)) return Verdict.GetNotAllowed; + rounds = repeat ? 1 : ExchangeTerms.RoundsFor(give, get); + if (get == 0) return Verdict.Gift; + if (give == 0) return Verdict.Request; + return Verdict.Exchange; + } + + /// + /// How far one click of − or + moves an amount: ten at a time (Shift: one), beavers one at a time (Shift: ten). + /// + public static int Step(string item, bool shift) => item == ExchangeTerms.Beavers ? (shift ? 10 : 1) : (shift ? 1 : 10); + + /// + /// A number after one click: on to the next whole step (from 95, + gives 100 and − gives 90), within + /// and . + /// + public static int Stepped(int value, int step, bool up, int min, int max) + { + if (step <= 0) step = 1; + value = Math.Max(min, Math.Min(max, value)); + long next = up ? ((long)value / step + 1) * step : ((long)value + step - 1) / step * step - step; + return (int)Math.Max(min, Math.Min(max, next)); + } + + /// An amount after one click, within 0 and what the box takes (). + public static int Stepped(int amount, int step, bool up, bool repeat) => Stepped(amount, step, up, 0, MaxFor(repeat)); + } +} diff --git a/BeaverBuddies/Colonies/TradeOverviewPanel.cs b/BeaverBuddies/Colonies/TradeOverviewPanel.cs index daa0d07..ca41344 100644 --- a/BeaverBuddies/Colonies/TradeOverviewPanel.cs +++ b/BeaverBuddies/Colonies/TradeOverviewPanel.cs @@ -837,9 +837,8 @@ private void Describe(DistrictCrossing half, ColonyExchangeService exchanges, ou detail = T("BeaverBuddies.Colony.Overview.Idle"); return; } - // The whole deal: every round's amounts added up, or one round's for an exchange that repeats until stopped. - int rounds = mine.Repeat ? 1 : Math.Max(1, mine.Rounds); - string give = exchanges.Amount(mine.Total * rounds, mine.GoodId), get = exchanges.Amount(theirs.Total * rounds, theirs.GoodId); + // The whole deal as offered, or one round's for an exchange that repeats until stopped. + string give = exchanges.Amount(mine.Whole, mine.GoodId), get = exchanges.Amount(theirs.Whole, theirs.GoodId); string dealKey = mine.Repeat ? "BeaverBuddies.Colony.Overview.DealRepeat" : "BeaverBuddies.Colony.Overview.Deal"; string deal = string.Format(T(dealKey), give, get); if (mine.State == ExchangeState.Proposed) diff --git a/BeaverBuddies/Colonies/TradingPostExchange.cs b/BeaverBuddies/Colonies/TradingPostExchange.cs index 043d477..abe4b7a 100644 --- a/BeaverBuddies/Colonies/TradingPostExchange.cs +++ b/BeaverBuddies/Colonies/TradingPostExchange.cs @@ -44,6 +44,7 @@ public class CrossingExchange : BaseComponent, IAwakableComponent, IPersistentEn private static readonly PropertyKey ProposedHereKey = new PropertyKey("ProposedHere"); private static readonly PropertyKey GoodKey = new PropertyKey("Good"); private static readonly PropertyKey TotalKey = new PropertyKey("Total"); + private static readonly PropertyKey WholeKey = new PropertyKey("Whole"); private static readonly PropertyKey HeldKey = new PropertyKey("Held"); private static readonly PropertyKey SerialKey = new PropertyKey("Serial"); private static readonly PropertyKey RepeatKey = new PropertyKey("Repeat"); @@ -64,8 +65,16 @@ public class CrossingExchange : BaseComponent, IAwakableComponent, IPersistentEn public bool ProposedHere { get; private set; } /// What this half's colony gives each round, or null for nothing. public string GoodId { get; private set; } - /// How many of it each round (0 to ). + /// + /// How many of it this round (0 to ): its share of , set + /// again as each round starts (), so the rounds add up to exactly the whole. + /// public int Total { get; private set; } + /// + /// How many of it over the whole exchange, as offered (a repeating exchange: each round's). What the players + /// see; the rounds are the game's detail. + /// + public int Whole { get; private set; } /// How many of this round's goods already wait on this half (reserved there, so nobody takes them). public int Held { get; private set; } /// @@ -98,16 +107,18 @@ public class CrossingExchange : BaseComponent, IAwakableComponent, IPersistentEn public bool IsActive => State == ExchangeState.Active; public bool GivesGoods => Total > 0 && GoodId != null && !ExchangeTerms.IsSpecial(GoodId); - internal void Propose(int serial, bool proposedHere, string goodId, int total, int rounds, bool repeat, int colony, int keep) + /// is this side's whole (a repeating exchange: each round's). + internal void Propose(int serial, bool proposedHere, string goodId, int whole, int rounds, bool repeat, int colony, int keep) { Serial = serial; State = ExchangeState.Proposed; ProposedHere = proposedHere; - GoodId = ExchangeTerms.GoodOf(goodId, total); - Total = total; + GoodId = ExchangeTerms.GoodOf(goodId, whole); + Whole = whole; Held = 0; Repeat = repeat; Rounds = repeat ? 1 : rounds; + Total = repeat ? whole : ExchangeTerms.ShareOf(whole, Rounds, 0); Done = 0; CancelAsked = false; Colony = colony; @@ -145,6 +156,8 @@ internal void Crossed() { Done++; Held = 0; + // The next round's share of the whole (a repeating exchange's rounds are all the same). + if (!Repeat && Done < Rounds) Total = ExchangeTerms.ShareOf(Whole, Rounds, Done); Changed("exchange-crossed"); } @@ -170,7 +183,7 @@ internal void Record(TradeRecord record) /// Diagnostics: every field, open or not (a serial that differs makes Accept or Cancel skip on one computer only). public long Fingerprint() => - 1 + (int)State + 3L * Held + 7919L * Total + 104729L * Done + 15485863L * Serial + 1299709L * Rounds + 1 + (int)State + 3L * Held + 7919L * Total + 31L * Whole + 104729L * Done + 15485863L * Serial + 1299709L * Rounds + (CancelAsked ? 2 : 0) + (Repeat ? 4 : 0) + (ProposedHere ? 8 : 0) + 16L * (Colony + 2) + 17L * ColonyDigest.Of(GoodId) + 19L * ledger.Count + (ledger.Count > 0 ? ColonyDigest.Of(ledger[ledger.Count - 1].Encode()) : 0) + 23L * Keep + 29L * ColonyDigest.Of(LastTerms); @@ -188,6 +201,7 @@ internal void Clear() ProposedHere = false; GoodId = null; Total = 0; + Whole = 0; Held = 0; Repeat = false; Rounds = 0; @@ -212,6 +226,7 @@ public void Save(IEntitySaver entitySaver) saver.Set(ProposedHereKey, ProposedHere ? 1 : 0); if (!string.IsNullOrEmpty(GoodId)) saver.Set(GoodKey, GoodId); saver.Set(TotalKey, Total); + saver.Set(WholeKey, Whole); if (Held > 0) saver.Set(HeldKey, Held); if (Repeat) saver.Set(RepeatKey, 1); saver.Set(RoundsKey, Rounds); @@ -239,14 +254,17 @@ public void Load(IEntityLoader entityLoader) int total = loader.Has(TotalKey) ? loader.Get(TotalKey) : 0; int rounds = loader.Has(RoundsKey) ? loader.Get(RoundsKey) : 1; bool repeat = loader.Has(RepeatKey) && loader.Get(RepeatKey) != 0; + int whole = loader.Has(WholeKey) ? loader.Get(WholeKey) : total; // Only a state an exchange can be in (a side that gives nothing has no good and 0). if (state < (int)ExchangeState.Proposed || state > (int)ExchangeState.Active || total < 0 || total > ExchangeTerms.MaxAmount - || (total > 0 && string.IsNullOrEmpty(good)) || (!repeat && !ExchangeTerms.AreValidRounds(rounds))) + || whole < 0 || whole > (repeat ? ExchangeTerms.MaxAmount : ExchangeTerms.MaxWhole) + || (whole > 0 && string.IsNullOrEmpty(good)) || (!repeat && !ExchangeTerms.AreValidRounds(rounds))) return; State = (ExchangeState)state; ProposedHere = loader.Has(ProposedHereKey) && loader.Get(ProposedHereKey) != 0; - GoodId = ExchangeTerms.GoodOf(good, total); + GoodId = ExchangeTerms.GoodOf(good, whole); Total = total; + Whole = whole; Held = loader.Has(HeldKey) ? Math.Max(0, Math.Min(total, loader.Get(HeldKey))) : 0; Repeat = repeat; Rounds = repeat ? 1 : rounds; @@ -507,8 +525,7 @@ private void CheckTradingPosts() bool trading = partnerOpen && TradingPosts.IsTradingPost(half); // A mixed-factions game: terms the factions no longer allow (a colony founded again as another faction), // judged only while the post trades (C1). - bool factionsAllow = !trading || FactionsAllow(owner, partnerOwner, mine.Total > 0 ? mine.GoodId : null, - theirs.Total > 0 ? theirs.GoodId : null); + bool factionsAllow = !trading || FactionsAllow(owner, partnerOwner, mine.GoodId, theirs.GoodId); switch (ExchangeTerms.Ending(partnerOpen, mine.ProposedHere, mine.Colony, owner, theirs?.Colony ?? -1, partnerOwner, trading, factionsAllow)) { @@ -666,8 +683,10 @@ private void Cross(DistrictCrossing a, DistrictCrossing b, int aSlot, int bSlot) if (aTotal > 0) totals?.Record(aSlot, bSlot, aGood, aTotal); if (bTotal > 0) totals?.Record(bSlot, aSlot, bGood, bTotal); int cycle = _gameCycleService.Cycle, day = _gameCycleService.CycleDay; - ax.Record(new TradeRecord(cycle, day, aGood, aTotal, bGood, bTotal)); - bx.Record(new TradeRecord(cycle, day, bGood, bTotal, aGood, aTotal)); + // A round may carry none of a side's whole (1 Gear over 5 rounds): the ledger says nothing for it. + string aGave = ExchangeTerms.GoodOf(aGood, aTotal), bGave = ExchangeTerms.GoodOf(bGood, bTotal); + ax.Record(new TradeRecord(cycle, day, aGave, aTotal, bGave, bTotal)); + bx.Record(new TradeRecord(cycle, day, bGave, bTotal, aGave, aTotal)); Plugin.Log($"[Colony] Exchange {ax.Serial} round {ax.Done} crossed: slot {aSlot} gave {aTotal} {aGood}, slot {bSlot} gave {bTotal} {bGood}"); if (ExchangeTerms.HasAnotherRound(ax.Rounds, ax.Done, ax.Repeat)) return; int rounds = ax.Done; @@ -746,8 +765,9 @@ public string WhyNotPropose(DistrictCrossing half, int actorSlot, string giveGoo if (!half) return "no such crossing"; if (!TradingPosts.IsTradingPost(half)) return "the crossing is not a Trading Post between two colonies"; if (actorSlot < 0 || OwnerOf(half) != actorSlot) return $"the half is slot {OwnerOf(half)}'s, not slot {actorSlot}'s"; - if (!ExchangeTerms.AreValid(giveGood, giveAmount, getGood, getAmount)) return "the terms are not valid"; - if (!repeat && !ExchangeTerms.AreValidRounds(rounds)) return $"{rounds} rounds"; + if (!ExchangeTerms.AreValidTerms(giveGood, giveAmount, getGood, getAmount, repeat)) return "the terms are not valid"; + // The rounds follow from the amounts (a Trading Post carries up to MaxAmount of each a round). + if (!repeat && rounds != ExchangeTerms.RoundsFor(giveAmount, getAmount)) return $"{rounds} rounds for {giveAmount} for {getAmount}"; if (!ExchangeTerms.IsValidKeep(keep)) return $"a reserve of {keep}"; if ((giveAmount > 0 && !IsKnownItem(giveGood)) || (getAmount > 0 && !IsKnownItem(getGood))) return "a good is unknown in this game, or science is not separate"; @@ -763,6 +783,10 @@ public string WhyNotPropose(DistrictCrossing half, int actorSlot, string giveGoo public bool IsKnownItem(string item) => item == ExchangeTerms.Beavers || (item == ExchangeTerms.Science ? ColonyScienceService.IsEnabled : _goodService.HasGood(item)); + /// + /// An offer of for in all, over + /// rounds (a repeating one: each round's, until both stop). + /// public void Propose(DistrictCrossing half, int actorSlot, string giveGood, int giveAmount, string getGood, int getAmount, int rounds, bool repeat, int keep = 0) { @@ -786,9 +810,9 @@ public void Propose(DistrictCrossing half, int actorSlot, string giveGood, int g theirs.RememberTerms(ExchangeTerms.EncodeTerms(getGood, getAmount, giveGood, giveAmount, rounds, repeat, 0)); Plugin.Log($"[Colony] Slot {from} offers {giveAmount} {giveGood} for {getAmount} {getGood} from slot {to}, " + $"{(repeat ? "repeating" : rounds + " rounds")}{(keep > 0 ? $", keeping {keep}" : "")} (exchange {serial})"); - // The notice says the whole exchange (every round's goods), not one round's. - Ask(() => to, partner, () => Whole("BeaverBuddies.Colony.Trade.Notice.Proposed", "BeaverBuddies.Colony.Trade.Notice.ProposedRounds", - "BeaverBuddies.Colony.Trade.Notice.ProposedRepeat", ColonyName(from), giveGood, giveAmount, getGood, getAmount, rounds, repeat), warning: false); + // The notice says the whole exchange, as offered; the rounds are the game's detail. + Ask(() => to, partner, () => Whole("BeaverBuddies.Colony.Trade.Notice.Proposed", "BeaverBuddies.Colony.Trade.Notice.ProposedRepeat", + ColonyName(from), giveGood, giveAmount, getGood, getAmount, repeat), warning: false); } /// @@ -808,15 +832,15 @@ public void Accept(DistrictCrossing half, int actorSlot, int serial, string give why = "no offer is waiting here"; else if (actorSlot < 0 || OwnerOf(half) != actorSlot) why = $"the half is slot {OwnerOf(half)}'s, not slot {actorSlot}'s"; - else if (mine.Serial != serial || mine.Repeat != repeat || (!repeat && mine.Rounds != rounds) || mine.Total != giveAmount - || theirs.Total != getAmount || mine.GoodId != ExchangeTerms.GoodOf(giveGood, giveAmount) + else if (mine.Serial != serial || mine.Repeat != repeat || (!repeat && mine.Rounds != rounds) || mine.Whole != giveAmount + || theirs.Whole != getAmount || mine.GoodId != ExchangeTerms.GoodOf(giveGood, giveAmount) || theirs.GoodId != ExchangeTerms.GoodOf(getGood, getAmount)) why = "the offer changed"; // A mixed game only (the faction check below needs the colony it was offered to); otherwise the tick's // check ends such an exchange, as before. else if (Factions.MixedFactions.IsOn && theirs.Colony >= 0 && OwnerOf(partner) != theirs.Colony) why = "the other half has changed colony"; - else if (!FactionsAllow(OwnerOf(half), OwnerOf(partner), mine.Total > 0 ? mine.GoodId : null, theirs.Total > 0 ? theirs.GoodId : null)) + else if (!FactionsAllow(OwnerOf(half), OwnerOf(partner), mine.GoodId, theirs.GoodId)) why = FactionsRefuse; if (why != null) { @@ -829,9 +853,8 @@ public void Accept(DistrictCrossing half, int actorSlot, int serial, string give int me = OwnerOf(half), them = OwnerOf(partner); Plugin.Log($"[Colony] Slot {me} accepted exchange {serial}: {getAmount} {getGood} for {giveAmount} {giveGood}"); // The colony that offered hears it, and a chime says so (it may be looking elsewhere). - Tell(() => them, null, () => Whole("BeaverBuddies.Colony.Trade.Notice.Accepted", "BeaverBuddies.Colony.Trade.Notice.AcceptedRounds", - "BeaverBuddies.Colony.Trade.Notice.AcceptedRepeat", ColonyName(me), theirs.GoodId, theirs.Total, mine.GoodId, mine.Total, - mine.Rounds, mine.Repeat), warning: false, chime: true); + Tell(() => them, null, () => Whole("BeaverBuddies.Colony.Trade.Notice.Accepted", "BeaverBuddies.Colony.Trade.Notice.AcceptedRepeat", + ColonyName(me), theirs.GoodId, theirs.Whole, mine.GoodId, mine.Whole, mine.Repeat), warning: false, chime: true); } /// @@ -1162,17 +1185,12 @@ private static void Answered(DistrictCrossing half, int actorSlot) } /// - /// A notice about a whole exchange, "{colony} offers {1} for {2}": for one round, - /// with every round's goods added up and the rounds, for a - /// standing deal (one round's goods, every round). + /// A notice about a whole exchange, "{colony} offers {1} for {2}": with the whole as + /// offered (never the rounds), for a standing deal (one round's goods, every round). /// - private string Whole(string once, string many, string repeating, string colony, string giveGood, int giveAmount, string getGood, - int getAmount, int rounds, bool repeat) - { - if (repeat) return string.Format(T(repeating), colony, Amount(giveAmount, giveGood), Amount(getAmount, getGood)); - if (rounds <= 1) return string.Format(T(once), colony, Amount(giveAmount, giveGood), Amount(getAmount, getGood)); - return string.Format(T(many), colony, Amount(giveAmount * rounds, giveGood), Amount(getAmount * rounds, getGood), rounds); - } + private string Whole(string once, string repeating, string colony, string giveGood, int giveAmount, string getGood, + int getAmount, bool repeat) => + string.Format(T(repeat ? repeating : once), colony, Amount(giveAmount, giveGood), Amount(getAmount, getGood)); /// "100 Planks", "1 Beaver", or "nothing" for a side that gives nothing. public string Amount(int amount, string goodId) => @@ -1206,6 +1224,7 @@ public class ExchangeProposedEvent : ReplayEvent { public string crossingID; public string giveGood; + // The whole exchange's amounts (a repeating one: each round's), and the rounds they take (ExchangeTerms.RoundsFor). public int giveAmount; public string getGood; public int getAmount; diff --git a/BeaverBuddies/Colonies/TradingPostFragment.cs b/BeaverBuddies/Colonies/TradingPostFragment.cs index 5873a5a..5304ba9 100644 --- a/BeaverBuddies/Colonies/TradingPostFragment.cs +++ b/BeaverBuddies/Colonies/TradingPostFragment.cs @@ -94,7 +94,6 @@ private sealed class ChipRow private VisualElement compose; private OfferSide giveSide, getSide; private TextField roundsBox; - private Button roundsLess, roundsMore; private Label roundsNote; private Label summary; private Toggle repeatToggle; @@ -330,11 +329,13 @@ private OfferSide BuildOfferSide(int side, string caption) minus.style.marginLeft = 4; _tooltipRegistrar.Register(minus, () => StepTooltip(o, "BeaverBuddies.Colony.Trade.StepLess")); row.Add(minus); - // Room for more than a round carries: the offer is then split into rounds (TradeOfferForm.Split). + // The whole trade, up to 9,900 (a repeating one: each round's, up to 100); the game carries it in rounds. o.Amount = NativeElements.InputBox(maxLength: 4, width: 50); o.Amount.value = ExchangeTerms.MaxAmount.ToString(CultureInfo.InvariantCulture); - o.Amount.RegisterValueChangedCallback(_ => RefreshSummary()); - _tooltipRegistrar.Register(o.Amount, () => string.Format(T("BeaverBuddies.Colony.Trade.AmountTooltip"), ExchangeTerms.MaxAmount)); + o.Amount.RegisterValueChangedCallback(_ => { FitRepeating(); RefreshSummary(); }); + _tooltipRegistrar.Register(o.Amount, () => repeatToggle != null && repeatToggle.value + ? string.Format(T("BeaverBuddies.Colony.Trade.AmountTooltipRepeat"), ExchangeTerms.MaxAmount) + : string.Format(T("BeaverBuddies.Colony.Trade.AmountTooltip"), Count(TradeOfferForm.MaxTyped))); row.Add(o.Amount); Button plus = NativeElements.SquareButton(plus: true, e => StepAmount(o, up: true, e.shiftKey)); _tooltipRegistrar.Register(plus, () => StepTooltip(o, "BeaverBuddies.Colony.Trade.StepMore")); @@ -343,7 +344,10 @@ private OfferSide BuildOfferSide(int side, string caption) return o; } - /// "Rounds" [−] [3] [+] with the check box for a standing deal, on the description's blue. + /// + /// "Rounds" [3] with the check box for a standing deal, on the description's blue. The box only shows how many + /// rounds the game carries the trade in (a Trading Post carries up to 100 of each a round); nobody types in it. + /// private VisualElement BuildRounds() { NineSliceVisualElement card = Card(); @@ -359,21 +363,15 @@ private VisualElement BuildRounds() card.Add(top); VisualElement row = NativeElements.Row(); - roundsLess = NativeElements.SquareButton(plus: false, e => StepRounds(up: false, e.shiftKey)); - _tooltipRegistrar.Register(roundsLess, () => string.Format(T("BeaverBuddies.Colony.Trade.StepLess"), TradeOfferForm.RoundsStep(false), TradeOfferForm.RoundsStep(true))); - row.Add(roundsLess); roundsBox = NativeElements.InputBox(maxLength: 2, width: 36); roundsBox.value = "1"; - roundsBox.RegisterValueChangedCallback(_ => RefreshSummary()); - _tooltipRegistrar.Register(roundsBox, () => string.Format(T("BeaverBuddies.Colony.Trade.RoundsTooltip"), ExchangeTerms.MaxRounds)); + roundsBox.SetEnabled(false); + _tooltipRegistrar.Register(roundsBox, () => string.Format(T("BeaverBuddies.Colony.Trade.RoundsTooltip"), ExchangeTerms.MaxAmount)); row.Add(roundsBox); - roundsMore = NativeElements.SquareButton(plus: true, e => StepRounds(up: true, e.shiftKey)); - _tooltipRegistrar.Register(roundsMore, () => string.Format(T("BeaverBuddies.Colony.Trade.StepMore"), TradeOfferForm.RoundsStep(false), TradeOfferForm.RoundsStep(true))); - row.Add(roundsMore); repeatToggle = NativeElements.CheckBox(T("BeaverBuddies.Colony.Trade.RepeatToggle")); repeatToggle.style.marginLeft = 10; repeatToggle.style.flexShrink = 1; - repeatToggle.RegisterValueChangedCallback(_ => RefreshSummary()); + repeatToggle.RegisterValueChangedCallback(_ => { FitRepeating(); RefreshSummary(); }); _tooltipRegistrar.Register(repeatToggle, T("BeaverBuddies.Colony.Trade.RepeatTooltip")); row.Add(repeatToggle); card.Add(row); @@ -926,9 +924,10 @@ private void Remember(ExchangeState state, CrossingExchange ax, CrossingExchange shownSerial = state == ExchangeState.None ? 0 : ax.Serial; if (state == ExchangeState.None) return; shownGiveGood = ax.GoodId; - shownGiveAmount = ax.Total; + // The whole trade, as offered (what Accept checks). + shownGiveAmount = ax.Whole; shownGetGood = bx.GoodId; - shownGetAmount = bx.Total; + shownGetAmount = bx.Whole; shownRounds = ax.Rounds; shownRepeat = ax.Repeat; } @@ -991,7 +990,7 @@ private void RefreshCompose(DistrictCrossing mine, DistrictCrossing theirs, int RefreshSummary(); } - /// "Last exchange here: 100 Logs for 25 Gears, 4 rounds." with Offer again, when this half remembers one. + /// "Last exchange here: 400 Logs for 100 Gears." with Offer again, when this half remembers one. private void RefreshLast(CrossingExchange ax, int them) { string give = null, get = null; @@ -1001,10 +1000,8 @@ private void RefreshLast(CrossingExchange ax, int them) out rounds, out repeat, out _); NativeElements.Show(lastRow, known); if (!known) return; - string terms = string.Format(T("BeaverBuddies.Colony.Trade.LastTerms"), AmountOf(giveAmount, give), AmountOf(getAmount, get)) - ; - string lastRounds = RoundsText(rounds, repeat, giveAmount, getAmount); - if (lastRounds.Length > 0) terms += "\n" + lastRounds; + string terms = string.Format(T("BeaverBuddies.Colony.Trade.LastTerms"), AmountOf(giveAmount, give), AmountOf(getAmount, get)); + if (repeat) terms += "\n" + T("BeaverBuddies.Colony.Trade.RoundsRepeatLine"); NativeElements.SetText(lastLabel, terms); } @@ -1037,9 +1034,10 @@ private void ApplyPrefill() prefillPending = false; if (prefillGive != null && _items.IsOffered(prefillGive)) giveItem = prefillGive; if (prefillGet != null && _items.IsOffered(prefillGet) && prefillGet != giveItem) getItem = prefillGet; - giveSide.Amount.SetValueWithoutNotify(Math.Max(0, Math.Min(ExchangeTerms.MaxAmount, prefillGiveAmount)).ToString(CultureInfo.InvariantCulture)); - getSide.Amount.SetValueWithoutNotify(Math.Max(0, Math.Min(ExchangeTerms.MaxAmount, prefillGetAmount)).ToString(CultureInfo.InvariantCulture)); - roundsBox.SetValueWithoutNotify(Math.Max(1, Math.Min(ExchangeTerms.MaxRounds, prefillRounds)).ToString(CultureInfo.InvariantCulture)); + // The terms are whole trades (a repeating one's: each round's), as offered. + int most = TradeOfferForm.MaxFor(prefillRepeat); + giveSide.Amount.SetValueWithoutNotify(Math.Max(0, Math.Min(most, prefillGiveAmount)).ToString(CultureInfo.InvariantCulture)); + getSide.Amount.SetValueWithoutNotify(Math.Max(0, Math.Min(most, prefillGetAmount)).ToString(CultureInfo.InvariantCulture)); repeatToggle.SetValueWithoutNotify(prefillRepeat); keepBox.SetValueWithoutNotify(Math.Max(0, Math.Min(ExchangeTerms.MaxKeep, prefillKeep)).ToString(CultureInfo.InvariantCulture)); } @@ -1069,14 +1067,10 @@ private void RefreshSummary() if (summary == null) return; bool repeat = repeatToggle.value; TradeOfferForm.Verdict verdict = TradeOfferForm.Judge(giveItem, giveSide.Amount.value, getItem, getSide.Amount.value, - roundsBox.value, repeat, out int give, out int get, out int rounds, out bool split, GiveAllowed(), GetAllowed()); - // An amount over a round is the whole trade, so the rounds box has no say (nor for a repeating offer). - bool roundsUsed = !repeat && !split; - roundsBox.SetEnabled(roundsUsed); - roundsLess.SetEnabled(roundsUsed); - roundsMore.SetEnabled(roundsUsed); - // The greyed box says how many rounds the whole trade is split into, not a number it ignores. - if (split && !repeat) roundsBox.SetValueWithoutNotify(rounds.ToString(CultureInfo.InvariantCulture)); + repeat, out int give, out int get, out int rounds, GiveAllowed(), GetAllowed()); + // The greyed box shows how many rounds the game carries the trade in: one per 100 of the larger side, or + // "∞" for a repeating one. It says nothing while the form holds no offer. + roundsBox.SetValueWithoutNotify(!TradeOfferForm.IsOffer(verdict) ? "" : repeat ? "∞" : rounds.ToString(CultureInfo.InvariantCulture)); // A reserve matters over more than one round, and only when this side gives something. bool keepShown = give > 0 && (repeat || rounds > 1); NativeElements.Show(keepCard, keepShown); @@ -1093,22 +1087,16 @@ private void RefreshSummary() switch (verdict) { case TradeOfferForm.Verdict.Exchange: - text = string.Format(T("BeaverBuddies.Colony.Trade.SummaryExchange"), AmountOf(give * (repeat ? 1 : rounds), giveItem), AmountOf(get * (repeat ? 1 : rounds), getItem)); + text = string.Format(T("BeaverBuddies.Colony.Trade.SummaryExchange"), AmountOf(give, giveItem), AmountOf(get, getItem)); break; case TradeOfferForm.Verdict.Gift: - text = string.Format(T("BeaverBuddies.Colony.Trade.SummaryGift"), partner, AmountOf(give * (repeat ? 1 : rounds), giveItem)); + text = string.Format(T("BeaverBuddies.Colony.Trade.SummaryGift"), partner, AmountOf(give, giveItem)); break; case TradeOfferForm.Verdict.Request: - text = string.Format(T("BeaverBuddies.Colony.Trade.SummaryRequest"), partner, AmountOf(get * (repeat ? 1 : rounds), getItem)); + text = string.Format(T("BeaverBuddies.Colony.Trade.SummaryRequest"), partner, AmountOf(get, getItem)); break; case TradeOfferForm.Verdict.BadAmount: - text = string.Format(T("BeaverBuddies.Colony.Trade.ErrorAmount"), Count(TradeOfferForm.MaxTyped), ExchangeTerms.MaxRounds); - break; - case TradeOfferForm.Verdict.Uneven: - text = string.Format(T("BeaverBuddies.Colony.Trade.ErrorUneven"), ExchangeTerms.MaxAmount); - break; - case TradeOfferForm.Verdict.BadRounds: - text = string.Format(T("BeaverBuddies.Colony.Trade.ErrorRounds"), ExchangeTerms.MaxRounds); + text = string.Format(T("BeaverBuddies.Colony.Trade.ErrorAmount"), Count(TradeOfferForm.MaxFor(repeat))); break; case TradeOfferForm.Verdict.NothingEitherWay: text = T("BeaverBuddies.Colony.Trade.ErrorNothing"); @@ -1129,30 +1117,14 @@ private void RefreshSummary() break; } bool offer = TradeOfferForm.IsOffer(verdict); - // Each thing on its own line: the deal, then how it is split into rounds. - if (offer) - { - string rounding = RoundsText(rounds, repeat, give, get); - if (rounding.Length > 0) text += "\n" + rounding; - // A repeating offer typed over a round's worth repeats one equal part of it: say what each round is. - if (split && repeat) - text += "\n" + string.Format(T("BeaverBuddies.Colony.Trade.SummarySplitRepeat"), AmountOf(give, giveItem), AmountOf(get, getItem), ExchangeTerms.MaxAmount); - } + // The deal as typed; the rounds are the game's detail (only a standing deal says it repeats). + if (offer && repeat) text += "\n" + T("BeaverBuddies.Colony.Trade.RoundsRepeatLine"); if (offer && keepShown && keep > 0) text += "\n" + string.Format(T("BeaverBuddies.Colony.Trade.SummaryKeep"), Count(keep), _items.Name(giveItem)); NativeElements.SetText(summary, text); summary.style.color = offer ? NativeElements.Muted : NativeElements.Warning; makeOfferButton.SetEnabled(offer); } - /// "Once.", "3 rounds: 300 Berries for 3 Beavers in all.", or "Round after round, until you both agree to stop." - private string RoundsText(int rounds, bool repeat, int give, int get) - { - if (rounds <= 1 && !repeat) return ""; - string each = give > 0 && get > 0 ? Count(give) + "/" + Count(get) : Count(Math.Max(give, get)); - return repeat ? string.Format(T("BeaverBuddies.Colony.Trade.RoundsRepeat"), each) - : string.Format(T("BeaverBuddies.Colony.Trade.RoundsMany"), rounds, each); - } - private string ItemOf(OfferSide side) => side.Side == Give ? giveItem : getItem; private void SetItem(OfferSide side, string item) @@ -1164,16 +1136,22 @@ private void SetItem(OfferSide side, string item) private void StepAmount(OfferSide side, bool up, bool shift) { TradeOfferForm.TryReadAmount(side.Amount.value, out int amount); - int next = TradeOfferForm.Stepped(amount, TradeOfferForm.Step(ItemOf(side), shift), up); + int next = TradeOfferForm.Stepped(amount, TradeOfferForm.Step(ItemOf(side), shift), up, repeatToggle.value); side.Amount.value = next.ToString(CultureInfo.InvariantCulture); } - private void StepRounds(bool up, bool shift) + /// + /// A repeating offer's amounts are each round's, so they go no higher than a round carries: a box holding more is + /// brought down to that, never refused. + /// + private void FitRepeating() { - if (repeatToggle.value) return; - if (!TradeOfferForm.TryReadRounds(roundsBox.value, out int rounds)) rounds = 1; - int next = TradeOfferForm.Stepped(rounds, TradeOfferForm.RoundsStep(shift), up, 1, ExchangeTerms.MaxRounds); - roundsBox.value = next.ToString(CultureInfo.InvariantCulture); + if (repeatToggle == null || !repeatToggle.value) return; + foreach (OfferSide side in new[] { giveSide, getSide }) + { + if (side?.Amount == null || !TradeOfferForm.TryReadAmount(side.Amount.value, out int amount) || amount <= ExchangeTerms.MaxAmount) continue; + side.Amount.SetValueWithoutNotify(ExchangeTerms.MaxAmount.ToString(CultureInfo.InvariantCulture)); + } } private string StepTooltip(OfferSide side, string key) => @@ -1235,12 +1213,13 @@ private void RefreshProposal(CrossingExchange ax, CrossingExchange bx, bool canA NativeElements.SetText(proposalNote, ""); ShowTerm(firstTerm, T("BeaverBuddies.Colony.Trade.YouGetCaption"), bx, ""); // Whether the colony can keep its side. - string have = ax.Total > 0 + string have = ax.Whole > 0 ? string.Format(T("BeaverBuddies.Colony.Trade.YouHaveNote"), Count(_items.StockOf(crossing, OwnerOf(crossing), ax.GoodId))) : ""; ShowTerm(secondTerm, T("BeaverBuddies.Colony.Trade.YouGiveCaption"), ax, have); } - NativeElements.SetText(proposalRounds, RoundsText(ax.Rounds, ax.Repeat, ax.Total, bx.Total)); + // An offer says the whole trade; only a standing deal says it repeats. + NativeElements.SetText(proposalRounds, ax.Repeat ? T("BeaverBuddies.Colony.Trade.RoundsRepeatLine") : ""); NativeElements.Show(acceptButton, !offeredHere && canAccept); NativeElements.Show(declineButton, !offeredHere); NativeElements.Show(withdrawButton, offeredHere); @@ -1250,11 +1229,11 @@ private void RefreshProposal(CrossingExchange ax, CrossingExchange bx, bool canA private void ShowTerm(TermRow term, string caption, CrossingExchange side, string note) { NativeElements.SetText(term.Caption, caption); - bool something = side.Total > 0; + bool something = side.Whole > 0; Sprite icon = something ? _items.IconOf(side.GoodId) : null; if (term.Icon.sprite != icon) term.Icon.sprite = icon; NativeElements.Show(term.Icon, icon != null); - NativeElements.SetText(term.What, AmountOf(side.Total, side.GoodId)); + NativeElements.SetText(term.What, AmountOf(side.Whole, side.GoodId)); term.What.style.color = something ? new StyleColor(StyleKeyword.Null) : new StyleColor(NativeElements.Muted); NativeElements.SetText(term.Note, note); NativeElements.Show(term.Note, !string.IsNullOrEmpty(note)); @@ -1597,8 +1576,8 @@ private void Propose() if (!myHalf) return; bool repeating = repeatToggle.value; TradeOfferForm.Verdict verdict = TradeOfferForm.Judge(giveItem, giveSide.Amount.value, getItem, getSide.Amount.value, - roundsBox.value, repeating, out int give, out int get, out int rounds, GiveAllowed(), GetAllowed()); - if (!TradeOfferForm.IsOffer(verdict) || !ExchangeTerms.AreValid(giveItem, give, getItem, get)) return; + repeating, out int give, out int get, out int rounds, GiveAllowed(), GetAllowed()); + if (!TradeOfferForm.IsOffer(verdict) || !ExchangeTerms.AreValidTerms(giveItem, give, getItem, get, repeating)) return; // The reserve counts only where its box is shown (more than one round, something given). int keep = 0; if (give > 0 && (repeating || rounds > 1) && (!TradeOfferForm.TryReadKeep(keepBox.value, out keep) || !ExchangeTerms.IsValidKeep(keep))) return; diff --git a/BeaverBuddies/Localizations/enUS_BeaverBuddie.csv b/BeaverBuddies/Localizations/enUS_BeaverBuddie.csv index 985231c..1e95ffa 100644 --- a/BeaverBuddies/Localizations/enUS_BeaverBuddie.csv +++ b/BeaverBuddies/Localizations/enUS_BeaverBuddie.csv @@ -243,21 +243,18 @@ BeaverBuddies.Colony.Trade.TheyHaveN,"{0} has {1}","" BeaverBuddies.Colony.Trade.ChooseTooltip,"Choose what to trade","" BeaverBuddies.Colony.Trade.StepLess,"-{0} (Shift+click: -{1})","" BeaverBuddies.Colony.Trade.StepMore,"+{0} (Shift+click: +{1})","" -BeaverBuddies.Colony.Trade.AmountTooltip,"How many each round: 0 to {0}. Type more for the whole trade: it's split into rounds.","" +BeaverBuddies.Colony.Trade.AmountTooltip,"How many in all: 0 to {0}. A Trading Post carries the trade in rounds for you.","" +BeaverBuddies.Colony.Trade.AmountTooltipRepeat,"How many each round: 0 to {0}.","" BeaverBuddies.Colony.Trade.RoundsCaption,"Rounds","" BeaverBuddies.Colony.Trade.RoundsNote,"up to {0} of each per round","" -BeaverBuddies.Colony.Trade.RoundsTooltip,"How many times the exchange runs: 1 to {0}. Each round crosses on its own.","" +BeaverBuddies.Colony.Trade.RoundsTooltip,"The rounds the trade takes: a Trading Post carries up to {0} of each a round.","" BeaverBuddies.Colony.Trade.RepeatToggle,"Repeat until cancelled","" BeaverBuddies.Colony.Trade.RepeatTooltip,"A standing deal: round after round, until both colonies agree to end it.","" BeaverBuddies.Colony.Trade.SummaryExchange,"{0} for {1}","" BeaverBuddies.Colony.Trade.SummaryGift,"Gift to {0}: {1}","" BeaverBuddies.Colony.Trade.SummaryRequest,"Request from {0}: {1}","" -BeaverBuddies.Colony.Trade.RoundsOnce,"Once.","" -BeaverBuddies.Colony.Trade.RoundsMany,"{0} rounds of {1}","" -BeaverBuddies.Colony.Trade.RoundsRepeat,"Repeating: {0} a round, until you both agree to stop","" -BeaverBuddies.Colony.Trade.ErrorAmount,"Each side gives a whole number, up to {0} in all over at most {1} rounds.","" -BeaverBuddies.Colony.Trade.ErrorRounds,"Rounds go from 1 to {0}.","" -BeaverBuddies.Colony.Trade.ErrorUneven,"These amounts don't split into equal rounds of up to {0} each. Change one amount a little.","" +BeaverBuddies.Colony.Trade.RoundsRepeatLine,"Every round, until you both agree to stop.","" +BeaverBuddies.Colony.Trade.ErrorAmount,"Each side gives a whole number, up to {0}.","" BeaverBuddies.Colony.Trade.ErrorNothing,"Set an amount above 0 on at least one side.","" BeaverBuddies.Colony.Trade.ErrorSame,"Choose two different goods.","" BeaverBuddies.Colony.Trade.ErrorNoItem,"Choose what to trade.","" @@ -323,12 +320,9 @@ BeaverBuddies.Colony.Trade.NothingInReturn,"nothing","" BeaverBuddies.Colony.Trade.HostFirst,"Trading works in a co-op game: host the game first (even alone).","" BeaverBuddies.Colony.Trade.Notice.Proposed,"{0} offers {1} for {2} at a Trading Post. Click here to answer.","" -BeaverBuddies.Colony.Trade.Notice.ProposedRounds,"{0} offers {1} for {2} in all, over {3} rounds, at a Trading Post. -Click here to answer.","" BeaverBuddies.Colony.Trade.Notice.ProposedRepeat,"{0} offers {1} for {2} every round, until you both stop, at a Trading Post. Click here to answer.","" BeaverBuddies.Colony.Trade.Notice.Accepted,"{0} accepted your exchange: {1} for {2}.","" -BeaverBuddies.Colony.Trade.Notice.AcceptedRounds,"{0} accepted your exchange: {1} for {2} in all, over {3} rounds.","" BeaverBuddies.Colony.Trade.Notice.AcceptedRepeat,"{0} accepted your exchange: {1} for {2} every round, until you both stop.","" BeaverBuddies.Colony.Trade.Notice.Declined,"{0} declined your exchange offer.","" BeaverBuddies.Colony.Trade.Notice.Withdrawn,"{0} withdrew their exchange offer.","" @@ -435,8 +429,6 @@ BeaverBuddies.Colony.Trade.KeepTooltip,"A reserve: your side is brought (or paid BeaverBuddies.Colony.Trade.KeepBoxTooltip,"0 to {0}.","" BeaverBuddies.Colony.Trade.ErrorKeep,"Keep at least goes from 0 to {0}.","" BeaverBuddies.Colony.Trade.SummaryKeep,"You keep at least {0} {1}","" -BeaverBuddies.Colony.Trade.SummarySplit,"Split into rounds: a Trading Post carries up to {2} of each a round.","" -BeaverBuddies.Colony.Trade.SummarySplitRepeat,"Each round is {0} for {1}: a Trading Post carries up to {2} of each a round.","" BeaverBuddies.Colony.Trade.DeclineTooltip,"Declines the offer. Its terms stay in your form, so you can change a number and offer back.","" BeaverBuddies.Colony.Trade.WithdrawTooltip,"Takes the offer back. Its terms stay in your form.","" BeaverBuddies.Colony.Trade.StatusYourReserve,"You keep {0} {1} back. Waiting for more.","" diff --git a/CLAUDE.md b/CLAUDE.md index d740bf5..7e0b317 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -146,7 +146,9 @@ Kyler, 2026-09-24: "simplicity and elegance is effective and desirable." Every c as in game. - The Trading Post demo must keep matching the mod (`Colonies/TradingPostFragment.cs`, `ExchangeTerms`, `TradeOfferForm`): a colony is named by its player (Player 1 = colony 1, Player 2 = colony 2); ledger stamp - `cycle-day` ("3-13"); 0–100 of an item per round, steps 10 / Shift 1 (beavers 1 / Shift 10); rounds 1–99. + `cycle-day` ("3-13"); the whole trade is typed, 0–9,900 a side (a repeating offer: each round's, 0–100), steps 10 / + Shift 1 (beavers 1 / Shift 10); the rounds are not chosen: one per 100 of the larger side, each side spread evenly + (`ExchangeTerms.RoundsFor`/`ShareOf`), the greyed Rounds box shows them, and offers say only the whole trade. - `docs/assets/release.js` is Timber Together's own variant of the timbermods release script (the other sites share one byte-identical copy, SHA-1 f771fa55…). This copy fills `data-release` / `data-release-href` from the most recently *published* pre-release, because GitHub's release list sorts tags as text. The HTML's static values are the diff --git a/README.md b/README.md index 5f759ca..cf5d3c1 100644 --- a/README.md +++ b/README.md @@ -113,10 +113,10 @@ the colonies window (**Y**), or after its player misses the host's limit, **Hand Build a **Trading Post** (District Management; 10 logs, no science) between your road and another colony's, one half's door on each road. It's the only place two colonies' roads meet, and it starts trading once both reach it. -1. **Offer.** Select your half. Choose what **You give** and **You get** and how many **Rounds** (up to 100 of each a round), or tick - **Repeat until cancelled**. Type more than 100 and that is the whole trade, split into equal rounds; **Rounds** is then ignored. - A side at 0 is a gift. **Keep at least** holds back a reserve so - a long deal never empties your stock. Then **Make offer**. +1. **Offer.** Select your half. Choose what **You give** and **You get**, as the whole trade (101 logs for 2 gears, say). + A post carries up to 100 of each a round, so the game spreads it over rounds; **Rounds** shows how many. Or tick + **Repeat until cancelled**, with each round's amounts. A side at 0 is a gift. **Keep at least** holds back a reserve + so a long deal never empties your stock. Then **Make offer**. 2. **They accept** on their half, or decline; a declined offer stays in your form, ready to adjust. The offer reaches them as a message that says the whole trade and stays until they answer or close it, with a chime. Clicking it takes them to the post. diff --git a/RuntimeChecks/RcTradingRuntimeChecks.cs b/RuntimeChecks/RcTradingRuntimeChecks.cs index 93e8fd6..6079de4 100644 --- a/RuntimeChecks/RcTradingRuntimeChecks.cs +++ b/RuntimeChecks/RcTradingRuntimeChecks.cs @@ -182,8 +182,8 @@ JsonNode Read(string path) Type rules = mod.GetType("BeaverBuddies.Factions.FactionRules", true)!; MethodInfo allows = Only(rules, "FactionAllows"); Type form = mod.GetType("BeaverBuddies.Colonies.TradeOfferForm", true)!; - // The form's Judge without the split flag (1.4.0-rc22 added an overload that also says whether it split). - MethodInfo judge = form.GetMethods(BindingFlags.Public | BindingFlags.Static).Single(m => m.Name == "Judge" && m.GetParameters().Length == 11); + // The form's Judge (1.4.0-rc31: the whole trade as typed, repeat, the amounts and rounds out, the factions' say). + MethodInfo judge = form.GetMethods(BindingFlags.Public | BindingFlags.Static).Single(m => m.Name == "Judge" && m.GetParameters().Length == 10); string science = (string)terms.GetField("Science")!.GetValue(null)!, beavers = (string)terms.GetField("Beavers")!.GetValue(null)!; int max = (int)terms.GetField("MaxAmount")!.GetValue(null)!; Need(max == 100, "a half's room for a good is no longer 100"); @@ -203,7 +203,7 @@ JsonNode Read(string path) if (allowed && !stores[receiver].Contains(type)) problems.Add($"{receiver} may receive {id} ({type}) but has nowhere to store it"); // The offer form offers exactly what may cross, 100 of it for one of something else. Func giveAllowed = item => (bool)allows.Invoke(null, new object?[] { item, receiverStores, giver, receiver, science, beavers })!; - object?[] args = { id, "100", "Log" == id ? "Plank" : "Log", "1", "1", false, 0, 0, 0, giveAllowed, null }; + object?[] args = { id, "100", "Log" == id ? "Plank" : "Log", "1", false, 0, 0, 0, giveAllowed, null }; string verdict = judge.Invoke(null, args)!.ToString()!; if (verdict != (allowed ? "Exchange" : "GiveNotAllowed")) problems.Add($"the form says {verdict} for 100 {id} from {giver} to {receiver}"); } diff --git a/StabilityTests/ColonyChecks.cs b/StabilityTests/ColonyChecks.cs index 85ba218..49479e9 100644 --- a/StabilityTests/ColonyChecks.cs +++ b/StabilityTests/ColonyChecks.cs @@ -877,6 +877,8 @@ static void Equal(T expected, T actual) => yield return ("Colony: an amount box holds a whole number from 0 to a whole exchange's worth, and empty means 0", () => { Equal(9900, TradeOfferForm.MaxTyped); + Equal(100, TradeOfferForm.MaxFor(repeat: true)); + Equal(9900, TradeOfferForm.MaxFor(repeat: false)); foreach (var (text, amount) in new[] { ("", 0), (" ", 0), (null, 0), ("0", 0), ("100", 100), (" 42 ", 42), ("050", 50), ("101", 101), ("9900", 9900) }) { Check(TradeOfferForm.TryReadAmount(text, out int read), $"[{text}] should read"); @@ -884,19 +886,12 @@ static void Equal(T expected, T actual) => } foreach (string text in new[] { "9901", "99999", "-5", "+5", "1,000", "1.5", "12a", "1e3", "٣" }) Check(!TradeOfferForm.TryReadAmount(text, out _), $"[{text}] should not read"); - foreach (var (text, rounds) in new[] { ("1", 1), (" 3 ", 3), ("99", 99), ("07", 7) }) - { - Check(TradeOfferForm.TryReadRounds(text, out int read), $"[{text}] rounds should read"); - Equal(rounds, read); - } - foreach (string text in new[] { "", "0", "100", "-1", "x", null }) - Check(!TradeOfferForm.TryReadRounds(text, out _), $"[{text}] rounds should not read"); }); - yield return ("Colony: the offer form says what an offer is, or what is wrong with it", () => + yield return ("Colony: the offer form says what an offer is, or what is wrong with it; amounts are never refused for their size", () => { - TradeOfferForm.Verdict Judge(string giveItem, string giveText, string getItem, string getText, string roundsText = "1", - bool repeat = false) => TradeOfferForm.Judge(giveItem, giveText, getItem, getText, roundsText, repeat, out _, out _, out _); + TradeOfferForm.Verdict Judge(string giveItem, string giveText, string getItem, string getText, bool repeat = false) => + TradeOfferForm.Judge(giveItem, giveText, getItem, getText, repeat, out _, out _, out _); Equal(TradeOfferForm.Verdict.Exchange, Judge("Log", "100", "Gear", "25")); Equal(TradeOfferForm.Verdict.Gift, Judge("Log", "30", "Gear", "0")); Equal(TradeOfferForm.Verdict.Gift, Judge("Log", "30", "Gear", "")); @@ -908,104 +903,75 @@ TradeOfferForm.Verdict Judge(string giveItem, string giveText, string getItem, s Equal(TradeOfferForm.Verdict.BadAmount, Judge("Log", "5", "Gear", "lots")); Equal(TradeOfferForm.Verdict.NoItem, Judge(null, "5", "Gear", "5")); Equal(TradeOfferForm.Verdict.Exchange, Judge(ExchangeTerms.Science, "100", ExchangeTerms.Beavers, "2")); - Equal(TradeOfferForm.Verdict.BadRounds, Judge("Log", "100", "Gear", "25", "0")); - Equal(TradeOfferForm.Verdict.BadRounds, Judge("Log", "100", "Gear", "25", "100")); - Equal(TradeOfferForm.Verdict.Exchange, Judge("Log", "100", "Gear", "25", "99")); - // A repeating offer ignores the rounds box. - Equal(TradeOfferForm.Verdict.Exchange, Judge("Log", "100", "Gear", "25", "", repeat: true)); - TradeOfferForm.Judge("Log", "100", "Gear", "25", "7", false, out _, out _, out int seven); - Equal(7, seven); - - // Whatever is typed, the form offers exactly what an exchange accepts: the numbers it read when a round - // carries them, else those split into rounds. + // Awkward numbers are offers too: the game spreads them over its rounds. + Equal(TradeOfferForm.Verdict.Exchange, Judge("Log", "101", "Gear", "2")); + Equal(TradeOfferForm.Verdict.Exchange, Judge("Log", "500", "Gear", "1")); + Equal(TradeOfferForm.Verdict.Gift, Judge("Log", "101", "Gear", "0")); + // A repeating offer's amounts are each round's (the form brings a larger one down to 100). + Equal(TradeOfferForm.Verdict.Exchange, Judge("Log", "100", "Gear", "25", repeat: true)); + Equal(TradeOfferForm.Verdict.BadAmount, Judge("Log", "101", "Gear", "25", repeat: true)); + TradeOfferForm.Judge("Log", "301", "Gear", "300", false, out int wg, out int wa, out int wr); + Equal(301, wg); Equal(300, wa); Equal(4, wr); + + // Whatever is typed, the form offers exactly what an exchange accepts, as typed, in RoundsFor rounds. var random = new Random(20260921); string[] items = { "Log", "Gear", ExchangeTerms.Science, ExchangeTerms.Beavers, null, "" }; string[] texts = { "", "0", "1", "10", "100", "101", "250", "9900", "9901", "-1", "x", " 7 " }; - string[] roundTexts = { "", "0", "1", "2", "50", "99", "100", "x", " 3 " }; for (int i = 0; i < 5000; i++) { string giveItem = items[random.Next(items.Length)], getItem = items[random.Next(items.Length)]; string giveText = random.Next(4) == 0 ? texts[random.Next(texts.Length)] : random.Next(0, random.Next(3) == 0 ? 1200 : 130).ToString(); string getText = random.Next(4) == 0 ? texts[random.Next(texts.Length)] : random.Next(0, random.Next(3) == 0 ? 1200 : 130).ToString(); - string roundsText = roundTexts[random.Next(roundTexts.Length)]; bool repeat = random.Next(3) == 0; - var verdict = TradeOfferForm.Judge(giveItem, giveText, getItem, getText, roundsText, repeat, out int give, out int get, out int rounds, out bool split); + var verdict = TradeOfferForm.Judge(giveItem, giveText, getItem, getText, repeat, out int give, out int get, out int rounds); bool read = TradeOfferForm.TryReadAmount(giveText, out int g) & TradeOfferForm.TryReadAmount(getText, out int a); - bool roundsRead = TradeOfferForm.TryReadRounds(roundsText, out int r); - bool fits = g <= ExchangeTerms.MaxAmount && a <= ExchangeTerms.MaxAmount; - if (TradeOfferForm.IsOffer(verdict)) - { - Check(ExchangeTerms.AreValid(giveItem, give, getItem, get) && (repeat || ExchangeTerms.AreValidRounds(rounds)), - $"{giveText} {giveItem} for {getText} {getItem} x[{roundsText}]: the form offers {give} for {get} x{rounds}, which an exchange refuses"); - Equal(!fits, split); - if (fits) - { - Equal(g, give); Equal(a, get); - Equal(repeat ? 1 : r, rounds); - } - } - // Where a round carries both amounts the form agrees with an exchange exactly, as before. - if (read && fits) - { - bool valid = ExchangeTerms.AreValid(giveItem, g, getItem, a) && (repeat || roundsRead); - Check(TradeOfferForm.IsOffer(verdict) == valid, - $"{giveText} {giveItem} for {getText} {getItem} x[{roundsText}]{(repeat ? " repeating" : "")}: the form says {verdict}, an exchange says {(valid ? "valid" : "not valid")}"); - } + bool valid = read && ExchangeTerms.AreValidTerms(giveItem, g, getItem, a, repeat); + Check(TradeOfferForm.IsOffer(verdict) == valid, + $"{giveText} {giveItem} for {getText} {getItem}{(repeat ? " repeating" : "")}: the form says {verdict}, an exchange says {(valid ? "valid" : "not valid")}"); + if (!TradeOfferForm.IsOffer(verdict)) continue; + Equal(g, give); Equal(a, get); + Equal(repeat ? 1 : ExchangeTerms.RoundsFor(g, a), rounds); } }); - yield return ("Colony: more than a round carries is split into the fewest equal rounds, never rounded", () => - { - TradeOfferForm.Verdict Judge(string give, string get, string rounds, bool repeat, out int g, out int a, out int r, out bool split) => - TradeOfferForm.Judge("Log", give, "Bread", get, rounds, repeat, out g, out a, out r, out split); - // 300 logs for 300 bread: three rounds of 100 for 100. - Equal(TradeOfferForm.Verdict.Exchange, Judge("300", "300", "1", false, out int g1, out int a1, out int r1, out bool s1)); - Equal(100, g1); Equal(100, a1); Equal(3, r1); Check(s1, "300 for 300 is not split"); - // Not a multiple of 100: the fewest equal rounds that carry exactly the whole. - Judge("250", "130", "1", false, out int g2, out int a2, out int r2, out _); - Equal(5, r2); Equal(50, g2); Equal(26, a2); - // No equal rounds carry 1000 for 5 within a round's 100: refused, not rounded up to 10. - Equal(TradeOfferForm.Verdict.Uneven, Judge("1000", "5", "1", false, out _, out _, out _, out _)); - // A gift stays a gift. - Equal(TradeOfferForm.Verdict.Gift, Judge("450", "0", "1", false, out int g4, out int a4, out int r4, out _)); - Equal(90, g4); Equal(0, a4); Equal(5, r4); - // More than a round carries is the whole trade: the rounds box is not read (500 Bread is 500 in all, never 500 x 5). - Judge("150", "50", "2", false, out int g5, out int a5, out int r5, out _); - Equal(2, r5); Equal(75, g5); Equal(25, a5); - Equal(TradeOfferForm.Verdict.Request, Judge("0", "500", "5", false, out int g9, out int a9, out int r9, out _)); - Equal(0, g9); Equal(100, a9); Equal(5, r9); - Equal(TradeOfferForm.Verdict.Request, Judge("0", "500", "", false, out _, out _, out int r10, out _)); - Equal(5, r10); - // What fits a round is left as typed. - Judge("100", "25", "4", false, out int g6, out int a6, out int r6, out bool s6); - Equal(100, g6); Equal(25, a6); Equal(4, r6); Check(!s6, "an offer that fits a round was split"); - // A repeating offer keeps repeating, its round cut to fit. - Judge("300", "150", "", true, out int g7, out int a7, out int r7, out _); - Equal(100, g7); Equal(50, a7); Equal(1, r7); - // The most an amount box takes fills the most rounds, whatever the rounds box says; more is refused. - Equal(TradeOfferForm.Verdict.Exchange, Judge("9900", "99", "2", false, out int g8, out _, out int r8, out _)); - Equal(100, g8); Equal(99, r8); - Equal(TradeOfferForm.Verdict.BadAmount, Judge("9901", "10", "1", false, out _, out _, out _, out _)); - // Every split carries exactly the whole, in the fewest equal rounds, each within what a post holds; amounts - // that no number of equal rounds divides are refused, never rounded (500 for 1 is not 5 beavers). - for (int give = 0; give <= 2000; give += 37) - for (int get = 0; get <= 2000; get += 53) + yield return ("Colony: a whole trade takes one round per 100 of its larger side, spread evenly, adding up to exactly what was typed", () => + { + Equal(1, ExchangeTerms.RoundsFor(0, 0)); + Equal(1, ExchangeTerms.RoundsFor(100, 25)); + Equal(2, ExchangeTerms.RoundsFor(101, 2)); + Equal(3, ExchangeTerms.RoundsFor(300, 300)); + Equal(4, ExchangeTerms.RoundsFor(301, 300)); + Equal(5, ExchangeTerms.RoundsFor(1, 500)); + Equal(99, ExchangeTerms.RoundsFor(9900, 9900)); + // 101 Logs for 2 Gears: 51 then 50 Logs, 1 and 1 Gear. 500 Logs for 1 Gear: the Gear in the first round. + Equal(51, ExchangeTerms.ShareOf(101, 2, 0)); Equal(50, ExchangeTerms.ShareOf(101, 2, 1)); + Equal(1, ExchangeTerms.ShareOf(2, 2, 0)); Equal(1, ExchangeTerms.ShareOf(2, 2, 1)); + Equal(1, ExchangeTerms.ShareOf(1, 5, 0)); Equal(0, ExchangeTerms.ShareOf(1, 5, 4)); + Equal(0, ExchangeTerms.ShareOf(10, 2, 2)); + for (int give = 0; give <= ExchangeTerms.MaxWhole; give += 37) + foreach (int get in new[] { 0, 1, 2, 7, 99, 100, 101, 999, 4321, 9900 }) { - if (give <= ExchangeTerms.MaxAmount && get <= ExchangeTerms.MaxAmount) continue; - int needed = (Math.Max(give, get) + 99) / 100; - int fewest = Enumerable.Range(needed, Math.Max(0, ExchangeTerms.MaxRounds - needed + 1)).FirstOrDefault(k => give % k == 0 && get % k == 0); - bool splits = TradeOfferForm.Split(give, get, 1, false, out int eg, out int ea, out int n); - Equal(fewest != 0, splits); - if (!splits) continue; - Equal(fewest, n); - Check(eg <= ExchangeTerms.MaxAmount && ea <= ExchangeTerms.MaxAmount && eg * n == give && ea * n == get, - $"{give} for {get}: {eg}x{n} for {ea}x{n} is not the whole"); + int rounds = ExchangeTerms.RoundsFor(give, get); + Check(rounds >= 1 && rounds <= ExchangeTerms.MaxRounds, $"{give} for {get}: {rounds} rounds"); + int sumGive = 0, sumGet = 0; + for (int r = 0; r < rounds; r++) + { + int eg = ExchangeTerms.ShareOf(give, rounds, r), ea = ExchangeTerms.ShareOf(get, rounds, r); + Check(eg >= 0 && eg <= ExchangeTerms.MaxAmount && ea >= 0 && ea <= ExchangeTerms.MaxAmount, $"{give} for {get}: round {r} is {eg} for {ea}"); + int before = r == 0 ? eg : ExchangeTerms.ShareOf(give, rounds, r - 1); + Check(before - eg == 0 || before - eg == 1, $"{give} over {rounds}: not even"); + sumGive += eg; sumGet += ea; + } + Equal(give, sumGive); Equal(get, sumGet); } - Check(!TradeOfferForm.Split(500, 1, 1, false, out _, out _, out _), "500 for 1 was rounded"); - Equal(TradeOfferForm.Verdict.Uneven, Judge("500", "1", "", false, out _, out _, out _, out _)); - Equal(TradeOfferForm.Verdict.Uneven, Judge("101", "0", "", false, out _, out _, out _, out _)); - Judge("250", "50", "", false, out int g11, out int a11, out int r11, out _); - Equal(50, g11); Equal(10, a11); Equal(5, r11); + // An exchange's own terms: whole amounts need their rounds; a repeating one's are each round's. + Check(ExchangeTerms.AreValidTerms("Log", 101, "Gear", 2, repeat: false)); + Check(!ExchangeTerms.AreValidTerms("Log", 101, "Gear", 2, repeat: true)); + Check(!ExchangeTerms.AreValidTerms("Log", 9901, "Gear", 2, repeat: false)); + Check(ExchangeTerms.TryDecodeTerms(ExchangeTerms.EncodeTerms("Log", 101, "Gear", 2, 2, false, 0), out _, out int dg, out _, out int da, out int dr, out _, out _) + && dg == 101 && da == 2 && dr == 2, "whole terms are not remembered"); + Check(!ExchangeTerms.TryDecodeTerms(ExchangeTerms.EncodeTerms("Log", 101, "Gear", 2, 5, false, 0), out _, out _, out _, out _, out _, out _, out _), + "terms with rounds that don't follow from the amounts were accepted"); }); yield return ("Colony: − and + go to the next whole step and stay within their box's range", () => @@ -1015,28 +981,22 @@ TradeOfferForm.Verdict Judge(string give, string get, string rounds, bool repeat Equal(10, TradeOfferForm.Step(ExchangeTerms.Science, shift: false)); Equal(1, TradeOfferForm.Step(ExchangeTerms.Beavers, shift: false)); Equal(10, TradeOfferForm.Step(ExchangeTerms.Beavers, shift: true)); - Equal(1, TradeOfferForm.RoundsStep(false)); - Equal(10, TradeOfferForm.RoundsStep(true)); - Equal(100, TradeOfferForm.Stepped(95, 10, up: true)); - Equal(90, TradeOfferForm.Stepped(95, 10, up: false)); - Check(TradeOfferForm.Stepped(100, 10, up: true) == 100, "no more than a half holds"); - // An amount typed above a round's worth steps on from there. - Equal(310, TradeOfferForm.Stepped(300, 10, up: true)); - Equal(290, TradeOfferForm.Stepped(300, 10, up: false)); - Equal(90, TradeOfferForm.Stepped(100, 10, up: false)); - Equal(0, TradeOfferForm.Stepped(0, 10, up: false)); - Equal(1, TradeOfferForm.Stepped(0, 1, up: true)); - Equal(99, TradeOfferForm.Stepped(98, 1, up: true)); - // Rounds: from 1 to 99. - Equal(1, TradeOfferForm.Stepped(1, 1, up: false, 1, ExchangeTerms.MaxRounds)); - Equal(10, TradeOfferForm.Stepped(1, 10, up: true, 1, ExchangeTerms.MaxRounds)); - Equal(99, TradeOfferForm.Stepped(95, 10, up: true, 1, ExchangeTerms.MaxRounds)); - Equal(1, TradeOfferForm.Stepped(5, 10, up: false, 1, ExchangeTerms.MaxRounds)); + Equal(100, TradeOfferForm.Stepped(95, 10, up: true, repeat: false)); + Equal(90, TradeOfferForm.Stepped(95, 10, up: false, repeat: false)); + // A whole trade steps on past a round's worth; a repeating one's round stops at 100. + Equal(110, TradeOfferForm.Stepped(100, 10, up: true, repeat: false)); + Check(TradeOfferForm.Stepped(100, 10, up: true, repeat: true) == 100, "a repeating round went over what a post carries"); + Equal(310, TradeOfferForm.Stepped(300, 10, up: true, repeat: false)); + Equal(290, TradeOfferForm.Stepped(300, 10, up: false, repeat: false)); + Equal(9900, TradeOfferForm.Stepped(9900, 10, up: true, repeat: false)); + Equal(0, TradeOfferForm.Stepped(0, 10, up: false, repeat: false)); + Equal(1, TradeOfferForm.Stepped(0, 1, up: true, repeat: false)); + Equal(99, TradeOfferForm.Stepped(98, 1, up: true, repeat: true)); for (int amount = 0; amount <= ExchangeTerms.MaxAmount; amount += 3) { foreach (int step in new[] { 1, 10 }) { - int up = TradeOfferForm.Stepped(amount, step, up: true), down = TradeOfferForm.Stepped(amount, step, up: false); + int up = TradeOfferForm.Stepped(amount, step, up: true, repeat: true), down = TradeOfferForm.Stepped(amount, step, up: false, repeat: true); Check(up > amount || amount == ExchangeTerms.MaxAmount, $"+ from {amount} by {step} gave {up}"); Check(down < amount || amount == 0, $"- from {amount} by {step} gave {down}"); Check(up - amount <= step && amount - down <= step, $"{amount} by {step} jumped to {down} or {up}"); diff --git a/StabilityTests/FactionChecks.cs b/StabilityTests/FactionChecks.cs index e3b33f8..3f76078 100644 --- a/StabilityTests/FactionChecks.cs +++ b/StabilityTests/FactionChecks.cs @@ -139,15 +139,15 @@ bool Allows(string item, string from, string to) => Func toFolktails = item => FactionRules.FactionAllows(item, g => goods.Has(Folktails, g), IronTeeth, Folktails, ExchangeTerms.Science, ExchangeTerms.Beavers); TradeOfferForm.Verdict Judge(string give, string get) => - TradeOfferForm.Judge(give, "10", get, "10", "1", false, out _, out _, out _, toIronTeeth, toFolktails); + TradeOfferForm.Judge(give, "10", get, "10", false, out _, out _, out _, toIronTeeth, toFolktails); Equal(TradeOfferForm.Verdict.Exchange, Judge("Log", "Plank")); Equal(TradeOfferForm.Verdict.GiveNotAllowed, Judge("Carrot", "Log")); Equal(TradeOfferForm.Verdict.GetNotAllowed, Judge("Log", "Corn")); Equal(TradeOfferForm.Verdict.GiveNotAllowed, Judge(ExchangeTerms.Beavers, "Log")); Equal(TradeOfferForm.Verdict.Exchange, Judge(ExchangeTerms.Science, "Log")); // A side of nothing is not judged, and without the predicates everything may (as before mixed factions). - Equal(TradeOfferForm.Verdict.Request, TradeOfferForm.Judge("Carrot", "0", "Log", "5", "1", false, out _, out _, out _, toIronTeeth, toFolktails)); - Equal(TradeOfferForm.Verdict.Exchange, TradeOfferForm.Judge("Carrot", "10", "Corn", "10", "1", false, out _, out _, out _)); + Equal(TradeOfferForm.Verdict.Request, TradeOfferForm.Judge("Carrot", "0", "Log", "5", false, out _, out _, out _, toIronTeeth, toFolktails)); + Equal(TradeOfferForm.Verdict.Exchange, TradeOfferForm.Judge("Carrot", "10", "Corn", "10", false, out _, out _, out _)); Check(!TradeOfferForm.IsOffer(TradeOfferForm.Verdict.GiveNotAllowed) && !TradeOfferForm.IsOffer(TradeOfferForm.Verdict.GetNotAllowed)); }); diff --git a/StabilityTests/FeatureChecks.cs b/StabilityTests/FeatureChecks.cs index d2dec9c..fe3c56c 100644 --- a/StabilityTests/FeatureChecks.cs +++ b/StabilityTests/FeatureChecks.cs @@ -63,9 +63,9 @@ static void Equal(T expected, T actual) => yield return ("Exchange: an exchange's terms survive as one string, and a broken one is refused", () => { - string text = ExchangeTerms.EncodeTerms("Log", 100, "Gear", 25, 4, false, 200); + string text = ExchangeTerms.EncodeTerms("Log", 400, "Gear", 100, 4, false, 200); Check(ExchangeTerms.TryDecodeTerms(text, out string give, out int giveAmount, out string get, out int getAmount, out int rounds, out bool repeat, out int keep)); - Equal("Log", give); Equal(100, giveAmount); Equal("Gear", get); Equal(25, getAmount); Equal(4, rounds); Check(!repeat); Equal(200, keep); + Equal("Log", give); Equal(400, giveAmount); Equal("Gear", get); Equal(100, getAmount); Equal(4, rounds); Check(!repeat); Equal(200, keep); // A gift: the empty side has no good. Check(ExchangeTerms.TryDecodeTerms(ExchangeTerms.EncodeTerms("Log", 100, null, 0, 1, true, 0), out give, out giveAmount, out get, out getAmount, out rounds, out repeat, out keep)); Check(get == null && getAmount == 0 && repeat); diff --git a/StabilityTests/Rc15Checks.cs b/StabilityTests/Rc15Checks.cs index ea27ac3..cab96c2 100644 --- a/StabilityTests/Rc15Checks.cs +++ b/StabilityTests/Rc15Checks.cs @@ -133,7 +133,7 @@ static string Csv(string key) { Check(Csv("BeaverBuddies.Colony.Trade.Notice.Cancelled") == "The exchange between {0} and {1} was cancelled. Any goods already brought to the Trading Post go back to the colony that brought them.", "the cancelled exchange's message changed: " + Csv("BeaverBuddies.Colony.Trade.Notice.Cancelled")); - Check(new[] { "Proposed", "ProposedRounds", "ProposedRepeat", "CancelAsked" }.All(key => Csv("BeaverBuddies.Colony.Trade.Notice." + key).EndsWith(".\nClick here to answer.")), + Check(new[] { "Proposed", "ProposedRepeat", "CancelAsked" }.All(key => Csv("BeaverBuddies.Colony.Trade.Notice." + key).EndsWith(".\nClick here to answer.")), "the messages that stay no longer say, on a line of its own, that a click answers them"); foreach (string key in new[] { "Notice.Cancelled", "AskCancelTooltip", "AgreeCancelTooltip", "EndExchangeTooltip", "PausedCancel" }) { diff --git a/StabilityTests/Rc22Checks.cs b/StabilityTests/Rc22Checks.cs index 2886ad2..3acc2cf 100644 --- a/StabilityTests/Rc22Checks.cs +++ b/StabilityTests/Rc22Checks.cs @@ -48,12 +48,14 @@ static string Csv(string key) { string exchange = Source("BeaverBuddies", "Colonies", "TradingPostExchange.cs"); string accept = Body(exchange, "public void Accept(DistrictCrossing half,"); - Check(accept.Contains("\"BeaverBuddies.Colony.Trade.Notice.AcceptedRounds\"") && accept.Contains("chime: true"), "an accepted offer no longer chimes, or no longer says every round"); + Check(accept.Contains("\"BeaverBuddies.Colony.Trade.Notice.Accepted\"") && accept.Contains("theirs.Whole") && accept.Contains("chime: true"), + "an accepted offer no longer chimes, or no longer says the whole trade"); Check(Body(exchange, "private void Tell(").Contains("if (chime) TradeNotices.Instance?.ChimeSoon();"), "Tell no longer chimes when asked"); - Check(Body(exchange, "public void Propose(DistrictCrossing half,").Contains("\"BeaverBuddies.Colony.Trade.Notice.ProposedRounds\""), "an offer's message says one round only"); - Check(Body(exchange, "private string Whole(").Contains("Amount(giveAmount * rounds, giveGood)"), "the whole exchange is not every round's goods"); - Check(Csv("BeaverBuddies.Colony.Trade.Notice.ProposedRounds").Contains("in all, over {3} rounds") - && Csv("BeaverBuddies.Colony.Trade.Notice.AcceptedRounds").Contains("in all, over {3} rounds"), "the rounds' messages don't say the whole"); + // rc31: an offer's messages say the whole trade as typed ("101 Logs for 2 Gears"), never its rounds. + Check(Body(exchange, "public void Propose(DistrictCrossing half,").Contains("\"BeaverBuddies.Colony.Trade.Notice.Proposed\""), "an offer has no message"); + Check(Body(exchange, "private string Whole(").Contains("Amount(giveAmount, giveGood), Amount(getAmount, getGood)"), "the message is not the whole trade"); + Check(!exchange.Contains("Notice.ProposedRounds") && !exchange.Contains("Notice.AcceptedRounds") && !Csv("BeaverBuddies.Colony.Trade.Notice.Accepted").Contains("rounds"), + "a message still names the rounds"); // The chime is played on the next frame, never inside the action. string notices = Source("BeaverBuddies", "Colonies", "TradeNotices.cs"); Check(Body(notices, "public void UpdateSingleton()").Contains("if (posted.Count == 0 && !chimePending) return;"), "a chime asked for is never played"); @@ -137,7 +139,7 @@ static string Csv(string key) yield return ("The colonies window says each exchange in three lines: the whole deal, each side's round, what it waits on", () => { string describe = Body(Source("BeaverBuddies", "Colonies", "TradeOverviewPanel.cs"), "private void Describe("); - Check(describe.Contains("mine.Total * rounds") && describe.Contains("theirs.Total * rounds"), "the first line counts one round, not the whole deal"); + Check(describe.Contains("exchanges.Amount(mine.Whole, mine.GoodId)") && describe.Contains("exchanges.Amount(theirs.Whole, theirs.GoodId)"), "the first line is not the whole deal"); Check(describe.Contains("deal + \"\\n\" + progress"), "the deal and the sides are not on lines of their own"); Check(describe.Contains("string.Format(T(dealKey), get, give)"), "an offer made to you names your goods first"); Check(Csv("BeaverBuddies.Colony.Overview.Progress") == "Your side: {0}. Their side: {1}.", "the sides' line changed"); diff --git a/StabilityTests/RcTradingChecks.cs b/StabilityTests/RcTradingChecks.cs index d765e8d..d1b104e 100644 --- a/StabilityTests/RcTradingChecks.cs +++ b/StabilityTests/RcTradingChecks.cs @@ -205,9 +205,9 @@ static string Body(string text, string signature) foreach (string get in goods) { if (give == get) continue; - string terms = ExchangeTerms.EncodeTerms(give, 100, get, 7, 12, false, 250); + string terms = ExchangeTerms.EncodeTerms(give, 1200, get, 7, 12, false, 250); Check(ExchangeTerms.TryDecodeTerms(terms, out string g1, out int a1, out string g2, out int a2, out int r, out bool rep, out int k)); - Check(g1 == give && a1 == 100 && g2 == get && a2 == 7 && r == 12 && !rep && k == 250, terms); + Check(g1 == give && a1 == 1200 && g2 == get && a2 == 7 && r == 12 && !rep && k == 250, terms); } }); @@ -234,14 +234,15 @@ static string Body(string text, string signature) sealed class Side { - public int State, Serial, Total, Held, Rounds, Done, Keep, Colony = -1; + // Total: this round's share of Whole (the whole exchange, as offered; a repeating one's: each round's). + public int State, Serial, Total, Whole, Held, Rounds, Done, Keep, Colony = -1; public bool ProposedHere, Repeat, CancelAsked; public string Good, LastTerms; public readonly List Ledger = new List(); public bool IsOpen => State != 0; public bool IsActive => State == 2; public bool GivesGoods => Total > 0 && Good != null && !ExchangeTerms.IsSpecial(Good); - public void Clear() { State = 0; ProposedHere = Repeat = CancelAsked = false; Good = null; Total = Held = Rounds = Done = Keep = 0; Colony = -1; } + public void Clear() { State = 0; ProposedHere = Repeat = CancelAsked = false; Good = null; Total = Whole = Held = Rounds = Done = Keep = 0; Colony = -1; } } sealed class Half @@ -409,14 +410,18 @@ static int CheckPost(World w, Random random) int aTotal = mine.Total, bTotal = theirs.Total, aHeld = mine.Held, bHeld = theirs.Held; mine.Done++; mine.Held = 0; theirs.Done++; theirs.Held = 0; + // The next round's share of the whole, as CrossingExchange.Crossed sets it. + foreach (Side side in new[] { mine, theirs }) + if (!side.Repeat && side.Done < side.Rounds) side.Total = ExchangeTerms.ShareOf(side.Whole, side.Rounds, side.Done); MoveGoods(half, partner, aGood, aHeld); MoveGoods(partner, half, bGood, bHeld); aTotal = MoveSpecial(w, half, partner, aGood, aTotal, movableHere); bTotal = MoveSpecial(w, partner, half, bGood, bTotal, movableThere); if (aTotal > 0) { w.Totals.Record(half.Owner, partner.Owner, aGood, aTotal); Add2(w.Crossed, (half.Owner, partner.Owner, aGood), aTotal); } if (bTotal > 0) { w.Totals.Record(partner.Owner, half.Owner, bGood, bTotal); Add2(w.Crossed, (partner.Owner, half.Owner, bGood), bTotal); } - Record(mine, new TradeRecord(1, 1, aGood, aTotal, bGood, bTotal)); - Record(theirs, new TradeRecord(1, 1, bGood, bTotal, aGood, aTotal)); + string aGave = ExchangeTerms.GoodOf(aGood, aTotal), bGave = ExchangeTerms.GoodOf(bGood, bTotal); + Record(mine, new TradeRecord(1, 1, aGave, aTotal, bGave, bTotal)); + Record(theirs, new TradeRecord(1, 1, bGave, bTotal, aGave, aTotal)); if (!ExchangeTerms.HasAnotherRound(mine.Rounds, mine.Done, mine.Repeat)) { mine.Clear(); theirs.Clear(); } return 1; } @@ -465,12 +470,14 @@ static void Propose(World w, Half half, Random random) if (!w.Trading || half.X.IsOpen || partner.X.IsOpen) return; string[] items = Goods.Concat(new[] { ExchangeTerms.Science, ExchangeTerms.Beavers }).ToArray(); string give = items[random.Next(items.Length)], get = items[random.Next(items.Length)]; - int giveAmount = give == ExchangeTerms.Beavers ? random.Next(0, 4) : random.Next(0, 101); - int getAmount = get == ExchangeTerms.Beavers ? random.Next(0, 4) : random.Next(0, 101); - int rounds = random.Next(1, 6); + // A whole trade as typed (up to a few rounds' worth, awkward numbers included), or a repeating one's round. bool repeat = random.Next(5) == 0; + int most = repeat ? ExchangeTerms.MaxAmount : 250; + int giveAmount = give == ExchangeTerms.Beavers ? random.Next(0, 4) : random.Next(0, most + 1); + int getAmount = get == ExchangeTerms.Beavers ? random.Next(0, 4) : random.Next(0, most + 1); + int rounds = repeat ? 1 : ExchangeTerms.RoundsFor(giveAmount, getAmount); int keep = random.Next(5) == 0 ? random.Next(0, 300) : 0; - if (!ExchangeTerms.AreValid(give, giveAmount, get, getAmount) || !ExchangeTerms.AreValidRounds(rounds) || !ExchangeTerms.IsValidKeep(keep)) return; + if (!ExchangeTerms.AreValidTerms(give, giveAmount, get, getAmount, repeat) || !ExchangeTerms.IsValidKeep(keep)) return; int serial = Math.Max(half.X.Serial, partner.X.Serial) + 1; Set(half.X, serial, true, give, giveAmount, rounds, repeat, half.Owner, keep); Set(partner.X, serial, false, get, getAmount, rounds, repeat, partner.Owner, 0); @@ -478,10 +485,11 @@ static void Propose(World w, Half half, Random random) partner.X.LastTerms = ExchangeTerms.EncodeTerms(get, getAmount, give, giveAmount, rounds, repeat, 0); } - static void Set(Side side, int serial, bool here, string good, int total, int rounds, bool repeat, int colony, int keep) + static void Set(Side side, int serial, bool here, string good, int whole, int rounds, bool repeat, int colony, int keep) { - side.Serial = serial; side.State = 1; side.ProposedHere = here; side.Good = ExchangeTerms.GoodOf(good, total); side.Total = total; + side.Serial = serial; side.State = 1; side.ProposedHere = here; side.Good = ExchangeTerms.GoodOf(good, whole); side.Whole = whole; side.Held = 0; side.Repeat = repeat; side.Rounds = repeat ? 1 : rounds; side.Done = 0; side.CancelAsked = false; side.Colony = colony; + side.Total = repeat ? whole : ExchangeTerms.ShareOf(whole, side.Rounds, 0); side.Keep = keep; } diff --git a/TWO-COLONIES.md b/TWO-COLONIES.md index 5414625..b267f44 100644 --- a/TWO-COLONIES.md +++ b/TWO-COLONIES.md @@ -164,13 +164,15 @@ colony's road. Until then its panel says *Not trading yet*. isn't a store: its halves hold goods only for the round under way. (The District Crossing stays the game's own, for your own districts.) -An **exchange** is "this many of one thing for that many of another, so many times": for example *100 logs for 25 -gears, 4 rounds*. You trade from **your half**, the one your roads reach. - -1. **Offer.** Select your half. Set **You give** and **You get**: click an item for the goods grid, and set the amount - from 0 to 100 (**−**/**+** by 10, Shift by 1; beavers by 1). Set **Rounds** (1 to 99), or tick **Repeat until - cancelled**. A side at 0 is a gift, or a request for help. For more than one round, **Keep at least** holds back a - reserve so a long deal never empties your stock. Then **Make offer**. +An **exchange** is "this many of one thing for that many of another": for example *400 logs for 100 gears*. You +trade from **your half**, the one your roads reach. + +1. **Offer.** Select your half. Set **You give** and **You get**: click an item for the goods grid, and type the whole + trade, up to 9,900 each (**−**/**+** by 10, Shift by 1; beavers by 1). A post carries up to 100 of each a round, so + the game takes one round per 100 of the larger side; the greyed **Rounds** box shows how many. Or tick **Repeat + until cancelled**: the amounts are then each round's, up to 100. A side at 0 is a gift, or a request for help. For + more than one round, **Keep at least** holds back a reserve so a long deal never empties your stock. Then + **Make offer**. 2. **Answer.** The offer reaches the other player as a message under the top bar, with a chime. It stays until they click it: a click takes them to their half of the post, and its **×** just closes it. They choose **Accept** or **Decline**. Until then you can **Withdraw offer**. A declined or withdrawn offer stays in the form, ready to change. @@ -206,9 +208,8 @@ see them there, under the header of a post you share, and in the goods grid when - One exchange at a time per post; build more posts for more. - A half holds up to 100 of a good for the round under way. The next round waits until the last one's goods have been hauled away, so staff both halves and keep storage room. -- Type more than 100 in the form (300 for 300, say) and that's the whole trade: it's split into the fewest equal - rounds that carry exactly it (250 for 50 is 5 rounds of 50 for 10), and the Rounds box shows them. Amounts that - don't split into equal rounds (500 for 1) are refused. The offer's message says the whole trade. +- What you type is exactly what crosses, however awkward: 101 logs for 2 gears goes as 51 logs for 1 gear, then 50 + for 1. Offers and messages say the whole trade; the ledger shows each round as it crossed. - Heavy goods take many trips: give busy posts more workers (up to 10). - Either of its two colonies may remove a post; no one else can. Its halves are placed as one. diff --git a/docs/assets/trade-demo.js b/docs/assets/trade-demo.js index b9a31c6..365fd34 100644 --- a/docs/assets/trade-demo.js +++ b/docs/assets/trade-demo.js @@ -13,16 +13,17 @@ var SCIENCE = 'science', BEAVERS = 'beaver'; var GOODS = [ - { id: 'logs', name: 'Logs', icon: 'logs', plural: 'Logs' }, - { id: 'gear', name: 'Gears', icon: 'gear', plural: 'Gears' }, - { id: 'berries', name: 'Berries', icon: 'berries', plural: 'Berries' }, - { id: 'carrot', name: 'Carrots', icon: 'carrot', plural: 'Carrots' }, + { id: 'logs', name: 'Logs', icon: 'logs', plural: 'Logs', one: 'Log' }, + { id: 'gear', name: 'Gears', icon: 'gear', plural: 'Gears', one: 'Gear' }, + { id: 'berries', name: 'Berries', icon: 'berries', plural: 'Berries', one: 'Berries' }, + { id: 'carrot', name: 'Carrots', icon: 'carrot', plural: 'Carrots', one: 'Carrot' }, { id: SCIENCE, name: 'Science', icon: 'science', plural: 'Science', special: true }, { id: BEAVERS, name: 'Beavers', icon: 'beaver', plural: 'Beavers', special: true } ]; function good(id) { for (var i = 0; i < GOODS.length; i++) if (GOODS[i].id === id) return GOODS[i]; return null; } function icon(id, size) { var g = good(id); return ''; } - function nameOf(id, n) { var g = good(id); if (id === BEAVERS) return n === 1 ? 'Beaver' : 'Beavers'; return g.plural; } + // The game's singular for one (the mod's GoodName), else the plural. + function nameOf(id, n) { var g = good(id); if (id === BEAVERS) return n === 1 ? 'Beaver' : 'Beavers'; return n === 1 && g.one ? g.one : g.plural; } function amountOf(n, id) { return n + ' ' + nameOf(id, n); } // The panel names a colony by its player (the seat table), as the mod does; 'Colony N' only for an unclaimed one. @@ -41,8 +42,8 @@ { logs: 30, gear: 61, berries: 15, carrot: 140, science: 140, beaver: 9 } ], workers: [2, 2], - draft: { give: 'logs', get: 'gear', giveAmount: 100, getAmount: 25, rounds: 4, repeat: false }, - exchange: null, // { by, side: [{good,total,held}], rounds, repeat, done, state: proposed|active, cancelAsked: [b,b], serial } + draft: { give: 'logs', get: 'gear', giveAmount: 400, getAmount: 100, repeat: false }, + exchange: null, // { by, side: [{good,whole,total,held}], rounds, repeat, done, state: proposed|active, cancelAsked: [b,b], serial } ledger: [[], []], // per colony: {cycle, day, gave, gaveN, got, gotN} totals: { '0>1': {}, '1>0': {} }, cycle: 3, day: 12, dayTicks: 0, @@ -58,30 +59,19 @@ function judge(d) { if (!d.give || !d.get) return { verdict: 'noItem' }; if (d.give === d.get) return { verdict: 'same' }; - var give = d.giveAmount, get = d.getAmount; - if (isNaN(give) || isNaN(get) || give < 0 || get < 0 || give > MAX_TYPED || get > MAX_TYPED) return { verdict: 'badAmount' }; - // More than a round carries is the whole trade, and the rounds box is not read, as TradeOfferForm.Judge does. - var whole = give > MAX_AMOUNT || get > MAX_AMOUNT; - if (!d.repeat && !whole && (isNaN(d.rounds) || d.rounds < 1 || d.rounds > MAX_ROUNDS)) return { verdict: 'badRounds' }; + // The whole trade as typed (a repeating one's: each round's, up to 100). Never refused for its size. + var give = d.giveAmount, get = d.getAmount, most = d.repeat ? MAX_AMOUNT : MAX_TYPED; + if (isNaN(give) || isNaN(get) || give < 0 || get < 0 || give > most || get > most) return { verdict: 'badAmount' }; if (give === 0 && get === 0) return { verdict: 'nothing' }; - var rounds = d.repeat ? 1 : d.rounds, wasSplit = false; - if (whole) { - var s = split(give, get, 1, d.repeat); - if (!s) return { verdict: Math.ceil(Math.max(give, get) / MAX_AMOUNT) > MAX_ROUNDS ? 'badAmount' : 'uneven' }; - give = s.give; get = s.get; rounds = s.rounds; wasSplit = true; - } var v = give > 0 && get > 0 ? 'exchange' : give > 0 ? 'gift' : 'request'; - return { verdict: v, give: give, get: get, rounds: rounds, split: wasSplit }; + return { verdict: v, give: give, get: get, rounds: d.repeat ? 1 : roundsFor(give, get) }; } - // TradeOfferForm.Split: the whole over the fewest equal rounds that carry exactly it (250 for 50 is 5 rounds of - // 50 for 10); null when no number of rounds up to MAX_ROUNDS divides both. A repeating offer keeps one round a time. - function split(give, get, rounds, repeat) { - if (repeat) rounds = 1; - var wholeGive = Math.max(0, give) * Math.max(1, rounds), wholeGet = Math.max(0, get) * Math.max(1, rounds); - for (var n = Math.max(1, Math.ceil(Math.max(wholeGive, wholeGet) / MAX_AMOUNT)); n <= MAX_ROUNDS; n++) { - if (wholeGive % n === 0 && wholeGet % n === 0) return { give: wholeGive / n, get: wholeGet / n, rounds: repeat ? 1 : n }; - } - return null; + // ExchangeTerms.RoundsFor: one round per 100 of the larger side (300 for 300 is 3, 301 for 300 is 4). + function roundsFor(give, get) { return Math.max(1, Math.ceil(Math.max(give, get, 0) / MAX_AMOUNT)); } + // ExchangeTerms.ShareOf: a round's part of the whole, spread evenly, the larger rounds first (101 over 2: 51, 50). + function shareOf(whole, rounds, index) { + if (whole <= 0 || index >= rounds) return 0; + return Math.floor(whole / rounds) + (index < whole % rounds ? 1 : 0); } function isOffer(v) { return v === 'exchange' || v === 'gift' || v === 'request'; } function step(item, shift) { return item === BEAVERS ? (shift ? 10 : 1) : (shift ? 1 : 10); } @@ -89,12 +79,8 @@ var next = up ? Math.floor(value / st) * st + st : Math.ceil(value / st) * st - st; return Math.max(min, Math.min(max, next)); } - function roundsText(rounds, repeat, give, giveId, get, getId) { - if (repeat) return 'Round after round, until you both agree to stop.'; - if (rounds <= 1) return 'Once.'; - var a = give > 0 ? amountOf(give * rounds, giveId) : 'nothing', b = get > 0 ? amountOf(get * rounds, getId) : 'nothing'; - return rounds + ' rounds: ' + a + ' for ' + b + ' in all.'; - } + // An offer says the whole trade; only a standing deal says it repeats. + function roundsText(repeat) { return repeat ? 'Every round, until you both agree to stop.' : ''; } // ---- the simulation (what the tick does in the game) ---- var timer = null; @@ -143,6 +129,8 @@ if (S.ledger[c].length > 20) S.ledger[c].length = 20; } x.done++; + // The next round's share of the whole, as the game sets it. + if (!x.repeat && x.done < x.rounds) for (c = 0; c < 2; c++) x.side[c].total = shareOf(x.side[c].whole, x.rounds, x.done); var beavers = x.side[0].good === BEAVERS ? [0, x.side[0].total] : x.side[1].good === BEAVERS ? [1, x.side[1].total] : null; say('Round ' + x.done + ' crossed.' + (beavers ? ' ' + beavers[1] + ' beaver' + (beavers[1] === 1 ? '' : 's') + ' moved from ' + colored(beavers[0]) + ' to ' + colored(1 - beavers[0]) + '.' : '')); if (!x.repeat && x.done >= x.rounds) { @@ -160,8 +148,8 @@ var j = judge(S.draft); if (!isOffer(j.verdict) || S.exchange) return; var d = S.draft, me = S.me, them = 1 - me; var side = []; - side[me] = { good: j.give > 0 ? d.give : null, total: j.give, held: 0 }; - side[them] = { good: j.get > 0 ? d.get : null, total: j.get, held: 0 }; + side[me] = { good: j.give > 0 ? d.give : null, whole: j.give, total: d.repeat ? j.give : shareOf(j.give, j.rounds, 0), held: 0 }; + side[them] = { good: j.get > 0 ? d.get : null, whole: j.get, total: d.repeat ? j.get : shareOf(j.get, j.rounds, 0), held: 0 }; S.exchange = { by: me, side: side, rounds: j.rounds, repeat: d.repeat, done: 0, state: 'proposed', cancelAsked: [false, false], serial: ++S.serial }; say(colored(me) + ' made an offer.'); render(true); @@ -272,14 +260,10 @@ var d = S.draft, h = ''; h += offerSide('give', 'You give', d.give, 'You have ' + S.stock[me][d.give], d.giveAmount); h += offerSide('get', 'You get', d.get, esc(COLONY[them]) + ' has ' + S.stock[them][d.get], d.getAmount); - // rounds card (no say for a repeating offer, nor when an amount is the whole trade) - var roundsOff = d.repeat || d.giveAmount > MAX_AMOUNT || d.getAmount > MAX_AMOUNT; - // A split trade's greyed box says how many rounds it is split into, as the game's does. - var judged = roundsOff && !d.repeat ? judge(d) : null, shownRounds = judged && judged.split ? judged.rounds : d.rounds; + // rounds card: the box only shows the rounds the game carries the trade in (nobody types in it) + var judged = judge(d), shownRounds = !isOffer(judged.verdict) ? '' : d.repeat ? '\u221E' : judged.rounds; h += '
Roundsup to ' + MAX_AMOUNT + ' of each per round
' - + '
' - + '' - + '' + + '
' + '
'; // summary var j = judge(d), text, ok = isOffer(j.verdict); @@ -287,17 +271,12 @@ case 'exchange': text = esc(COLONY[them]) + ' gets ' + amountOf(j.give, d.give) + ', and you get ' + amountOf(j.get, d.get) + '.'; break; case 'gift': text = 'A gift: ' + esc(COLONY[them]) + ' gets ' + amountOf(j.give, d.give) + ', and you ask nothing back.'; break; case 'request': text = 'A request: you ask ' + esc(COLONY[them]) + ' for ' + amountOf(j.get, d.get) + ', and give nothing.'; break; - case 'uneven': text = "These amounts don't split into equal rounds of up to " + MAX_AMOUNT + ' each. Change one amount a little.'; break; - case 'badAmount': text = 'Each side gives a whole number, up to ' + MAX_TYPED.toLocaleString('en-US') + ' in all over at most ' + MAX_ROUNDS + ' rounds.'; break; - case 'badRounds': text = 'Rounds go from 1 to ' + MAX_ROUNDS + '.'; break; + case 'badAmount': text = 'Each side gives a whole number, up to ' + (d.repeat ? MAX_AMOUNT : MAX_TYPED).toLocaleString('en-US') + '.'; break; case 'nothing': text = 'Set an amount above 0 on at least one side.'; break; case 'same': text = 'Choose two different goods.'; break; default: text = 'Choose what to trade.'; } - if (ok) text += ' ' + roundsText(j.rounds, d.repeat, j.give, d.give, j.get, d.get); - if (ok && j.split) text += d.repeat - ? ' Each round is ' + (j.give > 0 ? amountOf(j.give, d.give) : 'nothing') + ' for ' + (j.get > 0 ? amountOf(j.get, d.get) : 'nothing') + ': a Trading Post carries up to ' + MAX_AMOUNT + ' of each a round.' - : ' Split into rounds: a Trading Post carries up to ' + MAX_AMOUNT + ' of each a round.'; + if (ok && d.repeat) text += ' ' + roundsText(true); h += '
' + text + '
'; h += ''; return h; @@ -308,7 +287,7 @@ var h = '
' + caption + '' + stock + '
' + '
' + '' - + '' + + '' + '
'; if (open) { var owner = which === 'give' ? S.me : 1 - S.me; @@ -327,14 +306,14 @@ var h = '
' + (byMe ? 'Your offer' : colored(them) + ' offers an exchange') + '' + (byMe ? 'waiting for ' + esc(COLONY[them]) : '') + '
'; h += term('You give', mine, byMe ? '' : 'you have ' + S.stock[me][mine.good || 'logs']); h += term('You get', theirs, ''); - h += '
' + roundsText(x.rounds, x.repeat, mine.total, mine.good, theirs.total, theirs.good) + '
'; + h += '
' + roundsText(x.repeat) + '
'; if (byMe) h += '
'; else h += '
'; return h; } function term(caption, s, note) { - if (s.total <= 0 || !s.good) return '
' + caption + 'nothing
'; - return '
' + caption + '' + icon(s.good, 40) + '' + amountOf(s.total, s.good) + '' + (note ? '' + note + '' : '') + '
'; + if (s.whole <= 0 || !s.good) return '
' + caption + 'nothing
'; + return '
' + caption + '' + icon(s.good, 40) + '' + amountOf(s.whole, s.good) + '' + (note ? '' + note + '' : '') + '
'; } function renderActive(me, them, x) { @@ -428,22 +407,28 @@ el.addEventListener('click', function (e) { var w = el.getAttribute('data-step'), up = el.getAttribute('data-dir') === '1', item = S.draft[w]; var now = S.draft[w + 'Amount']; - // An amount typed above a round steps on within the whole, as TradeOfferForm.Stepped does. - S.draft[w + 'Amount'] = stepped(now, step(item, e.shiftKey), up, 0, now > MAX_AMOUNT ? MAX_TYPED : MAX_AMOUNT); render(); + // Within what the box takes, as TradeOfferForm.Stepped does: a repeating offer's round stops at 100. + S.draft[w + 'Amount'] = stepped(now, step(item, e.shiftKey), up, 0, S.draft.repeat ? MAX_AMOUNT : MAX_TYPED); render(); }); }); Array.prototype.forEach.call(qa('[data-amount]'), function (el) { - el.addEventListener('input', function () { var v = parseInt(el.value, 10); S.draft[el.getAttribute('data-amount') + 'Amount'] = isNaN(v) ? NaN : v; softRender(el); }); + el.addEventListener('input', function () { + var v = parseInt(el.value, 10); + // A repeating offer's round carries up to 100: more comes down to 100, as the game's box does. + if (S.draft.repeat && v > MAX_AMOUNT) { v = MAX_AMOUNT; el.value = String(v); } + S.draft[el.getAttribute('data-amount') + 'Amount'] = isNaN(v) ? NaN : v; softRender(el); + }); }); - Array.prototype.forEach.call(qa('[data-rounds]'), function (el) { - el.addEventListener('click', function (e) { S.draft.rounds = stepped(S.draft.rounds, e.shiftKey ? 10 : 1, el.getAttribute('data-rounds') === '1', 1, MAX_ROUNDS); render(); }); + if ((b = q('[data-repeat]'))) b.addEventListener('change', function () { + S.draft.repeat = b.checked; + // A repeating offer's amounts are each round's: a box holding more comes down to 100, never refused. + if (b.checked) { S.draft.giveAmount = Math.min(S.draft.giveAmount, MAX_AMOUNT); S.draft.getAmount = Math.min(S.draft.getAmount, MAX_AMOUNT); } + render(); }); - if ((b = q('[data-rounds-box]'))) b.addEventListener('input', function () { var v = parseInt(b.value, 10); S.draft.rounds = isNaN(v) ? NaN : v; softRender(b); }); - if ((b = q('[data-repeat]'))) b.addEventListener('change', function () { S.draft.repeat = b.checked; render(); }); } // Re-render while typing without losing the caret: swap everything but the focused box. function softRender(focused) { - var sel = focused.hasAttribute('data-amount') ? '[data-amount="' + focused.getAttribute('data-amount') + '"]' : '[data-rounds-box]'; + var sel = '[data-amount="' + focused.getAttribute('data-amount') + '"]'; var start = focused.selectionStart, end = focused.selectionEnd, val = focused.value; render(); var again = root.querySelector(sel); @@ -452,11 +437,11 @@ function preset(name) { S.exchange = null; S.pickerOpen = null; - if (name === 'logs') S.draft = { give: 'logs', get: 'gear', giveAmount: 100, getAmount: 25, rounds: 4, repeat: false }; - if (name === 'gift') S.draft = { give: 'berries', get: 'carrot', giveAmount: 60, getAmount: 0, rounds: 1, repeat: false }; - if (name === 'science') S.draft = { give: SCIENCE, get: 'berries', giveAmount: 50, getAmount: 30, rounds: 1, repeat: false }; - if (name === 'beavers') S.draft = { give: BEAVERS, get: 'carrot', giveAmount: 2, getAmount: 100, rounds: 1, repeat: false }; - if (name === 'standing') S.draft = { give: 'logs', get: 'carrot', giveAmount: 20, getAmount: 10, rounds: 1, repeat: true }; + if (name === 'logs') S.draft = { give: 'logs', get: 'gear', giveAmount: 400, getAmount: 100, repeat: false }; + if (name === 'gift') S.draft = { give: 'berries', get: 'carrot', giveAmount: 60, getAmount: 0, repeat: false }; + if (name === 'science') S.draft = { give: SCIENCE, get: 'berries', giveAmount: 50, getAmount: 30, repeat: false }; + if (name === 'beavers') S.draft = { give: BEAVERS, get: 'carrot', giveAmount: 2, getAmount: 100, repeat: false }; + if (name === 'standing') S.draft = { give: 'logs', get: 'carrot', giveAmount: 20, getAmount: 10, repeat: true }; render(true); } diff --git a/docs/index.html b/docs/index.html index c327141..feb3013 100644 --- a/docs/index.html +++ b/docs/index.html @@ -369,7 +369,7 @@

Barter at a Trading Post

Load an offer
- + @@ -390,7 +390,7 @@

Things to try

  • Untick answers automatically and make an offer. Then switch to Player 2 to Accept or Decline it.
  • Set Workers on your half to 0 during a round. Your side stops, and nothing crosses.
  • Press Cancel exchange. It ends when the other player agrees, and any goods already brought go back to the colony that brought them.
  • -
  • Type 300 in both amount boxes. A post carries at most 100 of each a round, so the whole trade is split into rounds of 100 for 100, whatever the Rounds box says.
  • +
  • Type 101 for 2. A post carries at most 100 of each a round, so Rounds shows 2: 51 logs for 1 gear, then 50 for 1.
  • After a round crosses, press Clear on the Ledger. The totals traded below it stay.
  • From 9ddbbad1858bdb9c5c59e12439d4f06461d9e61c Mon Sep 17 00:00:00 2001 From: Kyler Ramsey Date: Tue, 29 Sep 2026 13:14:31 -0700 Subject: [PATCH 3/5] Changelog: whole trades and the Global history graphs Co-Authored-By: Claude Opus 5.5 --- STABILITY-CHANGELOG.md | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/STABILITY-CHANGELOG.md b/STABILITY-CHANGELOG.md index 68361c4..4f5ad0f 100644 --- a/STABILITY-CHANGELOG.md +++ b/STABILITY-CHANGELOG.md @@ -5,6 +5,33 @@ Every change this fork makes relative to the original BeaverBuddies `v1.1` branc 1.1.2.4. For a plain-language summary, see the [README](README.md). Future releases add a new entry above the current one. +## Unreleased + +**Trades typed whole and never refused, the Global history graphs your own colony's, and a design pass of the +colonies window** (built against Timberborn 1.1.2.4). **Not played.** + +- **A trade is typed whole and never refused for its amounts.** Kyler, after rc30: "No trade offer should be refused, + the game should just take of those details without concerning the player." rc30 refused amounts over 100 that + didn't split into equal rounds (101 Logs for 2 Gears); before that, rounding changed the totals (500 Logs for 1 Gear + became 5 Gears). Now the player types the whole trade, up to 9,900 a side, and exactly that crosses. The game takes + one round per 100 of the larger side (`ExchangeTerms.RoundsFor`: 300 for 300 is 3, 301 for 300 is 4) and spreads + each side as evenly as it goes, larger rounds first (`ExchangeTerms.ShareOf`: 101 Logs for 2 Gears is 51 for 1, + then 50 for 1; 500 Logs for 1 Gear carries the Gear in the first round and Logs alone after). `CrossingExchange` + saves each side's `Whole`; `Total` is the current round's share, set again as each round crosses, so everything + that reads a round (workers, holding, crossing, the progress bars) is unchanged. `ExchangeProposedEvent` and + `ExchangeAcceptedEvent` carry the whole amounts, and the host checks the rounds follow from them. The form's + **Rounds** box is display-only (greyed, the round count, or ∞ for **Repeat until cancelled**, whose amounts stay + each round's, up to 100: a larger number is brought down to 100). Offers, answers, the offer panel, the last-terms + line and the colonies window say only the whole trade ("101 Logs for 2 Gears"); once it runs, the panel shows + "round 1 of 2" and the ledger each round as it crossed. The site's Trading Post demo plays by the same rules. + Both players need this build. +- **The Global history graphs show your own colony.** The batch control window's Global view of the goods (F9) and + population (F10) graphs added both colonies. `ColonyHistoryView` builds a display-only colony history, day by day, + from this player's own districts' saved histories (goods summed; population summed, wellbeing weighted by beavers) + and hands it to the graphs (`GoodStatisticsGroupFactory.Create`, `PopulationStatisticsGraphFactory.Create`). The + game's saved global registries are only read. A deleted district's days drop out, as its history goes with it. + Faction unlocks are now the only map-wide figure a player sees. + ## 1.4.0-rc30 **The faction goal's progress is your own colony's, and an audit of rc16 to rc29 against the game's assemblies** From e703953215d463fc2fa90935577164eff55905ad Mon Sep 17 00:00:00 2001 From: Kyler Ramsey Date: Tue, 29 Sep 2026 13:16:12 -0700 Subject: [PATCH 4/5] Trading posts window (Y): drawn with the game UI's own classes A design pass of the Trading Posts and colonies window against the game's UXML/USS (UI.zip): the named box of the population's well-being, the map editor's wooden buttons, the game's text classes. - Text uses the game's text classes (game-text-small/normal/big/heading, text--yellow), which a window has; the entity panel's (entity-panel__text) is not loaded there, so titles, amounts, buttons and the goods grid's counts read in the game's light grey instead of the theme's dark default. The white overrides go. - NativeElements.Text and its buttons also carry game-text-normal (same grey as entity-panel__text: no change in an entity panel); new GameText / WithTextClass for text sized by the game's class alone. - The box keeps the game's own padding (45 px) and is 540 wide; rows get the panel sections' padding (8/12). - A colony's buttons sit under its text, at the right, and wrap, instead of a column that squeezed the text. - Food and water pairs wrap as one; captions (Goods, Looking for:) in the game's yellow as on the Trading Post. - Clear is the window's wooden button (the entity panel's red button has no art in a window); another colony's wishes are plain green tiles, not buttons that light up on hover. - RuntimeChecks (rc31): every class the window names is listed and defined in the sheets GameUI.uxml loads, and the window is still the game's named box. StabilityTests: the same list, from the source. Co-Authored-By: Claude Opus 5.5 --- BeaverBuddies/Colonies/TradeOverviewPanel.cs | 280 ++++++++++++------- BeaverBuddies/Util/NativeElements.cs | 33 ++- RuntimeChecks/Program.cs | 2 + RuntimeChecks/Rc31RuntimeChecks.cs | 85 ++++++ StabilityTests/Rc27Checks.cs | 34 +++ 5 files changed, 336 insertions(+), 98 deletions(-) create mode 100644 RuntimeChecks/Rc31RuntimeChecks.cs diff --git a/BeaverBuddies/Colonies/TradeOverviewPanel.cs b/BeaverBuddies/Colonies/TradeOverviewPanel.cs index daa0d07..33345d3 100644 --- a/BeaverBuddies/Colonies/TradeOverviewPanel.cs +++ b/BeaverBuddies/Colonies/TradeOverviewPanel.cs @@ -39,7 +39,27 @@ public class TradeOverviewPanel : IPostLoadableSingleton, IUpdatableSingleton, I public const string KeyBindingId = "BeaverBuddies.KeyBind.TradeOverview"; // The Trade button's icon, drawn like the game's own top-right buttons' (a file of this mod). private const string ToggleIconPath = "UI/Images/BeaverBuddies/square-toggle-trade"; - private const float Top = 110, BottomMargin = 40, Width = 470; + // Below the top bar, where the game's entity panel starts (entity-panel: top 110px). The box is as wide as the + // game's boxes of lists (the population's well-being is 590): room for a row's text beside its buttons. + private const float Top = 110, BottomMargin = 40, Width = 540; + + /// + /// Every class of the game's the window is drawn with. All are in the style sheets every game window has (the game + /// UI's: CoreStyle, CommonStyle, GameStyle), not the entity panel's, which a window does not have; RuntimeChecks + /// holds them to the game's UI files. + /// + public static readonly string[] ClassesUsed = + { + // The game's named box (Common/NamedBoxTemplate, as the population's well-being): frame, title badge, close button. + "sliced-border", "sliced-border--nontransparent", "box__content-container", "capsule-header", "capsule-header--lower", + "content-centered", "capsule-header__text", "close-button", + // Its list (the well-being box's scroll view), each row's green board, and a good's tile (the good cells' board). + "game-scroll-view", "bg-sub-box--green", "bg-box--green", + // Text: headings, a row's title, its lines, captions in the game's yellow. + NativeElements.TextSmall, NativeElements.TextNormal, NativeElements.TextBig, NativeElements.TextHeading, "text--bold", "text--yellow", + // Buttons: the wooden button (with its hover and pressed art), the square +. + "button-game", "button-square", "button-square--large", "button-plus", + }; private readonly UILayout _uiLayout; private readonly InputService _inputService; @@ -55,6 +75,7 @@ public class TradeOverviewPanel : IPostLoadableSingleton, IUpdatableSingleton, I /// A colony's row: its texts, its food and water, what it is looking for. private sealed class ColonyCard { + public VisualElement Root; public Label Title, Detail, Note; public VisualElement Supplies, Wishes; public Image FoodIcon, WaterIcon; @@ -203,8 +224,10 @@ private void Refresh() // ---- building ---- /// - /// The game's box (CoreStyle): a framed panel (sliced-border, box__content-container), a title badge on its top - /// edge (capsule-header), the round close button at its corner (close-button), and a scrolling list inside. + /// The game's named box (Common/NamedBoxTemplate, as the population's well-being): a framed panel (sliced-border, + /// box__content-container, with the game's padding), a title badge on its top edge (capsule-header), the round + /// close button at its corner (close-button), and a scrolling list inside (game-scroll-view). The frame is the + /// solid one of the game's dialog boxes (sliced-border--nontransparent), as the box stays open over the map. /// private void Build() { @@ -225,9 +248,6 @@ private void Build() // The class stretches a box across its parent (box__content-container: align-self: stretch, flex-grow: 1). box.style.alignSelf = Align.Center; box.style.flexGrow = 0; - box.style.paddingLeft = 32; - box.style.paddingRight = 32; - box.style.paddingBottom = 30; window.Add(box); var header = new NineSliceVisualElement(); @@ -253,11 +273,11 @@ private void Build() scroll.style.flexShrink = 1; scroll.style.minHeight = 0; postsTitle = Heading(); - emptyPosts = NativeElements.MutedText("", 13); + emptyPosts = NativeElements.GameText("", NativeElements.TextNormal); emptyPosts.style.marginTop = 4; postsList = new VisualElement(); Label coloniesTitle = Heading(T("BeaverBuddies.Colony.Overview.Colonies")); - coloniesTitle.style.marginTop = 14; + coloniesTitle.style.marginTop = 16; coloniesList = new VisualElement(); scroll.Add(postsTitle); scroll.Add(emptyPosts); @@ -269,7 +289,7 @@ private void Build() VisualElement footer = NativeElements.Row(); footer.style.marginTop = 12; footer.style.justifyContent = Justify.SpaceBetween; - Label hint = NativeElements.Text(T("BeaverBuddies.Colony.Overview.Hint"), 12); + Label hint = NativeElements.GameText(T("BeaverBuddies.Colony.Overview.Hint"), NativeElements.TextSmall); hint.style.flexShrink = 1; hint.style.marginRight = 8; footer.Add(hint); @@ -283,8 +303,6 @@ private void Build() box.Add(picker.Root); _visualElementInitializer.InitializeVisualElement(window); - // White on the dark board, set after the initializer so nothing it applies can darken it. - hint.style.color = Color.white; window.style.display = DisplayStyle.None; _uiLayout.AddAbsoluteItem(window); } @@ -404,7 +422,7 @@ private void RefreshLists() foreach (var (key, half) in posts) { DistrictCrossing target = half; - postsList.Add(Card(out Label title, out Label detail, + postsList.Add(PostCard(out Label title, out Label detail, SmallButton(T("BeaverBuddies.Colony.Overview.GoTo"), () => GoTo(target)))); postLabels[key] = (title, detail); } @@ -467,7 +485,7 @@ private void RefreshLists() if (started) buttons.AddRange(StewardButtons(slot, seat, me, myId, host, present, others, stewards, lifecycle)); if (started && slot == seat && slot == me) buttons.AddRange(FactionSwitchButtons(slot)); ColonyCard card = BuildColonyCard(buttons.ToArray()); - coloniesList.Add(card.Title.parent.parent.parent); + coloniesList.Add(card.Root); colonyCards[slot] = card; // This player's colony (the one their actions count as) says what it is looking for from here. if (slot == me && started) BuildWishEditor(card, slot, wishlist); @@ -617,7 +635,8 @@ private static void ShowSupply(Label label, Supply supply) NativeElements.SetText(label, days == null ? string.Format(T("BeaverBuddies.Colony.Overview.SupplyNoDays"), stock) : string.Format(T("BeaverBuddies.Colony.Overview.SupplyDays"), stock, days)); - label.style.color = SupplyDays.IsLow(supply.Days) ? new StyleColor(NativeElements.Warning) : new StyleColor(NativeElements.Muted); + // The game's light grey (its class), or the warning colour when less than a day is left. + label.style.color = SupplyDays.IsLow(supply.Days) ? new StyleColor(NativeElements.Warning) : new StyleColor(StyleKeyword.Null); } /// @@ -636,7 +655,7 @@ private void RefreshGoods(ColonyCard card, int slot, bool shown) card.ShownGoods = key; card.GoodsChips.Clear(); card.GoodsAmounts.Clear(); - if (goods.Count == 0) card.GoodsChips.Add(NativeElements.MutedText(T("BeaverBuddies.Colony.Trade.Nothing"))); + if (goods.Count == 0) card.GoodsChips.Add(MutedLine(T("BeaverBuddies.Colony.Trade.Nothing"))); foreach (var good in goods) { VisualElement chip = NativeElements.Row(); @@ -646,8 +665,9 @@ private void RefreshGoods(ColonyCard card, int slot, bool shown) icon.sprite = _items.IconOf(good.Key); icon.style.marginRight = 2; chip.Add(icon); - Label amount = NativeElements.Text("", 12); - amount.style.color = Color.white; + // An amount in the game's light grey, as its inventories write them. + Label amount = NativeElements.GameText("", NativeElements.TextSmall); + amount.style.whiteSpace = WhiteSpace.NoWrap; chip.Add(amount); _tooltipRegistrar.Register(chip, _items.Name(good.Key)); card.GoodsChips.Add(chip); @@ -693,10 +713,8 @@ private void RefreshWishes(ColonyCard card, int slot, ColonyWishlist wishlist) if (card.Wishes.userData as string == key) return; card.Wishes.userData = key; card.Wishes.Clear(); - Label caption = NativeElements.MutedText(T("BeaverBuddies.Colony.Overview.LookingFor")); - caption.style.marginRight = 6; - card.Wishes.Add(caption); - foreach (string item in wishes) card.Wishes.Add(WishChip(item, null)); + card.Wishes.Add(Caption(T("BeaverBuddies.Colony.Overview.LookingFor"))); + foreach (string item in wishes) card.Wishes.Add(WishTile(item)); } /// @@ -707,15 +725,14 @@ private void BuildWishEditor(ColonyCard card, int slot, ColonyWishlist wishlist) { NativeElements.Show(card.Wishes, true); card.Wishes.Clear(); - Label caption = NativeElements.MutedText(T("BeaverBuddies.Colony.Overview.LookingFor")); - caption.style.marginRight = 6; + Label caption = Caption(T("BeaverBuddies.Colony.Overview.LookingFor")); _tooltipRegistrar.Register(caption, T("BeaverBuddies.Colony.Overview.LookingForTooltip")); card.Wishes.Add(caption); List wishes = (wishlist?.Of(slot) ?? (IReadOnlyList)Array.Empty()).ToList(); for (int i = 0; i < wishes.Count; i++) { int index = i; - Button chip = WishChip(wishes[i], () => EditWish(slot, index, card.Wishes)); + Button chip = WishButton(wishes[i], () => EditWish(slot, index, card.Wishes)); picker.AddOpener(chip); card.Wishes.Add(chip); } @@ -729,36 +746,50 @@ private void BuildWishEditor(ColonyCard card, int slot, ColonyWishlist wishlist) } if (wishes.Count > 0) { - Button clear = NativeElements.RedButton(T("BeaverBuddies.Colony.Overview.ClearWishes"), () => SendWishes(new List())); - clear.style.fontSize = 12; - clear.style.color = Color.white; - clear.style.minHeight = 24; - clear.style.height = 24; - clear.style.paddingTop = 0; - clear.style.paddingBottom = 0; - clear.style.marginLeft = 8; + // The window's wooden button, as its others (the entity panel's red button has no art in a window). + Button clear = SmallButton(T("BeaverBuddies.Colony.Overview.ClearWishes"), () => SendWishes(new List())); + clear.style.marginLeft = 6; card.Wishes.Add(clear); } } - /// A good's icon on the game's wooden button (or, with no click, a plain chip with a tooltip). - private Button WishChip(string item, Action onClick) + // A good's tile: 32 by 28, its icon centred, as the goods grid's cells. + private const int WishWidth = 32, WishHeight = 28, WishIcon = 20; + + /// This player's wish: a good's icon on the game's wooden button (lighter on hover, pressed on click). + private Button WishButton(string item, Action onClick) { Button chip = NativeElements.WoodenButton("", onClick); - chip.style.minHeight = 28; - chip.style.height = 28; - chip.style.paddingLeft = 4; chip.style.paddingRight = 4; chip.style.paddingTop = 2; chip.style.paddingBottom = 2; - chip.style.marginRight = 4; - if (onClick == null) chip.pickingMode = PickingMode.Position; - chip.style.width = 32; chip.style.minWidth = 32; - chip.style.alignItems = Align.Center; chip.style.justifyContent = Justify.Center; - Image icon = NativeElements.Icon(20); - icon.style.marginLeft = 0; icon.style.marginRight = 0; icon.style.marginTop = 0; icon.style.marginBottom = 0; + chip.style.paddingLeft = 0; chip.style.paddingRight = 0; chip.style.paddingTop = 0; chip.style.paddingBottom = 0; + WishTileLayout(chip, item); + _tooltipRegistrar.Register(chip, string.Format(T("BeaverBuddies.Colony.Overview.WishTooltip"), _items.Name(item))); + return chip; + } + + /// + /// Another colony's wish, which is not a button: the good's icon on the game's plain green tile (the goods + /// cells' board, which has no hover art), with its name as a tooltip. + /// + private VisualElement WishTile(string item) + { + NineSliceVisualElement tile = NativeElements.Box("bg-box--green"); + WishTileLayout(tile, item); + _tooltipRegistrar.Register(tile, _items.Name(item)); + return tile; + } + + private void WishTileLayout(VisualElement tile, string item) + { + var s = tile.style; + s.width = WishWidth; s.minWidth = WishWidth; + s.height = WishHeight; s.minHeight = WishHeight; + s.flexShrink = 0; + s.marginRight = 4; s.marginTop = 2; s.marginBottom = 2; + s.alignItems = Align.Center; s.justifyContent = Justify.Center; + Image icon = NativeElements.Icon(WishIcon); icon.style.alignSelf = Align.Center; icon.sprite = _items.IconOf(item); - chip.Add(icon); - _tooltipRegistrar.Register(chip, onClick == null ? _items.Name(item) : string.Format(T("BeaverBuddies.Colony.Overview.WishTooltip"), _items.Name(item))); - return chip; + tile.Add(icon); } private void EditWish(int slot, int index, VisualElement anchor) @@ -892,53 +923,51 @@ private void HandOver(int from, int to) // ---- elements ---- /// - /// A colony's row: the post row's title and line, then its food and water (icons and days), a muted note (who - /// looks after it), and what it is looking for, with its buttons at the right. + /// A colony's row on the game's green board: its faction (a mixed game), then its name, its population and status, + /// its food and water (icons and days), its goods, a muted note (who looks after it), and what it is looking for; + /// its buttons under all that, at the right, wrapping onto a second line when there are many. /// private ColonyCard BuildColonyCard(params Button[] buttons) { var card = new ColonyCard(); - NineSliceVisualElement board = Card(out card.Title, out card.Detail, buttons); - VisualElement text = card.Title.parent; + NineSliceVisualElement board = Board(); + card.Root = board; + VisualElement top = NativeElements.Row(Align.FlexStart); card.Faction = new VisualElement(); card.Faction.style.marginRight = 8; - card.Faction.style.alignSelf = Align.FlexStart; card.Faction.style.flexShrink = 0; card.Faction.style.display = DisplayStyle.None; - text.parent.Insert(0, card.Faction); + top.Add(card.Faction); + VisualElement text = TitleAndDetail(out card.Title, out card.Detail); + top.Add(text); + board.Add(top); + + // Food and water as the top bar counts them: each an icon and its stock, a pair that wraps as one. card.Supplies = NativeElements.Row(); - card.Supplies.style.marginTop = 3; - card.FoodIcon = NativeElements.Icon(18); - card.Food = NativeElements.MutedText("", 12); - card.Food.style.marginLeft = 3; - card.Food.style.marginRight = 12; - card.WaterIcon = NativeElements.Icon(18); - card.Water = NativeElements.MutedText("", 12); - card.Water.style.marginLeft = 3; - card.Supplies.Add(card.FoodIcon); - card.Supplies.Add(card.Food); - card.Supplies.Add(card.WaterIcon); - card.Supplies.Add(card.Water); + card.Supplies.style.flexWrap = Wrap.Wrap; + card.Supplies.style.marginTop = 4; + card.Supplies.Add(Supply(out card.FoodIcon, out card.Food)); + card.Supplies.Add(Supply(out card.WaterIcon, out card.Water)); _tooltipRegistrar.Register(card.Supplies, T("BeaverBuddies.Colony.Overview.SuppliesTooltip")); text.Add(card.Supplies); // Another colony's goods, laid out as the Trading Post's totals: a caption, then icons and amounts that wrap. card.Goods = NativeElements.Row(Align.FlexStart); card.Goods.style.marginTop = 4; card.Goods.style.display = DisplayStyle.None; - card.GoodsCaption = NativeElements.MutedText("", 12); - card.GoodsCaption.style.marginRight = 6; - card.GoodsCaption.style.marginTop = 1; - card.GoodsCaption.style.flexShrink = 0; + card.GoodsCaption = Caption(); + // Level with the icons' line (20 px) beside it. + card.GoodsCaption.style.marginTop = 2; _tooltipRegistrar.Register(card.GoodsCaption, T("BeaverBuddies.Colony.Overview.GoodsTooltip")); card.GoodsChips = NativeElements.Row(); card.GoodsChips.style.flexWrap = Wrap.Wrap; card.GoodsChips.style.flexGrow = 1; card.GoodsChips.style.flexShrink = 1; + card.GoodsChips.style.minWidth = 0; card.Goods.Add(card.GoodsCaption); card.Goods.Add(card.GoodsChips); text.Add(card.Goods); - card.Note = NativeElements.MutedText("", 12); - card.Note.style.marginTop = 2; + card.Note = MutedLine(); + card.Note.style.marginTop = 4; card.Note.style.display = DisplayStyle.None; text.Add(card.Note); card.Wishes = NativeElements.Row(); @@ -946,53 +975,110 @@ private ColonyCard BuildColonyCard(params Button[] buttons) card.Wishes.style.flexWrap = Wrap.Wrap; card.Wishes.style.display = DisplayStyle.None; text.Add(card.Wishes); + + if (buttons.Length > 0) + { + VisualElement actions = NativeElements.Row(); + actions.style.flexWrap = Wrap.Wrap; + actions.style.justifyContent = Justify.FlexEnd; + actions.style.marginTop = 4; + foreach (Button button in buttons) + { + button.style.marginLeft = 6; + button.style.marginTop = 4; + actions.Add(button); + } + board.Add(actions); + } return card; } - /// A row of the list on the game's green board: a title, a line under it, and its buttons at the right. - private static NineSliceVisualElement Card(out Label title, out Label detail, params Button[] buttons) + /// A Trading Post's row on the game's green board: a title, the lines under it, and its button at the right. + private static NineSliceVisualElement PostCard(out Label title, out Label detail, Button button) { - NineSliceVisualElement card = NativeElements.Box("bg-sub-box--green"); - card.style.marginTop = 6; - card.style.paddingLeft = 10; card.style.paddingRight = 8; card.style.paddingTop = 6; card.style.paddingBottom = 7; + NineSliceVisualElement board = Board(); VisualElement row = NativeElements.Row(); - VisualElement text = new VisualElement(); + row.Add(TitleAndDetail(out title, out detail)); + button.style.marginLeft = 10; + row.Add(button); + board.Add(row); + return board; + } + + /// A row's board: the game's green sub-box, with the padding of the game's panel sections (entity-sub-panel: 8px 12px). + private static NineSliceVisualElement Board() + { + NineSliceVisualElement board = NativeElements.Box("bg-sub-box--green"); + board.style.marginTop = 6; + board.style.paddingLeft = 12; board.style.paddingRight = 12; board.style.paddingTop = 8; board.style.paddingBottom = 8; + return board; + } + + /// + /// A row's text, taking the room its buttons leave: its title (game-text-big, with a colony's name in bold in its + /// colour) and its lines under it (game-text-small), both in the game's light grey. + /// + private static VisualElement TitleAndDetail(out Label title, out Label detail) + { + var text = new VisualElement(); text.style.flexGrow = 1; text.style.flexShrink = 1; - title = NativeElements.Text("", 13); + text.style.minWidth = 0; + title = NativeElements.GameText("", NativeElements.TextBig); title.enableRichText = true; - detail = NativeElements.MutedText("", 12); - detail.style.marginTop = 1; + detail = NativeElements.GameText("", NativeElements.TextSmall); + detail.style.marginTop = 2; text.Add(title); text.Add(detail); - row.Add(text); - VisualElement actions = new VisualElement(); - actions.style.flexShrink = 0; - actions.style.alignItems = Align.FlexEnd; - foreach (Button button in buttons) - { - button.style.marginLeft = 8; - button.style.marginTop = 2; - actions.Add(button); - } - row.Add(actions); - card.Add(row); - return card; + return text; + } + + /// Food's or water's icon and its stock, kept together. + private static VisualElement Supply(out Image icon, out Label amount) + { + VisualElement pair = NativeElements.Row(); + pair.style.marginRight = 12; + pair.style.height = 20; + icon = NativeElements.Icon(18); + pair.Add(icon); + amount = NativeElements.GameText("", NativeElements.TextSmall); + amount.style.whiteSpace = WhiteSpace.NoWrap; + amount.style.marginLeft = 3; + pair.Add(amount); + return pair; + } + + /// A caption before a line of icons ("Goods", "Looking for:"), in the game's yellow, as the Trading Post's. + private static Label Caption(string text = "") + { + Label caption = NativeElements.GameText(text, NativeElements.TextSmall); + caption.AddToClassList("text--yellow"); + caption.style.whiteSpace = WhiteSpace.NoWrap; + caption.style.flexShrink = 0; + caption.style.marginRight = 6; + return caption; + } + + /// A secondary line (who looks after a colony, "nothing yet"), in the mod's muted grey. + private static Label MutedLine(string text = "") + { + Label label = NativeElements.GameText(text, NativeElements.TextSmall); + label.style.color = NativeElements.Muted; + return label; } - /// A heading as the game's boxes write them (game-text-heading). + /// A heading as the game's boxes write them (game-text-heading, bold). private static Label Heading(string text = "") { - var label = new Label(text); - label.AddToClassList("game-text-heading"); + Label label = NativeElements.GameText(text, NativeElements.TextHeading); label.AddToClassList("text--bold"); return label; } + /// The window's button: the game's wooden button (button-game) in its small text (game-text-small), 24 px high. private static Button SmallButton(string text, Action onClick) { - Button button = NativeElements.WoodenButton(text, onClick); - button.style.fontSize = 12; + Button button = NativeElements.WithTextClass(NativeElements.WoodenButton(text, onClick), NativeElements.TextSmall); button.style.minHeight = 24; button.style.height = 24; button.style.paddingTop = 0; diff --git a/BeaverBuddies/Util/NativeElements.cs b/BeaverBuddies/Util/NativeElements.cs index 4e69202..b22688a 100644 --- a/BeaverBuddies/Util/NativeElements.cs +++ b/BeaverBuddies/Util/NativeElements.cs @@ -37,11 +37,19 @@ public static NineSliceVisualElement Box(string backgroundClass) return box; } - /// Text as the game's entity panels write it (13 px, light grey), wrapping. + /// The game's text classes by size (CommonStyle, which every game window has): light grey, wrapping. + public const string TextSmall = "game-text-small", TextNormal = "game-text-normal", TextBig = "game-text-big", TextHeading = "game-text-heading"; + private static readonly string[] TextSizes = { TextSmall, TextNormal, TextBig, TextHeading }; + + /// + /// Text as the game's entity panels write it (13 px, light grey), wrapping. Also in the game's own light grey + /// (game-text-normal) outside an entity panel, whose sheet (entity-panel__text) a window does not have. + /// public static Label Text(string text = "", int size = 13, bool bold = false) { var label = new Label(SentencePerLine(text)); label.AddToClassList("entity-panel__text"); + label.AddToClassList(TextNormal); var s = label.style; s.fontSize = size; s.whiteSpace = WhiteSpace.Normal; @@ -66,6 +74,26 @@ public static Label MutedText(string text = "", int size = 12) return label; } + /// + /// Text sized and coloured by one of the game's text classes alone ( … ), + /// as the game's windows write it: for a window, where the entity panel's sheet is not loaded. + /// + public static Label GameText(string text = "", string textClass = TextNormal) => WithTextClass(Text(text), textClass); + + /// + /// Gives a text (a label or a button) one of the game's text classes for its size and colour, in place of the + /// size set on it here: the entity panel's text class, the other size classes and the inline size are taken off, + /// so the class decides. + /// + public static T WithTextClass(T element, string textClass) where T : TextElement + { + element.RemoveFromClassList("entity-panel__text"); + foreach (string size in TextSizes) element.RemoveFromClassList(size); + element.AddToClassList(textClass); + element.style.fontSize = StyleKeyword.Null; + return element; + } + /// The game's wooden button (the warehouse's "Accept goods" selector, MixedStorage's buttons). public static Button WoodenButton(string text, Action onClick) => TextButton(text, onClick, "button-game"); @@ -77,7 +105,10 @@ private static Button TextButton(string text, Action onClick, params string[] cl { var button = new NineSliceButton { text = text }; if (onClick != null) button.clicked += onClick; + // The game's light grey in an entity panel (entity-panel__text) and in a window (game-text-normal), as the + // map editor's wooden buttons are written (button-game game-text-normal). button.AddToClassList("entity-panel__text"); + button.AddToClassList(TextNormal); foreach (string c in classes) button.AddToClassList(c); var s = button.style; s.fontSize = 13; diff --git a/RuntimeChecks/Program.cs b/RuntimeChecks/Program.cs index ce5b72b..26dd08d 100644 --- a/RuntimeChecks/Program.cs +++ b/RuntimeChecks/Program.cs @@ -146,6 +146,8 @@ void Test(string name, Action run) Rc27RuntimeChecks.Run(assembly, Path.GetFullPath(args[1]), Test); Rc28RuntimeChecks.Run(assembly, Path.GetFullPath(args[1]), Test); Rc29RuntimeChecks.Run(assembly, Path.GetFullPath(args[1]), Test); +// 1.4.0-rc31: the trading posts window (Y) is drawn with the game UI's own classes. +Rc31RuntimeChecks.Run(assembly, Path.GetFullPath(args[1]), Test); Console.WriteLine($"{total-failures}/{total} passed"); return failures == 0 ? 0 : 1; diff --git a/RuntimeChecks/Rc31RuntimeChecks.cs b/RuntimeChecks/Rc31RuntimeChecks.cs new file mode 100644 index 0000000..4aa75e2 --- /dev/null +++ b/RuntimeChecks/Rc31RuntimeChecks.cs @@ -0,0 +1,85 @@ +#nullable enable +using System.IO.Compression; +using System.Reflection; +using System.Text.RegularExpressions; + +// 1.4.0-rc31, checks against the compiled mod and the game's own UI files (StreamingAssets/Modding/UI.zip): the +// Trading Posts and colonies window (Y) is drawn with the game's classes. The window hangs in the game UI's +// "Absolute-items", so only the style sheets GameUI.uxml loads reach it (not the entity panel's): every class it names is +// listed in TradeOverviewPanel.ClassesUsed, and every listed class is defined in one of those sheets. +internal static class Rc31RuntimeChecks +{ + const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; + + public static void Run(Assembly mod, string managedPath, Action test) + { + test("rc31: the trading posts window uses only classes of the style sheets the game UI loads", () => + { + using ZipArchive ui = UiZip(managedPath); + var sheets = Regex.Matches(Read(ui, "Views/Common/GameUI.uxml"), "Style src=\"/Assets/Resources/UI/(Views/[^\"]+\\.uss)\"") + .Select(m => m.Groups[1].Value).ToList(); + if (sheets.Count == 0) throw new Exception("GameUI.uxml loads no style sheets"); + var defined = new HashSet(); + foreach (string sheet in sheets) + foreach (Match m in Regex.Matches(Read(ui, sheet), "\\.([A-Za-z_][A-Za-z0-9_-]*)")) defined.Add(m.Groups[1].Value); + Type window = mod.GetType("BeaverBuddies.Colonies.TradeOverviewPanel", true)!; + var used = (string[])(window.GetField("ClassesUsed", All)?.GetValue(null) ?? throw new Exception("TradeOverviewPanel.ClassesUsed is gone")); + var missing = used.Where(c => !defined.Contains(c)).ToList(); + if (missing.Count > 0) throw new Exception("not in the game UI's style sheets (" + string.Join(", ", sheets) + "): " + string.Join(", ", missing)); + + // Every class-like string the window's code loads (its methods, lambdas and nested types) is one it lists. + // Unity's own classes (unity-…) are the Toggle's parts, found by name, not styled here. + var named = Types(window).SelectMany(t => t.GetMethods(All).Cast().Concat(t.GetConstructors(All))) + .Where(m => m.GetMethodBody() != null) + .SelectMany(m => IlScan.Instructions(m)).Select(i => i.Text) + .Where(text => text != null && Regex.IsMatch(text, "^[a-z][a-z0-9]*(?:(?:-|--|_|__)[a-z0-9]+)+$") && !text.StartsWith("unity-")) + .Select(text => text!).Distinct().ToList(); + var unlisted = named.Where(c => !used.Contains(c)).ToList(); + if (unlisted.Count > 0) throw new Exception("the window names classes it does not list in ClassesUsed: " + string.Join(", ", unlisted)); + Console.WriteLine(" The window's classes: " + string.Join(", ", named.OrderBy(c => c, StringComparer.Ordinal))); + + // The entity panel's classes are not among them: in a window they would draw nothing. + foreach (string panelOnly in new[] { "entity-panel__text", "entity-fragment__button--red" }) + if (defined.Contains(panelOnly)) Console.WriteLine($" Note: {panelOnly} is now in the game UI's sheets"); + else if (used.Contains(panelOnly) || named.Contains(panelOnly)) throw new Exception("the window relies on " + panelOnly + ", which a window does not have"); + }); + + test("rc31: the trading posts window is still built as the game's named box", () => + { + using ZipArchive ui = UiZip(managedPath); + string box = Read(ui, "Views/Common/NamedBoxTemplate.uxml"); + // The frame, the title badge on its edge, its text and the close button, as the window builds them. + foreach (string classes in new[] { "sliced-border box__content-container", "capsule-header capsule-header--lower content-centered", + "capsule-header__text", "close-button" }) + if (!box.Contains("class=\"" + classes + "\"")) throw new Exception("NamedBoxTemplate no longer has class=\"" + classes + "\""); + // The population's well-being box, the window's model, is still one of them, with the same scroll view. + string wellbeing = Read(ui, "Views/Game/Population/PopulationWellbeingBox.uxml"); + if (!wellbeing.Contains("NamedBoxTemplate.uxml") || !wellbeing.Contains("game-scroll-view")) + throw new Exception("the well-being box is no longer a named box with the game's scroll view"); + // The game UI's sheets define the text colours the window relies on: its light grey and its yellow. + string common = Read(ui, "Views/Common/CommonStyle.uss"); + foreach (string rule in new[] { "\\.game-text-small\\s*\\{[^}]*color:\\s*rgb\\(204, 204, 204\\)", "\\.game-text-big\\s*\\{[^}]*color:\\s*rgb\\(204, 204, 204\\)", + "\\.text--yellow\\s*\\{[^}]*color:\\s*rgb\\(188, 162, 108\\)" }) + if (!Regex.IsMatch(common, rule)) throw new Exception("CommonStyle no longer matches " + rule); + // A caption's yellow wins over its size class: text--yellow comes after the size classes in the same sheet. + if (common.IndexOf(".text--yellow", StringComparison.Ordinal) < common.IndexOf(".game-text-title", StringComparison.Ordinal)) + throw new Exception("text--yellow now comes before the text size classes: a caption would lose its yellow"); + }); + } + + static IEnumerable Types(Type type) => new[] { type }.Concat(type.GetNestedTypes(All).SelectMany(Types)); + + static ZipArchive UiZip(string managedPath) + { + string path = Path.GetFullPath(Path.Combine(managedPath, "..", "StreamingAssets", "Modding", "UI.zip")); + if (!File.Exists(path)) throw new Exception("the game's UI.zip is not at " + path); + return ZipFile.OpenRead(path); + } + + static string Read(ZipArchive zip, string entry) + { + ZipArchiveEntry file = zip.GetEntry(entry) ?? throw new Exception("UI.zip has no " + entry); + using var reader = new StreamReader(file.Open()); + return reader.ReadToEnd(); + } +} diff --git a/StabilityTests/Rc27Checks.cs b/StabilityTests/Rc27Checks.cs index 3d5dad6..4cbc37a 100644 --- a/StabilityTests/Rc27Checks.cs +++ b/StabilityTests/Rc27Checks.cs @@ -16,6 +16,19 @@ static string Source(params string[] parts) return File.ReadAllText(Path.Combine(new[] { root! }.Concat(parts).ToArray())).Replace("\r\n", "\n"); } + static string Body(string text, string signature) + { + int start = text.IndexOf(signature, StringComparison.Ordinal); + Check(start >= 0, "not found: " + signature); + int open = text.IndexOf('{', start), depth = 0; + for (int i = open; i < text.Length; i++) + { + if (text[i] == '{') depth++; + else if (text[i] == '}' && --depth == 0) return text.Substring(start, i - start + 1); + } + throw new Exception("unbalanced braces after " + signature); + } + public static IEnumerable<(string Name, Action Run)> Tests() { yield return ("rc27: another colony's cutting marks are hidden only from the game's interface, never from the simulation", () => @@ -208,5 +221,26 @@ static string Source(params string[] parts) Check(source.Contains("int[] before = (int[])records.Clone();") && source.Contains("&& WellbeingRecords.Announces(before[slot])) Announce(records[slot]);"), "the first record is announced"); }); + yield return ("rc31: the trading posts window names only the game UI's classes it lists, and none of the entity panel's", () => + { + string window = Source("BeaverBuddies", "Colonies", "TradeOverviewPanel.cs"); + int start = window.IndexOf("public static readonly string[] ClassesUsed", StringComparison.Ordinal); + Check(start >= 0, "the window no longer lists its classes"); + string listed = window.Substring(start, window.IndexOf("};", start, StringComparison.Ordinal) - start); + // Every class the window adds or builds a box of is listed (RuntimeChecks holds the list to the game's sheets). + foreach (System.Text.RegularExpressions.Match m in System.Text.RegularExpressions.Regex.Matches(window, + "(?:AddToClassList|Box)\\(\"([^\"]+)\"\\)")) + Check(listed.Contains("\"" + m.Groups[1].Value + "\""), "the window uses " + m.Groups[1].Value + " without listing it"); + // The entity panel's sheet is not in a window: its classes (the red button, entity-panel__text's colour) draw nothing there. + foreach (string panelOnly in new[] { "NativeElements.RedButton(", "NativeElements.Caption(", "NativeElements.Section(", "entity-panel__", "entity-fragment__" }) + Check(!window.Contains(panelOnly), "the window relies on the entity panel's style sheet: " + panelOnly); + // Text takes its size and colour from the game's classes, not colours set on it (only the warning and muted ones). + Check(!window.Contains("Color.white") && !window.Contains("style.fontSize"), "the window sets a text colour or size of its own"); + // Outside an entity panel the mod's text and buttons still have the game's light grey. + string native = Body(Source("BeaverBuddies", "Util", "NativeElements.cs"), "public static Label Text("); + Check(native.Contains("label.AddToClassList(TextNormal);"), "the mod's text has no colour outside an entity panel"); + Check(Body(Source("BeaverBuddies", "Util", "NativeElements.cs"), "private static Button TextButton(").Contains("button.AddToClassList(TextNormal);"), + "the mod's buttons have no text colour outside an entity panel"); + }); } } From e4d56ba8951d2bd6713cae957c1bb1f2d8ba34c8 Mon Sep 17 00:00:00 2001 From: Kyler Ramsey Date: Tue, 29 Sep 2026 13:18:54 -0700 Subject: [PATCH 5/5] Changelog: the colonies window design pass Co-Authored-By: Claude Opus 5.5 --- STABILITY-CHANGELOG.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/STABILITY-CHANGELOG.md b/STABILITY-CHANGELOG.md index 4f5ad0f..91ad4d1 100644 --- a/STABILITY-CHANGELOG.md +++ b/STABILITY-CHANGELOG.md @@ -31,6 +31,19 @@ colonies window** (built against Timberborn 1.1.2.4). **Not played.** and hands it to the graphs (`GoodStatisticsGroupFactory.Create`, `PopulationStatisticsGraphFactory.Create`). The game's saved global registries are only read. A deleted district's days drop out, as its history goes with it. Faction unlocks are now the only map-wide figure a player sees. +- **The Trading Posts and colonies window (Y) looks like the game's own windows.** It was written without the + game's files. Checked against the game's UXML and USS (`StreamingAssets/Modding/UI.zip`): the window hangs in the + interface's `Absolute-items`, where only `GameUI.uxml`'s style sheets reach, so two entity-panel classes it relied on + drew nothing: `entity-panel__text` (every label and button text fell back to the theme's dark default; this was the + dark text seen in play) and `entity-fragment__button--red` (the Clear button had no red). It now uses only classes + those sheets define, matched to the game's well-being window and batch control rows: the named box's frame, + capsule title and close button, `game-scroll-view`, the green row boards, `game-text-small/normal/big/heading` and + `text--yellow` for counts and captions, and wooden `button-game` buttons. Text is the game's light grey; the box is + 540 wide with the game's own 45 px padding; rows use the entity panel's 8/12 px padding; a colony's buttons sit in a + wrapping row under its text instead of a column squeezing it; food and water keep their icon and amount together; + another colony's wishes are plain tiles instead of buttons that did nothing. `NativeElements` text and buttons also + carry `game-text-normal`, which fixes the same dark text on a trade message's button and in the goods grid opened + from the window. RuntimeChecks reads UI.zip and fails if the window names a class those sheets don't define. ## 1.4.0-rc30