public void Play(Match match) { // Totally random match results for now... // Possible stuff contains 5 zeroes, 4 ones, 3 twos, 3 threes, etc. var possibleStuff = new Dictionary<int, float> { { 0, 5 }, { 1, 4 }, { 2, 3 }, { 3, 3 }, { 4, 2 }, { 5, 1 } }; match.HomeScore = possibleStuff.RandomElementByWeight(x => x.Value).Key; match.AwayScore = possibleStuff.RandomElementByWeight(x => x.Value).Key; // Take penalty shoot out, if necessary. bool matchEndedInDraw = match.HomeScore == match.AwayScore; if (matchEndedInDraw && !match.DrawPermitted) { var possiblePenaltyScores = new Dictionary<int, float> { { 5, 5 }, { 4, 5 }, { 3, 4 }, { 2, 1 }, { 1, 1 } }; match.HomePenaltyScore = possiblePenaltyScores.RandomElementByWeight(x => x.Value).Key; match.AwayPenaltyScore = possiblePenaltyScores.RandomElementByWeight(x => x.Value).Key; match.PenaltiesTaken = true; // Randomly pick a winner if the penalty shootout also ended undecisive. bool penaltyDraw = match.HomePenaltyScore == match.AwayPenaltyScore; if (penaltyDraw) { bool homeTeamWins = _randomizer.GetRandomBoolean(); if (homeTeamWins) { match.HomePenaltyScore++; } else { match.AwayPenaltyScore++; } } } match.MatchStatus = MatchStatus.Ended; //TODO Onderstaande nog afmaken... // Determine the best team. //Team bestTeam = match.HomeTeam; //Team worstTeam = match.AwayTeam; //if (match.AwayTeam.Rating > match.HomeTeam.Rating) //{ // bestTeam = match.AwayTeam; // worstTeam = match.HomeTeam; //} //// Determine difference between teams. //decimal ratio = bestTeam.Rating / worstTeam.Rating; //const decimal maxRatioWorstTeamCanWin = 2; //const decimal maxRatioDrawPossible = 2; //// Can the worst team win? //bool worstTeamCanWin = ratio <= maxRatioWorstTeamCanWin; //// Is a draw possible? //bool drawPossible = ratio <= maxRatioDrawPossible; }
public PawnKindDef ChooseOne() { if (hybridInfo.EnumerableNullOrEmpty()) { return(null); } PawnKindDef res = null; do { string key = hybridInfo.RandomElementByWeight(x => x.Value).Key; res = DefDatabase <PawnKindDef> .GetNamedSilentFail(key); if (res == null) { res = DefDatabase <ThingDef> .GetNamedSilentFail(key).race.AnyPawnKind; } if (res == null) { hybridInfo.Remove(key); } } while (res == null && !hybridInfo.EnumerableNullOrEmpty()); return(res); }
protected virtual void ApplyOutcome(float progress) { if (progress < 0.5f) { Find.LetterStack.ReceiveLetter("LetterLabelSpeechCancelled".Translate(), "LetterSpeechCancelled".Translate(organizer.Named("ORGANIZER")).CapitalizeFirst(), LetterDefOf.NegativeEvent, organizer); return; } ThoughtDef key = OutcomeThoughtChances.RandomElementByWeight((KeyValuePair <ThoughtDef, float> t) => (!PositiveOutcome(t.Key)) ? OutcomeThoughtChances[t.Key] : (OutcomeThoughtChances[t.Key] * organizer.GetStatValue(StatDefOf.SocialImpact) * progress)).Key; foreach (Pawn ownedPawn in lord.ownedPawns) { if (ownedPawn != organizer && organizer.Position.InHorDistOf(ownedPawn.Position, 18f)) { ownedPawn.needs.mood.thoughts.memories.TryGainMemory(key, organizer); } } TaggedString text = "LetterFinishedSpeech".Translate(organizer.Named("ORGANIZER")).CapitalizeFirst() + " " + ("Letter" + key.defName).Translate(); if (progress < 1f) { text += "\n\n" + "LetterSpeechInterrupted".Translate(progress.ToStringPercent(), organizer.Named("ORGANIZER")); } Find.LetterStack.ReceiveLetter(key.stages[0].LabelCap, text, PositiveOutcome(key) ? LetterDefOf.PositiveEvent : LetterDefOf.NegativeEvent, organizer); Ability ability = organizer.abilities.GetAbility(AbilityDefOf.Speech); RoyalTitle mostSeniorTitle = organizer.royalty.MostSeniorTitle; if (ability != null && mostSeniorTitle != null) { ability.StartCooldown(mostSeniorTitle.def.speechCooldown.RandomInRange); } }
public static void SendRaid(Map map, float points) { float totalPower = points; List <PawnKindDef> selectedKinds = new List <PawnKindDef>(); while (totalPower > 0) { PawnKindDef selected = PawnKinds.RandomElementByWeight(x => x.Value).Key; selectedKinds.Add(selected); totalPower -= selected.combatPower; } if (selectedKinds.Count == 0) { return; } List <Pawn> outPawns = new List <Pawn>(); foreach (PawnKindDef kind in selectedKinds) { PawnGenerationRequest request = new PawnGenerationRequest(kind, GssFaction, PawnGenerationContext.NonPlayer, -1, forceGenerateNewPawn: false, newborn: false, allowDead: false, allowDowned: false, canGeneratePawnRelations: true, mustBeCapableOfViolence: true, 1f, forceAddFreeWarmLayerIfNeeded: false, allowGay: true, true, false, certainlyBeenInCryptosleep: false, forceRedressWorldPawnIfFormerColonist: false, worldPawnFactionDoesntMatter: false); Pawn pawn = PawnGenerator.GeneratePawn(request); outPawns.Add(pawn); Find.WorldPawns.PassToWorld(pawn); } if (outPawns.Count == 0) { return; } CommunicationComponent_GssRaidTimer timer = new CommunicationComponent_GssRaidTimer((int)(Rand.Range(0.3f, 1.5f) * 60000), outPawns, map); timer.id = QuestsManager.Communications.UniqueIdManager.GetNextComponentID(); QuestsManager.Communications.RegisterComponent(timer); Find.LetterStack.ReceiveLetter("DarkNet_RaidSendedTitle".Translate(), "DarkNet_RaidSendedDesc".Translate(GssFaction.Name), LetterDefOf.ThreatBig); }
bool ReplaceRandomInfiniteObjectWithForceSpawnedObject(GameObject obj) { if (spawnedObjects.Count > 0) { int iterations = 20; Transform ground = null; if (groundTransformName != "") { ground = obj.transform.Find(groundTransformName); } ; Vector3 comparePosition = defaultGroundSize; if (ground != null) { comparePosition = ground.localScale; } while (iterations > 0) { GameObject replaceableObject = spawnedObjects.RandomElementByWeight(e => e.Value, randomSeed).Key; if (spawnedObjects[replaceableObject] > 0f) // check to see it's not accidentally a force-spawn object { replaceableObject.SetActive(false); obj.SetActive(false); Vector3 nextPosition = replaceableObject.transform.position; if (!Overlaps(nextPosition, replaceableObject, comparePosition)) { obj.transform.position = replaceableObject.transform.position; spawnedObjects.Remove(replaceableObject); spawnedObjects.Add(obj, 0f); obj.SetActive(true); Destroy(replaceableObject); return(true); } else { replaceableObject.SetActive(true); } } iterations--; } // failed to find an appropriately (sized) object, hide, put into queue queuedForceSpawnedObjects.Add(obj); obj.transform.position = new Vector3(9000f, 9000f, 9000f); return(false); } else // we couldn't find a spot for it, so we put into the queued list (and hide it) { queuedForceSpawnedObjects.Add(obj); obj.transform.position = new Vector3(9000f, 9000f, 9000f); return(false); } }
public EventCategory RandomCategory() { List <EventCategory> list = Enum.GetValues(typeof(EventCategory)).Cast <EventCategory>().ToList <EventCategory>(); Dictionary <EventCategory, float> dictionary = new Dictionary <EventCategory, float>(); foreach (EventCategory key in list) { dictionary.Add(key, ToolkitSettings.VoteCategoryWeights[key.ToString()]); } return(dictionary.RandomElementByWeight((KeyValuePair <EventCategory, float> pair) => pair.Value).Key); }
public KeyValuePair <int, int> GetRandomResult() { Dictionary <int, float> weightsWithZero = new Dictionary <int, float>(); weightsWithZero.Add(0, 0.3f); weightsWithZero.Add(1, 0.4f); weightsWithZero.Add(2, 0.35f); weightsWithZero.Add(3, 0.20f); weightsWithZero.Add(4, 0.1f); Dictionary <int, float> weightsNoZero = new Dictionary <int, float>(); weightsNoZero.Add(1, 0.4f); weightsNoZero.Add(2, 0.35f); weightsNoZero.Add(3, 0.20f); weightsNoZero.Add(4, 0.1f); var mark = GetRandomMark(); switch (mark) { case "X": var score = weightsWithZero.RandomElementByWeight(e => e.Value).Key; return(new KeyValuePair <int, int>(score, score)); case "1": var homeScore = weightsNoZero.RandomElementByWeight(e => e.Value).Key; var awayScore = rnd.Next(0, homeScore); return(new KeyValuePair <int, int>(homeScore, awayScore)); case "2": var a = weightsNoZero.RandomElementByWeight(e => e.Value).Key; var b = rnd.Next(0, a); return(new KeyValuePair <int, int>(b, a)); default: throw new Exception("Unkown mark " + mark); } }
public EventType RandomType() { Log.Warning("Trying random type", false); List <EventType> list = Enum.GetValues(typeof(EventType)).Cast <EventType>().ToList <EventType>(); Dictionary <EventType, float> dictionary = new Dictionary <EventType, float>(); foreach (EventType key in list) { dictionary.Add(key, ToolkitSettings.VoteCategoryWeights[key.ToString()]); } return(dictionary.RandomElementByWeight((KeyValuePair <EventType, float> pair) => pair.Value).Key); }
protected virtual void ApplyOutcome(float progress) { if (progress < 0.5f) { Find.LetterStack.ReceiveLetter("LetterLabelSpeechCancelled".Translate(), "LetterSpeechCancelled".Translate(organizer.Named("ORGANIZER")).CapitalizeFirst(), LetterDefOf.NegativeEvent, organizer); return; } ThoughtDef key = OutcomeThoughtChances.RandomElementByWeight((KeyValuePair <ThoughtDef, float> t) => (!PositiveOutcome(t.Key)) ? t.Value : (t.Value * organizer.GetStatValue(StatDefOf.SocialImpact) * progress)).Key; string text = ""; foreach (Pawn ownedPawn in lord.ownedPawns) { if (ownedPawn == organizer || !organizer.Position.InHorDistOf(ownedPawn.Position, 18f)) { continue; } ownedPawn.needs.mood.thoughts.memories.TryGainMemory(key, organizer); if (key == ThoughtDefOf.InspirationalSpeech && Rand.Chance(InspirationChanceFromInspirationalSpeech)) { InspirationDef randomAvailableInspirationDef = ownedPawn.mindState.inspirationHandler.GetRandomAvailableInspirationDef(); if (randomAvailableInspirationDef != null && ownedPawn.mindState.inspirationHandler.TryStartInspiration_NewTemp(randomAvailableInspirationDef, "LetterSpeechInspiration".Translate(ownedPawn.Named("PAWN"), organizer.Named("SPEAKER")))) { text = text + " - " + ownedPawn.NameShortColored.Resolve() + "\n"; } } } TaggedString text2 = "LetterFinishedSpeech".Translate(organizer.Named("ORGANIZER")).CapitalizeFirst() + " " + ("Letter" + key.defName).Translate(); if (!text.NullOrEmpty()) { text2 += "\n\n" + "LetterSpeechInspiredListeners".Translate() + "\n\n" + text.TrimEndNewlines(); } if (progress < 1f) { text2 += "\n\n" + "LetterSpeechInterrupted".Translate(progress.ToStringPercent(), organizer.Named("ORGANIZER")); } Find.LetterStack.ReceiveLetter(key.stages[0].LabelCap, text2, PositiveOutcome(key) ? LetterDefOf.PositiveEvent : LetterDefOf.NegativeEvent, organizer); Ability ability = organizer.abilities.GetAbility(AbilityDefOf.Speech); RoyalTitle mostSeniorTitle = organizer.royalty.MostSeniorTitle; if (ability != null && mostSeniorTitle != null) { ability.StartCooldown(mostSeniorTitle.def.speechCooldown.RandomInRange); } }
public static Pawn GetAnyRelatedWorldPawn(Func <Pawn, bool> selector, int minImportance) { // Get all important relations from all colonists var importantRelations = from colonist in PawnsFinder.AllMaps_FreeColonistsSpawned.Where(c => !c.Dead) from otherPawn in colonist.relations.RelatedPawns where !otherPawn.Dead && !otherPawn.Spawned && otherPawn.Faction != colonist.Faction && selector(otherPawn) && otherPawn.IsWorldPawn() select new { otherPawn, colonist, relationDef = colonist.GetMostImportantRelation(otherPawn) }; var dictRelations = new Dictionary <Pawn, float>(); // Calculate the total importance to colony foreach (var relation in importantRelations.Where(r => r.relationDef.importance >= minImportance)) { if (!dictRelations.ContainsKey(relation.otherPawn)) { dictRelations.Add(relation.otherPawn, relation.relationDef.importance); } else { dictRelations[relation.otherPawn] += relation.relationDef.importance; } } //Log.Message(dictRelations.Count + " distinct pawns:"); //foreach (var relation in dictRelations) //{ // Log.Message("- " + relation.Key.Name + ": " + relation.Value +(relation.Key.Faction.leader == relation.Key?" (leader)":"")); //} if (dictRelations.Count > 0) { var choice = dictRelations.RandomElementByWeight(pair => pair.Value); //Log.Message(choice.Key.Name + " with " + choice.Value + " points was chosen."); return(choice.Key); } else if (minImportance <= 0) { Log.Message("Couldn't find any pawn that is related to colony."); return(null); } else { return(GetAnyRelatedWorldPawn(selector, minImportance - 50)); } }
private static void SetupRandomizedGroupsByIDs(LG_PopulateArea area, Dictionary <int, float> enemyIDs) { if (enemyIDs == null || enemyIDs.Count < 1) { LoggerWrapper.Log("No enemy population tweaks, aborting setup..."); return; } HashSet <pAvailableEnemyTypes> validTypes; validTypes = GetValidGroups(enemyIDs); Dictionary <pAvailableEnemyTypes, float> weightedGroups = SetupWeighting(validTypes, enemyIDs); pAvailableEnemyTypes dataGroup = weightedGroups.RandomElementByWeight(e => e.Value).Key; LoggerWrapper.Log(dataGroup.ToString(), LogLevel.Debug); if (!enemyIDs.ContainsKey((int)dataGroup.enemyID)) { return; } area.m_groupPlacement.groupData.Difficulty = dataGroup.difficulty; area.m_groupPlacement.groupData.Type = GetValidGroupTypeFromRole(dataGroup.role); foreach (EnemyGroupCompositionData enemyGroupCompositionData in area.m_groupPlacement.groupData.Roles) { eEnemyRole role = dataGroup.role; EnsureValidRole(area.m_groupPlacement.groupData.Type, area.m_groupPlacement.groupData.Difficulty, ref role); enemyGroupCompositionData.Role = role; } LoggerWrapper.Log($"Setting enemyDataGroup: Diff:{area.m_groupPlacement.groupData.Difficulty} Role:{area.m_groupPlacement.groupData.Type} Type:{dataGroup.role}", LogLevel.Debug); }
public string selectTrait(int engineer, int pilot, int scientist, double educationRes, double educationNeeded, double flightExperienceRes, double flightExpNeeded) { Dictionary <string, float> foo = new Dictionary <string, float>(); if (educationRes >= educationNeeded) { foo.Add("Engineer", engineer); } if (flightExperienceRes >= flightExpNeeded) { foo.Add("Pilot", pilot); } if (educationRes >= educationNeeded) { foo.Add("Scientist", scientist); } if (foo.Count == 0) { return(""); } return(foo.RandomElementByWeight(e => e.Value).Key); //return selectTrait(rng.Next()); }
public override void DoEffect(Pawn usedBy) { base.DoEffect(usedBy); usedBy.Map.weatherManager.TransitionTo(weatherWeights.RandomElementByWeight(x => x.Value).Key); }
public int AwayPenaltyScore(Dictionary <int, float> stuff) { return(stuff.RandomElementByWeight(x => x.Value).Key); }
public bool HomeTeamWins(Dictionary <bool, float> stuff) { return(stuff.RandomElementByWeight(x => x.Value).Key); }
public List <PlayerSkillScore> Calculate(int startNumberR1, PlayerProfile profile, int age) { const ProfileSkillPriority profileSkillPriorityPrimary = ProfileSkillPriority.Primary; const ProfileSkillPriority profileSkillPrioritySecondary = ProfileSkillPriority.Secondary; const ProfileSkillPriority profileSkillPriorityTertiary = ProfileSkillPriority.Tertiary; const ProfileSkillPriority profileSkillPriorityQuatenary = ProfileSkillPriority.Quatenary; const ProfileSkillPriority profileSkillPriorityRandom = ProfileSkillPriority.Random; var playerSkillScores = new List <PlayerSkillScore>(); // Geef alle primary skills een score tussen de -30 en +30% van R1. // Onthoud de hoogste primary skill score, want dat is uitgangspunt voor de secondary skills. decimal highestPrimaryScore = 0; foreach (var primarySkill in profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPriorityPrimary)) { decimal randomPercentage = Randomizer.GetRandomNumber(-30, 30); decimal score = startNumberR1 + ((startNumberR1 * randomPercentage) / 100); if (score > highestPrimaryScore) { highestPrimaryScore = score; } int roundedScore = (int)decimal.Round(score, 0); if (roundedScore > MaxScore) { roundedScore = MaxScore; } if (roundedScore < 1) { roundedScore = 1; } var playerSkillScore = new PlayerSkillScore { PlayerSkill = primarySkill.Skill, Score = roundedScore }; playerSkillScores.Add(playerSkillScore); } // Bepaal uitgangspunt voor secondary skills score: tussen de 60% en 80% van de hoogste primary skill score (=R3) decimal secondaryPercentage = Randomizer.GetRandomNumber(60, 80); decimal r3 = (highestPrimaryScore * secondaryPercentage) / 100; // Bepaal random (true/false) of er onderscheid wordt gemaakt tussen tertiary en secondary skills. // Zo niet, dan zijn tertiary skills ook gewoon secondary. var booleans = new Dictionary <bool, float> { { true, 2 }, { false, 1 } }; bool useTertiarySkills = booleans.RandomElementByWeight(x => x.Value).Key; // Pak respectievelijk alleen de secondary skills of zowel de secondary als tertiary skills. IEnumerable <PlayerProfileSkill> secondarySkills = useTertiarySkills ? profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPrioritySecondary) : profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPrioritySecondary || x.SkillPriority == profileSkillPriorityTertiary); decimal highestSecondaryScore = 0; decimal lowestSecondaryScore = MaxScore; foreach (var secondarySkill in secondarySkills) { // Neem een random percentage tussen de -30% en +30% van R3 en bepaal hiermee de score. decimal randomPercentage = Randomizer.GetRandomNumber(-30, 30); decimal score = r3 + ((r3 * randomPercentage) / 100); // Onthoud de hoogste en laagste secondary skill score, want dat is uitgangspunt voor de tertiary en quatenary skills. if (score > highestSecondaryScore) { highestSecondaryScore = score; } if (score < lowestSecondaryScore) { lowestSecondaryScore = score; } int roundedScore = (int)decimal.Round(score, 0); if (roundedScore > MaxScore) { roundedScore = MaxScore; } if (roundedScore < 1) { roundedScore = 1; } var playerSkillScore = new PlayerSkillScore { PlayerSkill = secondarySkill.Skill, Score = roundedScore }; playerSkillScores.Add(playerSkillScore); } // Houtjetouwtje fix voor als een profiel geen secondary skills heeft... if (highestSecondaryScore == 0) { highestSecondaryScore = r3; } if (lowestSecondaryScore == MaxScore) { lowestSecondaryScore = r3; } // Bepaal random (true/false) of er onderscheid wordt gemaakt tussen quatenary en tertiary skills. // Zo niet, dan zijn tertiary skills ook gewoon secondary. bool useQuatenarySkills = booleans.RandomElementByWeight(x => x.Value).Key; IEnumerable <PlayerProfileSkill> tertiarySkills = new List <PlayerProfileSkill>(); IEnumerable <PlayerProfileSkill> quatenarySkills = new List <PlayerProfileSkill>(); if (useTertiarySkills) { if (useQuatenarySkills) { tertiarySkills = profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPriorityTertiary); quatenarySkills = profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPriorityQuatenary); } else { // De tertiary skills zijn zowel tertiary als quatenary. tertiarySkills = profile.PlayerProfileSkills.Where( x => x.SkillPriority == profileSkillPriorityTertiary || x.SkillPriority == profileSkillPriorityQuatenary); } } else { if (useQuatenarySkills) { quatenarySkills = profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPriorityQuatenary); } else { // De quatenary skills worden verplaatst naar de tertiary skills. tertiarySkills = profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPriorityQuatenary); useTertiarySkills = true; } } if (useTertiarySkills) { // Bepaal uitgangspunt voor tertiary skills score: tussen de 60% en 80% van de hoogste secondary skill score (=R3) decimal tertiaryPercentage = Randomizer.GetRandomNumber(60, 80); decimal r4 = (highestSecondaryScore * tertiaryPercentage) / 100; foreach (var tertiarySkill in tertiarySkills) { // Neem een random percentage tussen de -30% en +30% van R4 en bepaal hiermee de score. decimal randomPercentage = Randomizer.GetRandomNumber(-30, 30); decimal score = r4 + ((r4 * randomPercentage) / 100); int roundedScore = (int)decimal.Round(score, 0); if (roundedScore > MaxScore) { roundedScore = MaxScore; } if (roundedScore < 1) { roundedScore = 1; } var playerSkillScore = new PlayerSkillScore { PlayerSkill = tertiarySkill.Skill, Score = roundedScore }; playerSkillScores.Add(playerSkillScore); } } if (useQuatenarySkills) { foreach (var quatenarySkill in quatenarySkills) { // Pak een random nummer tussen 0 en de laagste secondary skill score. int score = Randomizer.GetRandomNumber(0, (int)decimal.Round(lowestSecondaryScore, 0)); if (score > MaxScore) { score = MaxScore; } if (score < 1) { score = 1; } var playerSkillScore = new PlayerSkillScore { PlayerSkill = quatenarySkill.Skill, Score = score }; playerSkillScores.Add(playerSkillScore); } } // De random skills krijgen een random waarde tussen 1 en de hoogste secondary skill. var randomSkills = profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPriorityRandom); foreach (var randomSkill in randomSkills) { // Pak een random nummer tussen 1 en de hoogste secondary skill score. int score = Randomizer.GetRandomNumber(1, (int)decimal.Round(highestSecondaryScore, 0)); if (score > MaxScore) { score = MaxScore; } var playerSkillScore = new PlayerSkillScore { PlayerSkill = randomSkill.Skill, Score = score }; playerSkillScores.Add(playerSkillScore); } return(playerSkillScores); }
// Start is called before the first frame update public IEnumerator Init() { finished = false; if (randomSeed != 0) { Random.InitState(randomSeed); } // start position is location of the spawner obejct lastPosition = transform.position; // and max extents are counted from the spawner object maxExtents = new Vector3(lastPosition.x + maxExtents.x, lastPosition.y + maxExtents.y, lastPosition.z + maxExtents.z); foreach (RandomObject obj in randomObjects) { spawnables.Add(obj, obj.weight); } // regular spawn spawnCounter = spawnObjectsMax; while (spawnCounter > 0) { yield return(null); //Debug.Log (spawnables.RandomElementByWeight (e => e.Value)); spawnCounter--; SpawnObject(spawnables.RandomElementByWeight(e => e.Value, randomSeed).Key); } ; // check to make sure all force-spawned objects were spawned during the regular spawn. and if not, spawn them foreach (RandomObject obj in randomObjects) { if (obj.spawnAmount > 0) { while (obj.spawnAmount > 0) { yield return(new WaitForEndOfFrame()); SpawnObjectRandom(obj); } ; } } if (queuedForceSpawnedObjects.Count > 0) { // if there are any queued force spawn objects, we try to place them now for (int i = 0; i < queuedForceSpawnedObjects.Count; i++) { yield return(new WaitForEndOfFrame()); if (PlaceObject(queuedForceSpawnedObjects[i], true, true)) { ; } { queuedForceSpawnedObjects.RemoveAt(i); } } } ; // If there are somehow still force spawn objects left, throw error if (queuedForceSpawnedObjects.Count > 0) { Debug.LogWarning("Could not place the following force-spawn objects for some reason!"); foreach (GameObject obj in queuedForceSpawnedObjects) { Debug.Log(obj.name, obj); } } Random.InitState((int)System.DateTime.Now.Second); // And we're done finished = true; }
public Religion MostSuitableReligion() { return(compabilities.RandomElementByWeight(x => x.Value).Key); }
public List<PlayerSkillScore> Calculate(int startNumberR1, PlayerProfile profile, int age) { const ProfileSkillPriority profileSkillPriorityPrimary = ProfileSkillPriority.Primary; const ProfileSkillPriority profileSkillPrioritySecondary = ProfileSkillPriority.Secondary; const ProfileSkillPriority profileSkillPriorityTertiary = ProfileSkillPriority.Tertiary; const ProfileSkillPriority profileSkillPriorityQuatenary = ProfileSkillPriority.Quatenary; const ProfileSkillPriority profileSkillPriorityRandom = ProfileSkillPriority.Random; var playerSkillScores = new List<PlayerSkillScore>(); // Geef alle primary skills een score tussen de -30 en +30% van R1. // Onthoud de hoogste primary skill score, want dat is uitgangspunt voor de secondary skills. decimal highestPrimaryScore = 0; foreach (var primarySkill in profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPriorityPrimary)) { decimal randomPercentage = Randomizer.GetRandomNumber(-30, 30); decimal score = startNumberR1 + ((startNumberR1 * randomPercentage) / 100); if (score > highestPrimaryScore) highestPrimaryScore = score; int roundedScore = (int)decimal.Round(score, 0); if (roundedScore > 20) roundedScore = 20; if (roundedScore < 1) roundedScore = 1; var playerSkillScore = new PlayerSkillScore { PlayerSkill = primarySkill.Skill, Score = roundedScore }; playerSkillScores.Add(playerSkillScore); } // Bepaal uitgangspunt voor secondary skills score: tussen de 60% en 80% van de hoogste primary skill score (=R3) decimal secondaryPercentage = Randomizer.GetRandomNumber(60, 80); decimal r3 = (highestPrimaryScore * secondaryPercentage) / 100; // Bepaal random (true/false) of er onderscheid wordt gemaakt tussen tertiary en secondary skills. // Zo niet, dan zijn tertiary skills ook gewoon secondary. var booleans = new Dictionary<bool, float> { { true, 2 }, { false, 1 } }; bool useTertiarySkills = booleans.RandomElementByWeight(x => x.Value).Key; // Pak respectievelijk alleen de secondary skills of zowel de secondary als tertiary skills. IEnumerable<PlayerProfileSkill> secondarySkills = useTertiarySkills ? profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPrioritySecondary) : profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPrioritySecondary || x.SkillPriority == profileSkillPriorityTertiary); decimal highestSecondaryScore = 0; decimal lowestSecondaryScore = 20; foreach (var secondarySkill in secondarySkills) { // Neem een random percentage tussen de -30% en +30% van R3 en bepaal hiermee de score. decimal randomPercentage = Randomizer.GetRandomNumber(-30, 30); decimal score = r3 + ((r3 * randomPercentage) / 100); // Onthoud de hoogste en laagste secondary skill score, want dat is uitgangspunt voor de tertiary en quatenary skills. if (score > highestSecondaryScore) highestSecondaryScore = score; if (score < lowestSecondaryScore) lowestSecondaryScore = score; int roundedScore = (int)decimal.Round(score, 0); if (roundedScore > 20) roundedScore = 20; if (roundedScore < 1) roundedScore = 1; var playerSkillScore = new PlayerSkillScore { PlayerSkill = secondarySkill.Skill, Score = roundedScore }; playerSkillScores.Add(playerSkillScore); } // Houtjetouwtje fix voor als een profiel geen secondary skills heeft... if (highestSecondaryScore == 0) highestSecondaryScore = r3; if (lowestSecondaryScore == 20) lowestSecondaryScore = r3; // Bepaal random (true/false) of er onderscheid wordt gemaakt tussen quatenary en tertiary skills. // Zo niet, dan zijn tertiary skills ook gewoon secondary. bool useQuatenarySkills = booleans.RandomElementByWeight(x => x.Value).Key; IEnumerable<PlayerProfileSkill> tertiarySkills = new List<PlayerProfileSkill>(); IEnumerable<PlayerProfileSkill> quatenarySkills = new List<PlayerProfileSkill>(); if (useTertiarySkills) { if (useQuatenarySkills) { tertiarySkills = profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPriorityTertiary); quatenarySkills = profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPriorityQuatenary); } else { // De tertiary skills zijn zowel tertiary als quatenary. tertiarySkills = profile.PlayerProfileSkills.Where( x => x.SkillPriority == profileSkillPriorityTertiary || x.SkillPriority == profileSkillPriorityQuatenary); } } else { if (useQuatenarySkills) { quatenarySkills = profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPriorityQuatenary); } else { // De quatenary skills worden verplaatst naar de tertiary skills. tertiarySkills = profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPriorityQuatenary); useTertiarySkills = true; } } if (useTertiarySkills) { // Bepaal uitgangspunt voor tertiary skills score: tussen de 60% en 80% van de hoogste secondary skill score (=R3) decimal tertiaryPercentage = Randomizer.GetRandomNumber(60, 80); decimal r4 = (highestSecondaryScore * tertiaryPercentage) / 100; foreach (var tertiarySkill in tertiarySkills) { // Neem een random percentage tussen de -30% en +30% van R4 en bepaal hiermee de score. decimal randomPercentage = Randomizer.GetRandomNumber(-30, 30); decimal score = r4 + ((r4 * randomPercentage) / 100); int roundedScore = (int)decimal.Round(score, 0); if (roundedScore > 20) roundedScore = 20; if (roundedScore < 1) roundedScore = 1; var playerSkillScore = new PlayerSkillScore { PlayerSkill = tertiarySkill.Skill, Score = roundedScore }; playerSkillScores.Add(playerSkillScore); } } if (useQuatenarySkills) { foreach (var quatenarySkill in quatenarySkills) { // Pak een random nummer tussen 0 en de laagste secondary skill score. int score = Randomizer.GetRandomNumber(0, (int)decimal.Round(lowestSecondaryScore, 0)); if (score > 20) score = 20; if (score < 1) score = 1; var playerSkillScore = new PlayerSkillScore { PlayerSkill = quatenarySkill.Skill, Score = score }; playerSkillScores.Add(playerSkillScore); } } // De random skills krijgen een random waarde tussen 1 en de hoogste secondary skill. var randomSkills = profile.PlayerProfileSkills.Where(x => x.SkillPriority == profileSkillPriorityRandom); foreach (var randomSkill in randomSkills) { // Pak een random nummer tussen 1 en de hoogste secondary skill score. int score = Randomizer.GetRandomNumber(1, (int)decimal.Round(highestSecondaryScore, 0)); if (score > 20) score = 20; var playerSkillScore = new PlayerSkillScore { PlayerSkill = randomSkill.Skill, Score = score }; playerSkillScores.Add(playerSkillScore); } // Sorteer de playerskills. playerSkillScores.Sort((x, y) => x.PlayerSkill.Order.CompareTo(y.PlayerSkill.Order)); return playerSkillScores; }
private List <Thing> CreateLoot() { Dictionary <string, float> lootEntries = new Dictionary <string, float>(); string[] arr = GenMagic.Magic(LootTable).Split('|'); int setsMin = int.Parse(arr[0]); int setsMax = int.Parse(arr[1]); int setsCount = GenMagic.GetRealCount(parent, Rand.RangeInclusive(setsMin, Rand.RangeInclusive(setsMin, setsMax))); //Log.Message("min: " + setsMin + ", max: " + setsMax + ", final: " + setsCount); for (int i = 2, iLen = arr.Length; i < iLen; i++) { string str = arr[i]; int pos = str.FirstIndexOf(c => c == ';'); lootEntries.Add(str.Substring(pos + 1), float.Parse(str.Substring(0, pos))); //Log.Message("key : " + str.Substring(pos + 1) + ", val: " + float.Parse(str.Substring(0, pos))); } List <Thing> lootList = new List <Thing>(); for (int i = 0; i < setsCount; i++) { string chosenSet = lootEntries.RandomElementByWeight(kvp => kvp.Value * kvp.Value).Key; //Log.Message("chosen set: " + chosenSet); arr = chosenSet.Split(';'); for (int j = 0, jLen = arr.Length; j < jLen; j++) { string[] inner = arr[j].Split(','); int min = (inner.Length <= 1) ? 1 : int.Parse(inner[1]); int max = (inner.Length <= 2) ? min : int.Parse(inner[2]); if (inner.Length >= 4) { max = Rand.RangeInclusive(max, int.Parse(inner[3])); } ThingDef def = DefDatabase <ThingDef> .GetNamed(inner[0]); //Log.Message("def: " + def.defName + ", min: " + min + ", max: " + max); if (def != null) { int countToDo = Rand.RangeInclusive(min, max); while (countToDo > 0) { int count = Math.Min(countToDo, def.stackLimit); countToDo -= count; Thing thing = ThingMaker.MakeThing(def, GenStuff.RandomStuffFor(def)); thing.stackCount = count; //Log.Message("thing: " + thing + ", stuff: " + thing.Stuff + ", count: " + count); CompQuality compQuality = thing.TryGetComp <CompQuality>(); if (compQuality != null) { QualityCategory q = QualityUtility.GenerateQualityCreatedByPawn(Rand.RangeInclusive(0, 19), false); compQuality.SetQuality(q, ArtGenerationContext.Outsider); } CompArt compArt = thing.TryGetComp <CompArt>(); if (compArt != null) { compArt.InitializeArt(ArtGenerationContext.Outsider); } lootList.Add(thing); } } } } return(lootList); }
public string GetTeamName() { //Bron: http://www.namegenerator.biz/place-name-generator.php var cities = new List<string> { "Falcondel", "Lochway", "Mallowice", "Whitemont", "Summerbutter", "Clearham", "Castleham", "Butterrock", "Westspring", "Westernesse", "Tenby", "Highview", "Dracmere", "Hollowston", "Wildesage", "Shadowbrook", "Buttercastle", "Silveroak", "Crystalcourt", "Springwinter", "Redwind", "Highfort", "Wyvernmere", "Whitemere", "Shadowgate", "Iceham", "Deeplake", "Freywyn", "Deeracre", "Shadowhal", "Deermead", "Starrydel", "Eastgriffin", "Marblewolf", "Woodmaple", "Edgeburn", "Highholt", "Coldfog", "Redash", "Hedgecliff", "Valhollow", "Byglass", "Westfay", "Greyhurst", "Fairfalcon", "Delland", "Glassmist", "Springbarrow", "Bykeep", "Grasslake", "Janlea", "Belwald", "Bellmare", "Brookden", "Hollowdel", "Iceacre", "Shadowlea", "Rockland", "Marbleborough", "Woodbeach", "Dorfield", "Lorbridge", "Bridgevale", "Alverton", "Larton", "Tunstead", "Wolfort", "Swanford", "Gormsey", "Deepbeech", "Woodfort", "Fayfield", "Edgeness", "Esterbeech", "Rosetown", "Hollowlyn", "Morfort", "Vertbrook", "Clearice", "Silveredge", "Mallowfield", "Fairmere", "Marblefield", "Norden", "Starryton", "Dracbarrow", "Wellden", "Crystalbeach", "Shadowmeadow", "Silverash", "Eastmarsh", "Pinevale", "Ericliff", "Janpond", "Raymont", "Marshfield", "Buttermeadow", "Bluedragon", "Deepburn", "Dracborough", "Estercrest", "Byway", "Mallowhedge", "Shorehal", "Fielddale", "Northfield", }; var suffixes = new Dictionary<string, float> { { "Rangers", 1 }, { "City", 2 }, { "Rovers", 1 }, { "FC", 3 }, { "Town", 1 }, { "United", 2 }, { "Athletic", 1 }, { "", 3 }, }; // Get random city. string teamName = _listRandomizer.GetItem(cities); // Combine city with (optional) suffix. string suffix = suffixes.RandomElementByWeight(x => x.Value).Key; if (!string.IsNullOrEmpty(suffix)) { teamName = $"{teamName} {suffix}"; } return teamName; }