public void Test1() { var list = new WeightedList <BasicClass>(); list.Add(new BasicClass("a")); list.Add(new BasicClass("b")); list.Add(new BasicClass("c")); Assert.Equal(0, list.IndexOf(c => c.Name == "a")); Assert.Equal(1, list.IndexOf(c => c.Name == "b")); Assert.Equal(2, list.IndexOf(c => c.Name == "c")); var n = list.Get(c => c.Name == "a"); list.CheckConsistency(); Assert.Equal("a", n.Name); n = list.Get(c => c.Name == "c"); list.CheckConsistency(); Assert.Equal(1, list.IndexOf(n)); n = list.Get(c => c.Name == "c"); list.CheckConsistency(); Assert.Equal(0, list.IndexOf(n)); n = list.Get(c => c.Name == "c"); list.CheckConsistency(); n = list.Get(c => c.Name == "c"); list.CheckConsistency(); Assert.Equal(0, list.IndexOf(n)); }
private void ReadPhonotactics(string filePath) { XmlDocument xml = new XmlDocument(); xml.Load(filePath); foreach (XmlNode node in xml.SelectNodes("Phonotactics/Constraint")) { string definition = node.Attributes.GetNamedItem("Definition").Value; FieldInfo field = GetType().GetField(definition); if (field != null) { WeightedList <Phonotactics> constraint = (WeightedList <Phonotactics>)field.GetValue(this); double forbiddenWeight = double.Parse(node.Attributes.GetNamedItem("Forbidden").Value, CultureInfo.InvariantCulture); double optionalWeight = double.Parse(node.Attributes.GetNamedItem("Optional").Value, CultureInfo.InvariantCulture); double requiredWeight = double.Parse(node.Attributes.GetNamedItem("Required").Value, CultureInfo.InvariantCulture); constraint.Add(Phonotactics.Forbidden, forbiddenWeight); constraint.Add(Phonotactics.Optional, optionalWeight); constraint.Add(Phonotactics.Required, requiredWeight); } else { Console.WriteLine("Error: " + definition + " not implemented"); } } }
private void AddCodae(IEnumerable <Consonant> consonants, double baseWeight, double weightMultiplier, Random rng) { foreach (Consonant consonant in consonants) { double weight = baseWeight + rng.NextDouble() * weightMultiplier; Codae.Add(consonant, weight); } }
public void RemoveEntries_PreserveAtZero_LeaveNone_GetExpectedOrderAndWeights() { var weightedList = new WeightedList<string>(); weightedList.Add("A"); weightedList.Add("B"); weightedList.Add("C"); weightedList.Add("A"); weightedList.Add("B"); weightedList.Add("C"); weightedList.Add("A"); weightedList.Add("B"); weightedList.Remove("A", false); weightedList.Remove("A", false); weightedList.Remove("A", false); List<string> list = weightedList.ToSortedList(); Assert.AreEqual(3, weightedList.Count); Assert.AreEqual(3, list.Count); Assert.AreEqual("A", list[0]); Assert.AreEqual("C", list[1]); Assert.AreEqual("B", list[2]); Assert.AreEqual("A", weightedList.GetMinWeight()); Assert.AreEqual("B", weightedList.GetMaxWeight()); }
private void AddNuclei(IEnumerable <Vowel> vowels, double baseWeight, double weightMultiplier, Random rng) { foreach (Vowel vowel in vowels) { double weight = baseWeight + rng.NextDouble() * weightMultiplier; Nuclei.Add(vowel, weight); } }
private void PortToSaneSystem(List <SpawnSystem.SpawnData> spawners) { foreach (var spawner in spawners) { var weightedSpawnData = new WeightedSpawnData(spawner); Spawners.Add(weightedSpawnData); } }
public void GlobalSetup() { for (int i = 0; i < 500; i++) { var a = new BasicClass(i.ToString()); _listA.Add(a); _listB.Add(a); } }
private void Test() { _output.text = string.Empty; // Fill weighted list with items and weights: _items.Add(ItemsWithWeights.Item1, (float)ItemsWithWeights.Item1); _items.Add(ItemsWithWeights.Item2, (float)ItemsWithWeights.Item2); _items.Add(ItemsWithWeights.Item3, (float)ItemsWithWeights.Item3); _items.Add(ItemsWithWeights.Item4, (float)ItemsWithWeights.Item4); //Prepare container for results: Dictionary <ItemsWithWeights, int> results = new Dictionary <ItemsWithWeights, int>(); results.Add(ItemsWithWeights.Item1, 0); results.Add(ItemsWithWeights.Item2, 0); results.Add(ItemsWithWeights.Item3, 0); results.Add(ItemsWithWeights.Item4, 0); // Begin test: ItemsWithWeights currentResult; for (int i = 0; i < _attempts; i++) { // Get item currentResult = _items.GetRandomByWeight(); // Save result results[currentResult]++; } // Log results: string message = "Weighted list test. " + _attempts + " attempts: "; Debug.Log(message); _output.text += message + System.Environment.NewLine; foreach (var key in results.Keys) { message = "Item " + key.ToString() + " with weight " + ((float)key) + " occurs " + results[key] + " times"; _output.text += message + System.Environment.NewLine; Debug.Log(message); } }
private void SelectWordLengths(ProceduralLanguageFactory factory) { Random rng = factory.RNG; double complexityModifier = Math.Log(SyllableComplexity); double bias = 20 / complexityModifier * (1 + (rng.NextDouble() - rng.NextDouble() / 4)); for (int i = 1; i < 6; i++) { WordLengths.Add(i, 1 / (0.5 + Math.Pow(Math.Abs(bias - i), 1.1))); } }
private void SelectAttack(SnakeHydra head) { var weightedList = new WeightedList <Snake.Action>(); weightedList.Add(new Snake.ActionIdle(head), 30); Vector2 dist = Target.Position - Position; if (Heads.Count(x => x.CurrentAction is Snake.ActionBite) < 2 && dist.LengthSquared() < 90 * 90) { weightedList.Add(new Snake.ActionBite(head, 60 + Random.Next(60), 20, 60 + Random.Next(60)), 50); } if (Heads.Count(x => x.CurrentAction is Snake.ActionSpit) < 1) { weightedList.Add(new Snake.ActionSpit(head, Target, new Vector2(0, -70), 60, 20, 20, 20), 30); } if (Heads.Count(x => x.CurrentAction is Snake.ActionBreath) < 1 && Math.Abs(dist.X) < 100) { weightedList.Add(new Snake.ActionBreath(head, Target, 80, 120, 60), 30); } head.CurrentAction = weightedList.GetWeighted(Random); }
public void Test2() { var list = new WeightedList <BasicClass>().AddComparator((a, b) => a.Value.Value - b.Value.Value); list.Add(new BasicClass("a") { Value = 0 }); list.Add(new BasicClass("b") { Value = 0 }); list.Add(new BasicClass("c") { Value = 1 }); Assert.Equal(1, list.IndexOf(c => c.Name == "a")); Assert.Equal(2, list.IndexOf(c => c.Name == "b")); Assert.Equal(0, list.IndexOf(c => c.Name == "c")); }
private static WeightedList<T> ProcessButtons<T>(WeightedList<T> list, int indexToRemove) { if (indexToRemove != -1) { list.RemoveAt(indexToRemove); } if (GUILayout.Button("Add")) { Debug.Log("Add " + default(T)); list.Add(default(T), 0f); } return list; }
private static WeightedList <SimGameState.ContractParticipants> GenerateContractParticipants(FactionDef employer, StarSystemDef system, List <string> opFor) { var weightedList1 = new WeightedList <SimGameState.ContractParticipants>(WeightedListType.PureRandom); var enemies = opFor?.Count > 0 ? opFor : system.contractTargetIDs.Except(employer.Allies).Except(Globals.Sim.GetAllCareerAllies()); var neutrals = FactionEnumeration.PossibleNeutralToAllList.Where(f => !employer.FactionValue.Equals(f) && !Globals.Sim.IgnoredContractTargets.Contains(f.Name)).ToList(); var hostiles = FactionEnumeration.PossibleHostileToAllList.Where(f => !employer.FactionValue.Equals(f) && !Globals.Sim.IgnoredContractTargets.Contains(f.Name)).ToList(); var allies = FactionEnumeration.PossibleAllyFallbackList.Where(f => !employer.FactionValue.Equals(f) && !Globals.Sim.IgnoredContractTargets.Contains(f.Name)).ToList(); foreach (var str in enemies) { var target = str; var targetFactionDef = Globals.Sim.factions[target]; var mercenariesFactionValue = FactionEnumeration.GetHostileMercenariesFactionValue(); var defaultHostileFaction = Globals.Sim.GetDefaultHostileFaction(employer.FactionValue, targetFactionDef.FactionValue); var defaultTargetAlly = allies.Where(f => !targetFactionDef.Enemies.Contains(f.Name) && !employer.Allies.Contains(f.Name) && target != f.Name).DefaultIfEmpty(targetFactionDef.FactionValue).GetRandomElement(Globals.Sim.NetworkRandom); var randomElement = allies.Where(f => !employer.Enemies.Contains(f.Name) && !targetFactionDef.Allies.Contains(f.Name) && defaultTargetAlly != f && target != f.Name).DefaultIfEmpty(employer.FactionValue).GetRandomElement(Globals.Sim.NetworkRandom); var weightedList2 = targetFactionDef.Allies.Select(FactionEnumeration.GetFactionByName).Where(f => !employer.Allies.Contains(f.Name) && !Globals.Sim.IgnoredContractTargets.Contains(f.Name)).DefaultIfEmpty(defaultTargetAlly).ToWeightedList(WeightedListType.PureRandom); var weightedList3 = employer.Allies.Select(FactionEnumeration.GetFactionByName).Where(f => !targetFactionDef.Allies.Contains(f.Name) && !Globals.Sim.IgnoredContractTargets.Contains(f.Name)).DefaultIfEmpty(randomElement).ToWeightedList(WeightedListType.PureRandom); var list2 = neutrals.Where(f => target != f.Name && !targetFactionDef.Enemies.Contains(f.Name) && !employer.Enemies.Contains(f.Name)).DefaultIfEmpty(mercenariesFactionValue).ToList(); var list3 = hostiles.Where(f => target != f.Name && !targetFactionDef.Allies.Contains(f.Name) && !employer.Allies.Contains(f.Name)).DefaultIfEmpty(defaultHostileFaction).ToList(); weightedList1.Add(new SimGameState.ContractParticipants(targetFactionDef.FactionValue, weightedList2, weightedList3, list2, list3)); } return(weightedList1); }
private List <Vector2> CreatePointOnBounds(int amount) { WeightedList <WeightedElement <Directions>, Directions> borderWeights = new WeightedList <WeightedElement <Directions>, Directions>(); // Add 8 valid directions to the weighted list. For now 8 streets max are possible borderWeights.Add(new WeightedElement <Directions>(Directions.North, 1)); borderWeights.Add(new WeightedElement <Directions>(Directions.East, 1)); borderWeights.Add(new WeightedElement <Directions>(Directions.South, 1)); borderWeights.Add(new WeightedElement <Directions>(Directions.West, 1)); borderWeights.Add(new WeightedElement <Directions>(Directions.North, 1)); borderWeights.Add(new WeightedElement <Directions>(Directions.East, 1)); borderWeights.Add(new WeightedElement <Directions>(Directions.South, 1)); borderWeights.Add(new WeightedElement <Directions>(Directions.West, 1)); List <Vector2> pointOnBounds = new List <Vector2>(); for (int i = 0; i < amount; i++) { var rnd = FloatGenerator.Generate(); var direction = borderWeights.GetElement(rnd); var rnd1 = FloatGenerator.Generate(); switch (direction) { case Directions.North: pointOnBounds.Add(new Vector2(rnd1, 1f)); break; case Directions.East: pointOnBounds.Add(new Vector2(1f, rnd1)); break; case Directions.South: pointOnBounds.Add(new Vector2(rnd1, 0f)); break; case Directions.West: pointOnBounds.Add(new Vector2(0f, rnd1)); break; } } return(pointOnBounds); }
public IWeightedList <ConcreteSpecimen> Build(int sizeOfStarterPopulation) { var random = new Random(); var result = new WeightedList <ConcreteSpecimen>(sizeOfStarterPopulation); // We generate the population around a random epicenter... var epicenter = -1.5d + random.NextDouble() * 3; for (var i = 0; i < sizeOfStarterPopulation; i++) { var cell = new ConcreteSpecimen(epicenter + (-2 + random.NextDouble() * 4)); result.Add(new WeightedItem <ConcreteSpecimen>(cell, 0)); } return(result); }
void Awake() { weightedSpawnables = new WeightedList <Spawnable>(); foreach (Spawnable s in Spawnables) { weightedSpawnables.Add(s, s.weight); } WorldContainer = new GameObject("WorldContainer"); WorldContainer.transform.parent = transform; Terrain = GetComponentInChildren <Terrain>(); bounds = TerrainUtils.GetTerrainBounds(Terrain); positions = new List <ObjectLocation>(); }
static void Postfix(JobApplicant __instance, WeightedList <QualificationDefinition> qualifications) { if (!Main.enabled || Main.InInitialisePools || Main.settings.RespecFutureApplicants == 0) { return; } Main.qualifications.Process(qualifications); WeightedList <string> buildlist = new WeightedList <string>(); foreach (KeyValuePair <string, int> item in statistics[__instance.Definition._type]) { buildlist.Add(item.Key, item.Value); } Main.ProcessJobApplicant(ref __instance, buildlist.Choose(null, RandomUtils.GlobalRandomInstance)); }
/* * public static void EditAssetObject<TAssetsLib,TAsset>(TAssetsLib assetsLib,TAssetsLib) * { * * }*/ public static void EditWeightedList(string label, bool show, WeightedList list) { DrawFoldList(label, show, list.Count, (i) => { EditorGUILayout.BeginHorizontal(); list[i].Object = EditorGUILayout.ObjectField(list[i].Object, typeof(UnityEngine.Object), true); list[i].Weight = EditorGUILayout.FloatField(list[i].Weight); if (GUILayout.Button("-")) { list.RemoveAt(i); } EditorGUILayout.EndHorizontal(); }, () => { list.Add(new WeightedItem(null, 1)); }); }
public void AddEntries_GetExpectedOrderAndWeights() { var weightedList = new WeightedList<string>(); weightedList.Add("A"); weightedList.Add("B"); weightedList.Add("C"); weightedList.Add("A"); weightedList.Add("B"); weightedList.Add("A"); List<string> list = weightedList.ToSortedList(); Assert.AreEqual(3, weightedList.Count); Assert.AreEqual(3, list.Count); Assert.AreEqual("C", list[0]); Assert.AreEqual("B", list[1]); Assert.AreEqual("A", list[2]); Assert.AreEqual("C", weightedList.GetMinWeight()); Assert.AreEqual("A", weightedList.GetMaxWeight()); }
public void UpdateAI() { var viewSize = new Vector2(200, 50); RectangleF viewArea = new RectangleF(Position - viewSize / 2, viewSize); if (viewArea.Contains(World.Player.Position)) { Target = World.Player; TargetTime = 200; } else { TargetTime--; if (TargetTime <= 0) { Target = null; } } if (Target != null) //Engaged { if (CurrentAction is ActionHit) { } else if (CurrentAction is ActionEnemyDeath) { } else if (CurrentAction is ActionJump) { } else if (CurrentAction is ActionClimb) { OnWall = false; } else { foreach (var weaponAI in GetWeaponAIs(Weapon)) { weaponAI.Update(this); } if (DifferenceVector.X < 0) { Owner.Facing = HorizontalFacing.Left; } else if (DifferenceVector.X > 0) { Owner.Facing = HorizontalFacing.Right; } float preferredDistanceMin = 20; float preferredDistanceMax = 30; if (Target.Invincibility > 0) { preferredDistanceMin = 30; preferredDistanceMax = 40; } if (Target.InAir) { preferredDistanceMin = 40; preferredDistanceMax = 50; } if (CurrentAction is ActionMove move) { move.WalkingLeft = false; move.WalkingRight = false; } if (Math.Abs(DifferenceVector.X) > preferredDistanceMax) { Owner.WalkConstrained(DifferenceVector.X); } if (Math.Abs(DifferenceVector.X) < preferredDistanceMin) { Owner.WalkConstrained(-DifferenceVector.X); } } AttackCooldown--; RangedCooldown--; } else //Idle { IdleTime--; switch (Idle) { case (IdleState.Wait): break; case (IdleState.MoveLeft): Owner.Facing = HorizontalFacing.Left; Owner.WalkConstrained(-1); break; case (IdleState.MoveRight): Owner.Facing = HorizontalFacing.Right; Owner.WalkConstrained(1); break; } if (OnWall) { if (Idle == IdleState.MoveLeft) { Idle = IdleState.MoveRight; } else if (Idle == IdleState.MoveRight) { Idle = IdleState.MoveLeft; } OnWall = false; IdleTime = 70; } if (IdleTime <= 0) { WeightedList <IdleState> nextState = new WeightedList <IdleState>(); nextState.Add(IdleState.Wait, 30); nextState.Add(IdleState.MoveLeft, 70); nextState.Add(IdleState.MoveRight, 70); IdleTime = Owner.Random.Next(50) + 20; Idle = nextState.GetWeighted(Owner.Random); } } }
public void TestExport() { WeightedList <AtmosphericGasSD> atmoGases = new WeightedList <AtmosphericGasSD>(); AtmosphericGasSD gas = new AtmosphericGasSD(); gas.BoilingPoint = 100; gas.MeltingPoint = 0; gas.ChemicalSymbol = "H20"; gas.Name = "Water"; gas.IsToxic = false; atmoGases.Add(1.0, gas); gas.BoilingPoint = 100; gas.MeltingPoint = 0; gas.ChemicalSymbol = "H2O"; gas.Name = "Water Second take"; gas.IsToxic = false; atmoGases.Add(1.0, gas); StaticDataManager.ExportStaticData(atmoGases, "AtmoGasesExportTest.json"); List <CommanderNameThemeSD> nameThemes = new List <CommanderNameThemeSD>(); CommanderNameThemeSD nameTheme = new CommanderNameThemeSD(); nameTheme.NameList = new List <CommanderNameSD>(); nameTheme.ThemeName = "The Creators"; CommanderNameSD name = new CommanderNameSD(); name.First = "Greg"; name.Last = "Nott"; name.IsFemale = false; nameTheme.NameList.Add(name); name.First = "Rod"; name.Last = "Serling"; name.IsFemale = false; nameTheme.NameList.Add(name); nameThemes.Add(nameTheme); StaticDataManager.ExportStaticData(nameThemes, "CommanderNameThemeExportTest.json"); StaticDataManager.ExportStaticData(VersionInfo.PulsarVersionInfo, "VersionInfoExportTest.vinfo"); List <MineralSD> minList = new List <MineralSD>(); MineralSD min = new MineralSD(); min.Abundance = new Dictionary <BodyType, double>(); min.Abundance.Add(BodyType.Asteroid, 0.01); min.Abundance.Add(BodyType.Comet, 0.05); min.Abundance.Add(BodyType.DwarfPlanet, 0.075); min.Abundance.Add(BodyType.GasDwarf, 0.1); min.Abundance.Add(BodyType.GasGiant, 1.0); min.Abundance.Add(BodyType.IceGiant, 0.5); min.Abundance.Add(BodyType.Moon, 0.5); min.Abundance.Add(BodyType.Terrestrial, 1.0); min.ID = Guid.NewGuid(); min.Name = "Sorium"; min.Description = "des"; minList.Add(min); StaticDataManager.ExportStaticData(minList, "MineralsExportTest.json"); //Dictionary<ID, TechSD> techs = Tech(); //TechSD tech1 = new TechSD(); //tech1.Name = "Trans-Newtonian Technology"; //tech1.Requirements = new Dictionary<ID, int>(); //tech1.Description = "Unlocks almost all other technology."; //tech1.Cost = 1000; //tech1.Category = ResearchCategories.ConstructionProduction; //tech1.ID = ID.NewGuid(); //TechSD tech2 = new TechSD(); //tech2.Name = "Construction Rate"; //tech2.Requirements = new Dictionary<ID, int>(); //tech2.Requirements.Add(tech1.ID, 0); //tech2.Description = "Boosts Construction Rate by 12 BP"; //tech2.Cost = 3000; //tech2.Category = ResearchCategories.ConstructionProduction; //tech2.ID = ID.NewGuid(); //techs.Add(tech1.ID, tech1); //techs.Add(tech2.ID, tech2); //StaticDataManager.ExportStaticData(techs, "./TechnologyDataExportTest.json"); //InstallationSD install = new InstallationSD(); //install.Name = "Mine"; //install.Description = "Employs population to mine transnewtonian resources."; //install.PopulationRequired = 1; //install.CargoSize = 1; //install.BaseAbilityAmounts = new Dictionary<AbilityType, int>(); //install.BaseAbilityAmounts.Add(AbilityType.Mine, 1); //install.TechRequirements = new List<ID>(); //install.TechRequirements.Add(tech1.ID); //use trans-newtonian techology you just added to the tech list //install.ResourceCosts = new Dictionary<ID, int>(); //install.ResourceCosts.Add(min.ID,60); //use Sorium that you just added to the mineral list //install.WealthCost = 120; //install.BuildPoints = 120; //installations.Add(install); //ComponentAbilitySD launchAbility = new ComponentAbilitySD(); //launchAbility.Ability = AbilityType.LaunchMissileSize; //launchAbility.AbilityAmount = new List<float>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; //launchAbility.CrewAmount = new List<float>() { 3, 6, 9, 12, 15, 18, 21, 24, 27, 30}; ////launchAbility.ID = ID.NewGuid(); //launchAbility.Name = "Missile Launcher Size"; //launchAbility.Description = "Can fire a missile of this size or smaller"; //launchAbility.WeightAmount = new List<float>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //launchAbility.TechRequirements = new List<ID>() { }; //ComponentAbilitySD reloadAbility = new ComponentAbilitySD(); //reloadAbility.Name = "Missile Launcher Reload Rate"; //reloadAbility.Description = "Speed at which this launcher can reload from a magazine"; ////reloadAbility.ID = ID.NewGuid(); //reloadAbility.Ability = AbilityType.ReloadRateFromMag; //reloadAbility.AbilityAmount = new List<float>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; //reloadAbility.CrewAmount = new List<float>() { }; //ComponentSD missileLauncher = new ComponentSD(); //missileLauncher.ComponentAbilitySDs = new List<ComponentAbilitySD>() { launchAbility, reloadAbility}; //missileLauncher.Name = "MissileLauncher"; //missileLauncher.Description = "Can launch Missiles and be reloaded via a magazine"; //missileLauncher.ID = ID.NewGuid(); ////StaticDataManager.ExportStaticData(launchAbility, "./launcherabilitytest.json"); ////StaticDataManager.ExportStaticData(reloadAbility, "./launcherabilitytest.json"); //Dictionary<ID, ComponentSD> components = new Dictionary<ID, ComponentSD>(); //components.Add(missileLauncher.ID, missileLauncher); //StaticDataManager.ExportStaticData(components, "./Componentstest.json"); // test export of galaxy settings: GalaxyFactory gf = new GalaxyFactory(true, 1); StaticDataManager.ExportStaticData(gf.Settings, "SystemGenSettings.json"); }
public void Add(Card card) { cards.Add(card); }
public static Contract GetNewWarContract(SimGameState Sim, int Difficulty, Faction emp, Faction targ, StarSystem system) { if (Difficulty <= 1) { Difficulty = 2; } else if (Difficulty > 9) { Difficulty = 9; } ContractDifficulty minDiffClamped = (ContractDifficulty)AccessTools.Method(typeof(SimGameState), "GetDifficultyEnumFromValue").Invoke(Sim, new object[] { Difficulty }); ContractDifficulty maxDiffClamped = (ContractDifficulty)AccessTools.Method(typeof(SimGameState), "GetDifficultyEnumFromValue").Invoke(Sim, new object[] { Difficulty }); List <Contract> contractList = new List <Contract>(); int maxContracts = 1; int debugCount = 0; while (contractList.Count < maxContracts && debugCount < 1000) { WeightedList <MapAndEncounters> contractMaps = new WeightedList <MapAndEncounters>(WeightedListType.SimpleRandom, null, null, 0); List <ContractType> contractTypes = new List <ContractType>(); Dictionary <ContractType, List <ContractOverride> > potentialOverrides = new Dictionary <ContractType, List <ContractOverride> >(); AccessTools.Field(typeof(SimGameState), "singlePlayerTypes"); ContractType[] singlePlayerTypes = (ContractType[])AccessTools.Field(typeof(SimGameState), "singlePlayerTypes").GetValue(Sim); using (MetadataDatabase metadataDatabase = new MetadataDatabase()) { foreach (Contract_MDD contract_MDD in metadataDatabase.GetContractsByDifficultyRange(Difficulty - 1, Difficulty + 1)) { ContractType contractType = contract_MDD.ContractTypeEntry.ContractType; if (singlePlayerTypes.Contains(contractType)) { if (!contractTypes.Contains(contractType)) { contractTypes.Add(contractType); } if (!potentialOverrides.ContainsKey(contractType)) { potentialOverrides.Add(contractType, new List <ContractOverride>()); } ContractOverride item = Sim.DataManager.ContractOverrides.Get(contract_MDD.ContractID); potentialOverrides[contractType].Add(item); } } foreach (MapAndEncounters element in metadataDatabase.GetReleasedMapsAndEncountersByContractTypeAndTags(singlePlayerTypes, system.Def.MapRequiredTags, system.Def.MapExcludedTags, system.Def.SupportedBiomes)) { if (!contractMaps.Contains(element)) { contractMaps.Add(element, 0); } } } if (contractMaps.Count == 0) { Logger.LogLine("Maps0 break"); break; } if (potentialOverrides.Count == 0) { Logger.LogLine("Overrides0 break"); break; } contractMaps.Reset(false); WeightedList <Faction> validEmployers = new WeightedList <Faction>(WeightedListType.SimpleRandom, null, null, 0); Dictionary <Faction, WeightedList <Faction> > validTargets = new Dictionary <Faction, WeightedList <Faction> >(); int i = debugCount; debugCount = i + 1; WeightedList <MapAndEncounters> activeMaps = new WeightedList <MapAndEncounters>(WeightedListType.SimpleRandom, contractMaps.ToList(), null, 0); List <MapAndEncounters> discardedMaps = new List <MapAndEncounters>(); List <string> mapDiscardPile = (List <string>)AccessTools.Field(typeof(SimGameState), "mapDiscardPile").GetValue(Sim); for (int j = activeMaps.Count - 1; j >= 0; j--) { if (mapDiscardPile.Contains(activeMaps[j].Map.MapID)) { discardedMaps.Add(activeMaps[j]); activeMaps.RemoveAt(j); } } if (activeMaps.Count == 0) { mapDiscardPile.Clear(); foreach (MapAndEncounters element2 in discardedMaps) { activeMaps.Add(element2, 0); } } activeMaps.Reset(false); MapAndEncounters level = null; List <EncounterLayer_MDD> validEncounters = new List <EncounterLayer_MDD>(); Dictionary <ContractType, WeightedList <PotentialContract> > validContracts = new Dictionary <ContractType, WeightedList <PotentialContract> >(); WeightedList <PotentialContract> flatValidContracts = null; do { level = activeMaps.GetNext(false); if (level == null) { break; } validEncounters.Clear(); validContracts.Clear(); flatValidContracts = new WeightedList <PotentialContract>(WeightedListType.WeightedRandom, null, null, 0); foreach (EncounterLayer_MDD encounterLayer_MDD in level.Encounters) { ContractType contractType2 = encounterLayer_MDD.ContractTypeEntry.ContractType; if (contractTypes.Contains(contractType2)) { if (validContracts.ContainsKey(contractType2)) { validEncounters.Add(encounterLayer_MDD); } else { foreach (ContractOverride contractOverride2 in potentialOverrides[contractType2]) { bool flag = true; ContractDifficulty difficultyEnumFromValue = (ContractDifficulty)AccessTools.Method(typeof(SimGameState), "GetDifficultyEnumFromValue").Invoke(Sim, new object[] { contractOverride2.difficulty }); Faction employer2 = Faction.INVALID_UNSET; Faction target2 = Faction.INVALID_UNSET; if (difficultyEnumFromValue >= minDiffClamped && difficultyEnumFromValue <= maxDiffClamped) { employer2 = emp; target2 = targ; int difficulty = Sim.NetworkRandom.Int(Difficulty, Difficulty + 1); system.SetCurrentContractFactions(employer2, target2); int k = 0; while (k < contractOverride2.requirementList.Count) { RequirementDef requirementDef = new RequirementDef(contractOverride2.requirementList[k]); EventScope scope = requirementDef.Scope; TagSet curTags; StatCollection stats; switch (scope) { case EventScope.Company: curTags = Sim.CompanyTags; stats = Sim.CompanyStats; break; case EventScope.MechWarrior: case EventScope.Mech: goto IL_88B; case EventScope.Commander: goto IL_8E9; case EventScope.StarSystem: curTags = system.Tags; stats = system.Stats; break; default: goto IL_88B; } IL_803: for (int l = requirementDef.RequirementComparisons.Count - 1; l >= 0; l--) { ComparisonDef item2 = requirementDef.RequirementComparisons[l]; if (item2.obj.StartsWith("Target") || item2.obj.StartsWith("Employer")) { requirementDef.RequirementComparisons.Remove(item2); } } if (!SimGameState.MeetsRequirements(requirementDef, curTags, stats, null)) { flag = false; break; } k++; continue; IL_88B: if (scope != EventScope.Map) { throw new Exception("Contracts cannot use the scope of: " + requirementDef.Scope); } using (MetadataDatabase metadataDatabase2 = new MetadataDatabase()) { curTags = metadataDatabase2.GetTagSetForTagSetEntry(level.Map.TagSetID); stats = new StatCollection(); goto IL_803; } IL_8E9: curTags = Sim.CommanderTags; stats = Sim.CommanderStats; goto IL_803; } if (flag) { PotentialContract element3 = default(PotentialContract); element3.contractOverride = contractOverride2; element3.difficulty = difficulty; element3.employer = employer2; element3.target = target2; validEncounters.Add(encounterLayer_MDD); if (!validContracts.ContainsKey(contractType2)) { validContracts.Add(contractType2, new WeightedList <PotentialContract>(WeightedListType.WeightedRandom, null, null, 0)); } validContracts[contractType2].Add(element3, contractOverride2.weight); flatValidContracts.Add(element3, contractOverride2.weight); } } } } } } }while (validContracts.Count == 0 && level != null); system.SetCurrentContractFactions(Faction.INVALID_UNSET, Faction.INVALID_UNSET); if (validContracts.Count == 0) { if (mapDiscardPile.Count > 0) { mapDiscardPile.Clear(); } else { debugCount = 1000; Logger.LogLine(string.Format("[CONTRACT] Unable to find any valid contracts for available map pool. Alert designers.", new object[0])); } } else { GameContext gameContext = new GameContext(Sim.Context); gameContext.SetObject(GameContextObjectTagEnum.TargetStarSystem, system); Dictionary <ContractType, List <EncounterLayer_MDD> > finalEncounters = new Dictionary <ContractType, List <EncounterLayer_MDD> >(); foreach (EncounterLayer_MDD encounterLayer_MDD2 in validEncounters) { ContractType contractType3 = encounterLayer_MDD2.ContractTypeEntry.ContractType; if (!finalEncounters.ContainsKey(contractType3)) { finalEncounters.Add(contractType3, new List <EncounterLayer_MDD>()); } finalEncounters[contractType3].Add(encounterLayer_MDD2); } List <PotentialContract> discardedContracts = new List <PotentialContract>(); List <string> contractDiscardPile = (List <string>)AccessTools.Field(typeof(SimGameState), "contractDiscardPile").GetValue(Sim); for (int m = flatValidContracts.Count - 1; m >= 0; m--) { if (contractDiscardPile.Contains(flatValidContracts[m].contractOverride.ID)) { discardedContracts.Add(flatValidContracts[m]); flatValidContracts.RemoveAt(m); } } if ((float)discardedContracts.Count >= (float)flatValidContracts.Count * Sim.Constants.Story.DiscardPileToActiveRatio || flatValidContracts.Count == 0) { contractDiscardPile.Clear(); foreach (PotentialContract element4 in discardedContracts) { flatValidContracts.Add(element4, 0); } } PotentialContract next = flatValidContracts.GetNext(true); ContractType finalContractType = next.contractOverride.contractType; finalEncounters[finalContractType].Shuffle <EncounterLayer_MDD>(); string encounterGuid = finalEncounters[finalContractType][0].EncounterLayerGUID; ContractOverride contractOverride3 = next.contractOverride; Faction employer3 = next.employer; Faction target3 = next.target; int targetDifficulty = next.difficulty; Contract con = (Contract)AccessTools.Method(typeof(SimGameState), "CreateTravelContract").Invoke(Sim, new object[] { level.Map.MapName, level.Map.MapPath, encounterGuid, finalContractType, contractOverride3, gameContext, employer3, target3, employer3, false, targetDifficulty }); mapDiscardPile.Add(level.Map.MapID); contractDiscardPile.Add(contractOverride3.ID); Sim.PrepContract(con, employer3, target3, target3, level.Map.BiomeSkinEntry.BiomeSkin, con.Override.travelSeed, system); contractList.Add(con); } } if (debugCount >= 1000) { Logger.LogLine("Unable to fill contract list. Please inform AJ Immediately"); } return(contractList[0]); }
private static IEnumerator StartGeneratePotentialContractsRoutine(SimGameState instance, bool clearExistingContracts, Action onContractGenComplete, StarSystem systemOverride, bool useCoroutine) { if (useCoroutine) { yield return(new WaitForSeconds(0.2f)); } bool usingBreadcrumbs = systemOverride != null; StarSystem system; List <Contract> contractList; if (systemOverride != null) { system = systemOverride; contractList = instance.CurSystem.SystemBreadcrumbs; } else { system = instance.CurSystem; contractList = instance.CurSystem.SystemContracts; } if (clearExistingContracts) { contractList.Clear(); } int maxContracts; if (systemOverride != null) { maxContracts = instance.CurSystem.CurMaxBreadcrumbs; } else { maxContracts = Mathf.CeilToInt(system.CurMaxContracts); } int debugCount = 0; while (contractList.Count < maxContracts && debugCount < 1000) { if (usingBreadcrumbs) { List <StarSystem> listsys = instance.StarSystems; listsys.Shuffle <StarSystem>(); system = listsys[0]; } int globalDifficulty = system.Def.Difficulty + Mathf.FloorToInt(instance.GlobalDifficulty); int minDiff; int maxDiff; int contractDifficultyVariance = instance.Constants.Story.ContractDifficultyVariance; minDiff = Mathf.Max(1, globalDifficulty - contractDifficultyVariance); maxDiff = Mathf.Max(1, globalDifficulty + contractDifficultyVariance); ContractDifficulty minDiffClamped = (ContractDifficulty)ReflectionHelper.InvokePrivateMethode(instance, "GetDifficultyEnumFromValue", new object[] { minDiff }); ContractDifficulty maxDiffClamped = (ContractDifficulty)ReflectionHelper.InvokePrivateMethode(instance, "GetDifficultyEnumFromValue", new object[] { maxDiff }); WeightedList <MapAndEncounters> contractMaps = new WeightedList <MapAndEncounters>(WeightedListType.SimpleRandom, null, null, 0); List <ContractType> contractTypes = new List <ContractType>(); Dictionary <ContractType, List <ContractOverride> > potentialOverrides = new Dictionary <ContractType, List <ContractOverride> >(); ContractType[] singlePlayerTypes = (ContractType[])ReflectionHelper.GetPrivateStaticField(typeof(SimGameState), "singlePlayerTypes"); using (MetadataDatabase metadataDatabase = new MetadataDatabase()) { foreach (Contract_MDD contract_MDD in metadataDatabase.GetContractsByDifficultyRangeAndScope((int)minDiffClamped, (int)maxDiffClamped, instance.ContractScope)) { ContractType contractType = contract_MDD.ContractTypeEntry.ContractType; if (singlePlayerTypes.Contains(contractType)) { if (!contractTypes.Contains(contractType)) { contractTypes.Add(contractType); } if (!potentialOverrides.ContainsKey(contractType)) { potentialOverrides.Add(contractType, new List <ContractOverride>()); } ContractOverride item = instance.DataManager.ContractOverrides.Get(contract_MDD.ContractID); potentialOverrides[contractType].Add(item); } } foreach (MapAndEncounters element in metadataDatabase.GetReleasedMapsAndEncountersByContractTypeAndTags(singlePlayerTypes, system.Def.MapRequiredTags, system.Def.MapExcludedTags, system.Def.SupportedBiomes)) { if (!contractMaps.Contains(element)) { contractMaps.Add(element, 0); } } } if (contractMaps.Count == 0) { Debug.LogError(string.Format("No valid map for System {0}", system.Name)); if (onContractGenComplete != null) { onContractGenComplete(); } yield break; } if (potentialOverrides.Count == 0) { Debug.LogError(string.Format("No valid contracts queried for difficulties between {0} and {1}, with a SCOPE of {2}", minDiffClamped, maxDiffClamped, instance.ContractScope)); if (onContractGenComplete != null) { onContractGenComplete(); } yield break; } contractMaps.Reset(false); WeightedList <Faction> validEmployers = new WeightedList <Faction>(WeightedListType.SimpleRandom, null, null, 0); Dictionary <Faction, WeightedList <Faction> > validTargets = new Dictionary <Faction, WeightedList <Faction> >(); Dictionary <Faction, FactionDef> factions = (Dictionary <Faction, FactionDef>)ReflectionHelper.GetPrivateField(instance, "factions"); foreach (Faction faction in system.Def.ContractEmployers) { foreach (Faction faction2 in factions[faction].Enemies) { if (system.Def.ContractTargets.Contains(faction2)) { if (!validTargets.ContainsKey(faction)) { validTargets.Add(faction, new WeightedList <Faction>(WeightedListType.PureRandom, null, null, 0)); } validTargets[faction].Add(faction2, 0); } } if (validTargets.ContainsKey(faction)) { validTargets[faction].Reset(false); validEmployers.Add(faction, 0); } } validEmployers.Reset(false); if (validEmployers.Count <= 0 || validTargets.Count <= 0) { Debug.LogError(string.Format("Cannot find any valid employers or targets for system {0}", system)); } if (validTargets.Count == 0 || validEmployers.Count == 0) { SimGameState.logger.LogError(string.Format("There are no valid employers or employers for the system of {0}. Num valid employers: {1}", system.Name, validEmployers.Count)); foreach (Faction faction3 in validTargets.Keys) { SimGameState.logger.LogError(string.Format("--- Targets for {0}: {1}", faction3, validTargets[faction3].Count)); } if (onContractGenComplete != null) { onContractGenComplete(); } yield break; } int i = debugCount; debugCount = i + 1; WeightedList <MapAndEncounters> activeMaps = new WeightedList <MapAndEncounters>(WeightedListType.SimpleRandom, contractMaps.ToList(), null, 0); List <MapAndEncounters> discardedMaps = new List <MapAndEncounters>(); List <string> mapDiscardPile = (List <string>)ReflectionHelper.GetPrivateField(instance, "mapDiscardPile"); for (int j = activeMaps.Count - 1; j >= 0; j--) { if (mapDiscardPile.Contains(activeMaps[j].Map.MapID)) { discardedMaps.Add(activeMaps[j]); activeMaps.RemoveAt(j); } } if (activeMaps.Count == 0) { mapDiscardPile.Clear(); foreach (MapAndEncounters element2 in discardedMaps) { activeMaps.Add(element2, 0); } } activeMaps.Reset(false); MapAndEncounters level = null; List <EncounterLayer_MDD> validEncounters = new List <EncounterLayer_MDD>(); Dictionary <ContractType, WeightedList <PotentialContract> > validContracts = new Dictionary <ContractType, WeightedList <PotentialContract> >(); WeightedList <PotentialContract> flatValidContracts = null; do { level = activeMaps.GetNext(false); if (level == null) { break; } validEncounters.Clear(); validContracts.Clear(); flatValidContracts = new WeightedList <PotentialContract>(WeightedListType.WeightedRandom, null, null, 0); foreach (EncounterLayer_MDD encounterLayer_MDD in level.Encounters) { ContractType contractType2 = encounterLayer_MDD.ContractTypeEntry.ContractType; if (contractTypes.Contains(contractType2)) { if (validContracts.ContainsKey(contractType2)) { validEncounters.Add(encounterLayer_MDD); } else { foreach (ContractOverride contractOverride2 in potentialOverrides[contractType2]) { bool flag = true; ContractDifficulty difficultyEnumFromValue = (ContractDifficulty)ReflectionHelper.InvokePrivateMethode(instance, "GetDifficultyEnumFromValue", new object[] { contractOverride2.difficulty }); Faction employer2 = Faction.INVALID_UNSET; Faction target2 = Faction.INVALID_UNSET; object[] args = new object[] { system, validEmployers, validTargets, contractOverride2.requirementList, employer2, target2 }; if (difficultyEnumFromValue >= minDiffClamped && difficultyEnumFromValue <= maxDiffClamped && (bool)ReflectionHelper.InvokePrivateMethode(instance, "GetValidFaction", args)) { employer2 = (Faction)args[4]; target2 = (Faction)args[5]; int difficulty = instance.NetworkRandom.Int(minDiff, maxDiff + 1); system.SetCurrentContractFactions(employer2, target2); int k = 0; while (k < contractOverride2.requirementList.Count) { RequirementDef requirementDef = new RequirementDef(contractOverride2.requirementList[k]); EventScope scope = requirementDef.Scope; TagSet curTags; StatCollection stats; switch (scope) { case EventScope.Company: curTags = instance.CompanyTags; stats = instance.CompanyStats; break; case EventScope.MechWarrior: case EventScope.Mech: goto IL_88B; case EventScope.Commander: goto IL_8E9; case EventScope.StarSystem: curTags = system.Tags; stats = system.Stats; break; default: goto IL_88B; } IL_803: for (int l = requirementDef.RequirementComparisons.Count - 1; l >= 0; l--) { ComparisonDef item2 = requirementDef.RequirementComparisons[l]; if (item2.obj.StartsWith("Target") || item2.obj.StartsWith("Employer")) { requirementDef.RequirementComparisons.Remove(item2); } } if (!SimGameState.MeetsRequirements(requirementDef, curTags, stats, null)) { flag = false; break; } k++; continue; IL_88B: if (scope != EventScope.Map) { throw new Exception("Contracts cannot use the scope of: " + requirementDef.Scope); } using (MetadataDatabase metadataDatabase2 = new MetadataDatabase()) { curTags = metadataDatabase2.GetTagSetForTagSetEntry(level.Map.TagSetID); stats = new StatCollection(); goto IL_803; } IL_8E9: curTags = instance.CommanderTags; stats = instance.CommanderStats; goto IL_803; } if (flag) { PotentialContract element3 = default(PotentialContract); element3.contractOverride = contractOverride2; element3.difficulty = difficulty; element3.employer = employer2; element3.target = target2; validEncounters.Add(encounterLayer_MDD); if (!validContracts.ContainsKey(contractType2)) { validContracts.Add(contractType2, new WeightedList <PotentialContract>(WeightedListType.WeightedRandom, null, null, 0)); } validContracts[contractType2].Add(element3, contractOverride2.weight); flatValidContracts.Add(element3, contractOverride2.weight); } } } } } } }while (validContracts.Count == 0 && level != null); system.SetCurrentContractFactions(Faction.INVALID_UNSET, Faction.INVALID_UNSET); if (validContracts.Count == 0) { if (mapDiscardPile.Count > 0) { mapDiscardPile.Clear(); } else { debugCount = 1000; SimGameState.logger.LogError(string.Format("[CONTRACT] Unable to find any valid contracts for available map pool. Alert designers.", new object[0])); } } else { GameContext gameContext = new GameContext(instance.Context); gameContext.SetObject(GameContextObjectTagEnum.TargetStarSystem, system); Dictionary <ContractType, List <EncounterLayer_MDD> > finalEncounters = new Dictionary <ContractType, List <EncounterLayer_MDD> >(); foreach (EncounterLayer_MDD encounterLayer_MDD2 in validEncounters) { ContractType contractType3 = encounterLayer_MDD2.ContractTypeEntry.ContractType; if (!finalEncounters.ContainsKey(contractType3)) { finalEncounters.Add(contractType3, new List <EncounterLayer_MDD>()); } finalEncounters[contractType3].Add(encounterLayer_MDD2); } List <PotentialContract> discardedContracts = new List <PotentialContract>(); List <string> contractDiscardPile = (List <string>)ReflectionHelper.GetPrivateField(instance, "contractDiscardPile"); for (int m = flatValidContracts.Count - 1; m >= 0; m--) { if (contractDiscardPile.Contains(flatValidContracts[m].contractOverride.ID)) { discardedContracts.Add(flatValidContracts[m]); flatValidContracts.RemoveAt(m); } } if ((float)discardedContracts.Count >= (float)flatValidContracts.Count * instance.Constants.Story.DiscardPileToActiveRatio || flatValidContracts.Count == 0) { contractDiscardPile.Clear(); foreach (PotentialContract element4 in discardedContracts) { flatValidContracts.Add(element4, 0); } } PotentialContract next = flatValidContracts.GetNext(true); ContractType finalContractType = next.contractOverride.contractType; finalEncounters[finalContractType].Shuffle <EncounterLayer_MDD>(); string encounterGuid = finalEncounters[finalContractType][0].EncounterLayerGUID; ContractOverride contractOverride3 = next.contractOverride; Faction employer3 = next.employer; Faction target3 = next.target; int targetDifficulty = next.difficulty; Contract con; if (usingBreadcrumbs) { con = (Contract)ReflectionHelper.InvokePrivateMethode(instance, "CreateTravelContract", new object[] { level.Map.MapName, level.Map.MapPath, encounterGuid, finalContractType, contractOverride3, gameContext, employer3, target3, employer3, false, targetDifficulty }); } else { con = new Contract(level.Map.MapName, level.Map.MapPath, encounterGuid, finalContractType, instance.BattleTechGame, contractOverride3, gameContext, true, targetDifficulty, 0, null); } mapDiscardPile.Add(level.Map.MapID); contractDiscardPile.Add(contractOverride3.ID); instance.PrepContract(con, employer3, target3, target3, level.Map.BiomeSkinEntry.BiomeSkin, con.Override.travelSeed, system); contractList.Add(con); if (useCoroutine) { yield return(new WaitForSeconds(0.2f)); } } } if (debugCount >= 1000) { SimGameState.logger.LogError("Unable to fill contract list. Please inform AJ Immediately"); } if (onContractGenComplete != null) { onContractGenComplete(); } yield break; }