Пример #1
0
        private static TroopRoster ConstructTroopRoster(PartyTemplateObject pt, int troopNumberLimit = -1) //TODO implement troop number limit.
        {
            TroopRoster returned     = new TroopRoster();
            float       gameProcess  = MiscHelper.GetGameProcess();
            float       num          = 0.25f + 0.75f * gameProcess;
            int         num2         = MBRandom.RandomInt(2);
            float       num3         = (num2 == 0) ? MBRandom.RandomFloat : (MBRandom.RandomFloat * MBRandom.RandomFloat * MBRandom.RandomFloat * 4f);
            float       num4         = (num2 == 0) ? (num3 * 0.8f + 0.2f) : (1f + num3);
            float       randomFloat  = MBRandom.RandomFloat;
            float       randomFloat2 = MBRandom.RandomFloat;
            float       randomFloat3 = MBRandom.RandomFloat;

            for (int i = 0; i < pt.Stacks.Count; i++)
            {
                float f = (pt.Stacks.Count > 0) ? ((float)pt.Stacks[i].MinValue + num * num4 * randomFloat * (float)(pt.Stacks[i].MaxValue - pt.Stacks[i].MinValue)) : 0f;
                returned.AddToCounts(pt.Stacks[i].Character, MBRandom.RoundRandomized(f), false);
            }
            return(returned);
        }
Пример #2
0
        public static void AddRandomCultureUnits(MobileParty party, int numberToAdd, CultureObject overrideCulture = null)
        {
            // Get culture
            CultureObject partyCultureObject = null;

            if (overrideCulture != null)
            {
                partyCultureObject = overrideCulture;
            }
            else
            {
                partyCultureObject = party.Party.Culture;
            }

            // Get possible units to create
            List <CharacterObject> characterObjectList = null;

            if (partyCultureObject.IsBandit)
            {
                characterObjectList = GetBanditCharacters(partyCultureObject);
            }
            else
            {
                characterObjectList = GetMainCultureCharacters(partyCultureObject);
            }

            // Split spawn based on number to add
            int[] spawnNumbers   = new int[characterObjectList.Count];
            int   currentSpawned = 0;

            while (currentSpawned < numberToAdd)
            {
                int randomInt = MBRandom.RandomInt(0, spawnNumbers.Length);
                spawnNumbers[randomInt]++;
                currentSpawned++;
            }

            for (int i = 0; i < characterObjectList.Count; i++)
            {
                CharacterObject characterObject = (CharacterObject)characterObjectList[i];
                party.AddElementToMemberRoster(characterObject, spawnNumbers[i]);
            }
        }
Пример #3
0
        public override void StartEvent()
        {
            try
            {
                int totalToHeal = MBRandom.RandomInt(minTroopsToHeal, Math.Min(maxTroopsToHeal, MobileParty.MainParty.MemberRoster.TotalWoundedRegulars));
                int totalHealed = 0;

                while (totalHealed < totalToHeal)
                {
                    int randomElement = MBRandom.RandomInt(MobileParty.MainParty.MemberRoster.Count);
                    while (MobileParty.MainParty.MemberRoster.GetElementWoundedNumber(randomElement) == 0 || !MobileParty.MainParty.MemberRoster.GetCharacterAtIndex(randomElement).IsRegular)
                    {
                        randomElement++;

                        if (randomElement == MobileParty.MainParty.MemberRoster.Count)
                        {
                            randomElement = 0;
                        }
                    }

                    MobileParty.MainParty.MemberRoster.AddToCountsAtIndex(randomElement, 0, -1, 0, true);
                    totalHealed++;
                }

                InformationManager.ShowInquiry(
                    new InquiryData("Speedy Recovery!",
                                    $"You receive word that a group of your troops are feeling better, and are ready for combat.",
                                    true,
                                    false,
                                    "Done",
                                    null,
                                    null,
                                    null
                                    ),
                    true);

                StopEvent();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error while playing \"{this.RandomEventData.EventType}\" event :\n\n {ex.Message} \n\n { ex.StackTrace}");
            }
        }
        public static bool EconomyTweak_h_GetTownGoldChange(Town town, ref int __result)
        {
            int   gold = town.Gold;
            float num  = town.Prosperity;
            float num2 = (float)gold * 0.95f + num * EconomyTweak_h_globalConstants.EconomyTweak_h_MarketGoldProsperityRatio * EconomyTweak_h_globalConstants.EconomyTweak_h_ValueOfProsperity * 0.05f;
            int   num3 = MBRandom.RoundRandomized(num2 - (float)gold);

            __result = num3;
            bool flag = EconomyTweak_h_globalConstants.EconomyTweak_h_DebugLevel > 0;

            if (flag)
            {
                using (StreamWriter streamWriter = File.AppendText(EconomyTweak_h_globalConstants.EconomyTweak_h_path + "EconomyTweak_h_log.txt"))
                {
                    streamWriter.WriteLine("EconomyTweak_h_GetTownGoldChange");
                }
                bool economyTweak_h_DebugDisplay = EconomyTweak_h_globalConstants.EconomyTweak_h_DebugDisplay;
                if (economyTweak_h_DebugDisplay)
                {
                    InformationManager.DisplayMessage(new InformationMessage("EconomyTweak_h_GetTownGoldChange"));
                }
                bool flag2 = EconomyTweak_h_globalConstants.EconomyTweak_h_DebugLevel > 1;
                if (flag2)
                {
                    using (StreamWriter streamWriter2 = File.AppendText(EconomyTweak_h_globalConstants.EconomyTweak_h_path + "EconomyTweak_h_log.txt"))
                    {
                        streamWriter2.WriteLine(string.Concat(new string[]
                        {
                            "town = ",
                            town.ToString(),
                            ", EconomyTweak_h_TownGold = ",
                            gold.ToString(),
                            ", EconomyTweak_h_TownProsperity = ",
                            num.ToString(),
                            ", EconomyTweak_h_GetTownGoldChange(result) = ",
                            __result.ToString()
                        }));
                    }
                }
            }
            return(false);
        }
Пример #5
0
 private void DoTellStories(ToldStoriesTo village)
 {
     if (village._battleStoriesTold < _notableBattlesWon)
     {
         SkillObject skill;
         int         num;
         skill = SkillObject.FindFirst((x) => { return(x.StringId == "Charm"); });
         num   = (int)Math.Ceiling(MobileParty.MainParty.LeaderHero.GetSkillValue(skill) * 0.03f);
         float _renownToGive = CalculateRenownToGive(num);
         GainRenownAction.Apply(Hero.MainHero, _renownToGive, true);
         if ((double)_renownToGive <= 0.2)
         {
             village._daysToResetStories = CampaignTime.DaysFromNow(this.RandomizeDays());
             village._hasToldStories     = true;
             ++village._battleStoriesTold;
             Hero.MainHero.AddSkillXp(DefaultSkills.Charm, 1);
             InformationManager.DisplayMessage(new InformationMessage("Your story failed to inspire the villagers."));
             return;
         }
         InformationManager.DisplayMessage(new InformationMessage("You told the villagers a story about a notable battle, gained " + _renownToGive + " renown."));
         village._daysToResetStories = CampaignTime.DaysFromNow(RandomizeDays());
         village._hasToldStories     = true;
         village._battleStoriesTold++;
         Hero.MainHero.AddSkillXp(DefaultSkills.Charm, MBRandom.RandomInt(1, 3));
         if (_renownToGive >= 2.0)
         {
             if (Settlement.CurrentSettlement.Notables.Count >= 1)
             {
                 InformationManager.DisplayMessage(new InformationMessage("Notable people in village were impressed by your feats and like you more."));
                 foreach (Hero notablePerson in Settlement.CurrentSettlement.Notables)
                 {
                     int _relationToGive = CalculateRelationToGive(_renownToGive);
                     ChangeRelationAction.ApplyPlayerRelation(notablePerson, _relationToGive, false, true);
                 }
             }
         }
     }
     else
     {
         InformationManager.DisplayMessage(new InformationMessage("You do not have new stories to tell to these villagers."));
     }
 }
Пример #6
0
 public void SimulateAgent(Agent agent)
 {
     if (agent.IsHuman)
     {
         AgentNavigator agentNavigator = agent.GetComponent <CampaignAgentComponent>().AgentNavigator;
         int            num            = MBRandom.RandomInt(35, 50);
         agent.PreloadForRendering();
         for (int i = 0; i < num; i++)
         {
             if (agentNavigator != null)
             {
                 agentNavigator.Tick(0.1f, true);
             }
             if (agent.IsUsingGameObject)
             {
                 agent.CurrentlyUsedGameObject.SimulateTick(0.1f);
             }
         }
     }
 }
Пример #7
0
        private string DoBet(int goldToBet)
        {
            float decision = MBRandom.RandomFloatRanged(0.0f, 1.0f);


            string outcomeText;

            if (decision >= 0.5f)
            {
                outcomeText = "\"Well, I'm never going to make that money back...\" Your companion says with a heavy sigh as your pocket your 'hard earned' gold.";
                Hero.MainHero.ChangeHeroGold(goldToBet);
            }
            else
            {
                outcomeText = "\"Better luck next time\" Your companion says smugly.";
                Hero.MainHero.ChangeHeroGold(-goldToBet);
            }

            return(outcomeText);
        }
Пример #8
0
        private void ConsequenceSpecificCaptorRelations(Companion companion, Hero hero)
        {
            if (!companion.MultipleRestrictedListOfConsequences.Contains(RestrictedListOfConsequences.ChangeRelation))
            {
                return;
            }
            bool InformationMessage = !companion.MultipleRestrictedListOfConsequences.Contains(RestrictedListOfConsequences.NoInformationMessage);
            bool NoMessages         = companion.MultipleRestrictedListOfConsequences.Contains(RestrictedListOfConsequences.NoMessages);


            try
            {
                _dynamics.RelationsModifier(hero, new CEVariablesLoader().GetIntFromXML(companion.RelationTotal), null, InformationMessage && !NoMessages, !InformationMessage && !NoMessages);
            }
            catch (Exception)
            {
                CECustomHandler.LogToFile("Missing RelationTotal");
                _dynamics.RelationsModifier(hero, MBRandom.RandomInt(-5, 5), null, InformationMessage && !NoMessages, !InformationMessage && !NoMessages);
            }
        }
Пример #9
0
        internal void ConsequenceRenown(Companion companion, Hero hero)
        {
            if (!companion.MultipleRestrictedListOfConsequences.Contains(RestrictedListOfConsequences.ChangeRenown))
            {
                return;
            }

            try
            {
                if (!string.IsNullOrEmpty(companion.RenownTotal))
                {
                    _dynamics.RenownModifier(new CEVariablesLoader().GetIntFromXML(companion.RenownTotal), hero);
                }
                else
                {
                    CECustomHandler.LogToFile("Missing RenownTotal");
                    _dynamics.RenownModifier(MBRandom.RandomInt(-5, 5), hero);
                }
            }
            catch (Exception) { CECustomHandler.LogToFile("Invalid RenownTotal"); }
        }
Пример #10
0
        internal void ConsequenceChangeHealth(Companion companion, Hero hero)
        {
            if (!companion.MultipleRestrictedListOfConsequences.Contains(RestrictedListOfConsequences.ChangeHealth))
            {
                return;
            }

            try
            {
                if (!string.IsNullOrEmpty(companion.HealthTotal))
                {
                    hero.HitPoints += new CEVariablesLoader().GetIntFromXML(companion.HealthTotal);
                }
                else
                {
                    CECustomHandler.LogToFile("Invalid HealthTotal");
                    hero.HitPoints += MBRandom.RandomInt(-20, 20);
                }
            }
            catch (Exception) { CECustomHandler.LogToFile("Missing HealthTotal"); }
        }
Пример #11
0
        public static Mission OpenMission(IEnhancedBattleTestCombatant playerParty,
                                          IEnhancedBattleTestCombatant enemyParty, BattleConfig config, string map)
        {
            if (config.BattleTypeConfig.BattleType == BattleType.Siege)
            {
                var attackerSiegeWeaponCount = GetSiegeWeaponCount(config.SiegeMachineConfig.AttackerMeleeMachines)
                                               .Union(GetSiegeWeaponCount(config.SiegeMachineConfig.AttackerRangedMachines))
                                               .ToDictionary(pair => pair.Key, pair => pair.Value);
                var defenderSiegeWeaponCount = GetSiegeWeaponCount(config.SiegeMachineConfig.DefenderMachines);

                int breachedWallCount   = config.MapConfig.BreachedWallCount;
                var hitPointPercentages = new float[2];

                switch (breachedWallCount)
                {
                case 0:
                    hitPointPercentages[0] = 1;
                    hitPointPercentages[1] = 1;
                    break;

                case 1:
                    int i = MBRandom.RandomInt(2);
                    hitPointPercentages[i]     = 0;
                    hitPointPercentages[1 - i] = 1;
                    break;

                default:
                    hitPointPercentages[0] = 0;
                    hitPointPercentages[1] = 0;
                    break;
                }

                return(OpenEnhancedBattleTestSiege(map, config, playerParty, enemyParty, hitPointPercentages,
                                                   attackerSiegeWeaponCount, defenderSiegeWeaponCount));
            }
            else
            {
                return(OpenEnhancedBattleTestField(map, config, playerParty, enemyParty));
            }
        }
Пример #12
0
 public static void PartyReplenishFood(MobileParty mobileParty)
 {
     if (mobileParty.IsPartyTradeActive && mobileParty.Food < Mathf.Abs(mobileParty.FoodChange * 2))
     {
         mobileParty.PartyTradeGold = (int)((double)mobileParty.PartyTradeGold * 0.95 + (double)(50f * (float)mobileParty.Party.MemberRoster.TotalManCount * 0.05f));
         if (MBRandom.RandomFloat < 0.1f && mobileParty.MapEvent != null)
         {
             foreach (ItemObject itemObject in ItemObject.All)
             {
                 if (itemObject.IsFood)
                 {
                     int num  = 12;
                     int num2 = MBRandom.RoundRandomized((float)mobileParty.MemberRoster.TotalManCount * (1f / (float)itemObject.Value) * (float)num * MBRandom.RandomFloat * MBRandom.RandomFloat * MBRandom.RandomFloat * MBRandom.RandomFloat);
                     if (num2 > 0)
                     {
                         mobileParty.ItemRoster.AddToCounts(itemObject, num2, true);
                     }
                 }
             }
         }
     }
 }
        private static bool Prefix(ref TournamentGame __result, Town town)
        {
            float gameBasicMeleeChance = 65f;
            float rdm = MBRandom.RandomFloatRanged(1f, 100f);

            if (rdm < gameBasicMeleeChance)
            {
                __result = new FightTournamentGame(town);
            }
            else
            {
                var newgame = new Fight2TournamentGame(town);
                //rdm = MBRandom.RandomFloatRanged(1f, 100f);
                //if (rdm < 50f)
                //{
                //    newgame.SetFightMode(Fight2TournamentGame.FightMode.One_One);
                //}
                __result = newgame;
            }

            return(false);
        }
Пример #14
0
        public void RecordPrePregnantInfo(Hero sexPartner1, Hero sexPartner2)
        {
            if ((double)MBRandom.RandomFloatRanged(0.0f, 1f) > (double)Config.Instance.PregnancyProbability || sexPartner1 == null || sexPartner2 == null || !Config.Instance.EnableLesbianPregnancy && sexPartner1.IsFemale && sexPartner2.IsFemale)
            {
                return;
            }
            Hero key    = (Hero)null;
            Hero father = (Hero)null;

            if (sexPartner1.IsAlive && sexPartner1.IsFemale && (sexPartner1.IsPregnant == false && (double)sexPartner1.Age > (double)Config.Instance.MinAge))
            {
                key    = sexPartner1;
                father = sexPartner2;
            }
            if (sexPartner2.IsAlive && sexPartner2.IsFemale && (sexPartner2.IsPregnant == false && (double)sexPartner2.Age > (double)Config.Instance.MinAge) && (key == null || MBRandom.RandomInt(0, 1) == 0))
            {
                key    = sexPartner2;
                father = sexPartner1;
            }
            if (key == null || father == null)
            {
                return;
            }
            CampaignTime pregnantDate = CampaignTime.DaysFromNow((float)MBRandom.RandomInt(Config.Instance.MinPregnancyDelayDays, Config.Instance.MaxPregnancyDelayDays));

            if (this.m_prePregnancyInfoMap.ContainsKey(key))
            {
                if (this.m_prePregnancyInfoMap[key].m_pregnantDate > pregnantDate)
                {
                    this.m_prePregnancyInfoMap[key].m_father       = father;
                    this.m_prePregnancyInfoMap[key].m_pregnantDate = pregnantDate;
                }
            }
            else
            {
                this.m_prePregnancyInfoMap.Add(key, new PregnancyControlBehavior.PrePregnancyInfo(father, pregnantDate));
            }
            Utillty.DebugDisplayMessage("_recordPrePregnantInfo Success! Mother : " + ((object)key.Name).ToString() + " Father : " + ((object)father.Name).ToString() + " PregnantDate : " + pregnantDate.ToString());
        }
Пример #15
0
        private async void Grunt(Agent a)
        {
            if (_affirmativeAgentCounter > _affirmativeAgentMaxCount * 2)
            {
                return;
            }
            if (a == Agent.Main)
            {
                return;
            }

            try {
                var agentPosition = a.Position;

                var distanceToPlayer = agentPosition.Distance(Agent.Main.Position);
                if (distanceToPlayer > 35f)
                {
                    return;
                }

                _affirmativeAgentCounter++;

                var timeToRespond = (int)(MBRandom.RandomInt(700, 900) * (distanceToPlayer / 10)).Clamp(500, 1200);

                await Task.Delay(timeToRespond);

                var reactionList = new Action[] {
                    () => a.MakeVoice(SkinVoiceManager.VoiceType.Grunt, SkinVoiceManager.CombatVoiceNetworkPredictionType.NoPrediction),
                    () => a.MakeVoice(SkinVoiceManager.VoiceType.Everyone, SkinVoiceManager.CombatVoiceNetworkPredictionType.NoPrediction),
                    () => a.MakeVoice(SkinVoiceManager.VoiceType.Yell, SkinVoiceManager.CombatVoiceNetworkPredictionType.NoPrediction),
                    () => a.MakeVoice(SkinVoiceManager.VoiceType.HorseRally, SkinVoiceManager.CombatVoiceNetworkPredictionType.NoPrediction)
                };

                if (Mission.Current != null && !Mission.Current.MissionEnded())
                {
                    reactionList[MBRandom.RandomInt(0, 3)].Invoke();
                }
            } catch { }
        }
Пример #16
0
        private static void SacrificeTroopsWithRatio(
            MobileParty mobileParty,
            float sacrifaceRatio)
        {
            int num1 = MBRandom.RoundRandomized((float)mobileParty.Party.NumberOfRegularMembers * sacrifaceRatio);

            for (int index = 0; index < num1; ++index)
            {
                float num2 = 100f;
                TroopRosterElement troopRosterElement1 = mobileParty.Party.MemberRoster.First <TroopRosterElement>();
                foreach (TroopRosterElement troopRosterElement2 in mobileParty.Party.MemberRoster)
                {
                    float num3 = (float)((double)troopRosterElement2.Character.Level - (troopRosterElement2.WoundedNumber > 0 ? 0.5 : 0.0) - (double)MBRandom.RandomFloat * 0.5);
                    if (!troopRosterElement2.Character.IsHero && (double)num3 < (double)num2 && troopRosterElement2.Number > 0)
                    {
                        num2 = num3;
                        troopRosterElement1 = troopRosterElement2;
                    }
                }
                mobileParty.MemberRoster.AddToCounts(troopRosterElement1.Character, -1, false, troopRosterElement1.WoundedNumber > 0 ? -1 : 0, 0, true, -1);
            }
        }
Пример #17
0
        private bool RemoveFood(int foodToRemove)
        {
            int currentlyRemovedFood = 0;

            while (currentlyRemovedFood < foodToRemove)
            {
                List <ItemRosterElement> foodItems = MobileParty.MainParty.ItemRoster.Where((item) => item.EquipmentElement.Item.IsFood).ToList();

                if (foodItems.Count() == 0)
                {
                    return(true);
                }

                int element = MBRandom.RandomInt(0, foodItems.Count());
                int amount  = foodItems[element].Amount;
                amount--;
                MobileParty.MainParty.ItemRoster.Remove(foodItems[element]);
                MobileParty.MainParty.ItemRoster.AddToCounts(foodItems[element].EquipmentElement.Item, amount);
                currentlyRemovedFood++;
            }

            return(false);
        }
Пример #18
0
        private void conversation_tavernkeep_bought_drinks()
        {
            int _curDrinkPrice = CalculateDrinksPrice();

            GiveGoldAction.ApplyBetweenCharacters(Hero.MainHero, null, _curDrinkPrice, false);
            if (_curDrinkPrice >= 500 && _curDrinkPrice < 1000)
            {
                GainRenownAction.Apply(Hero.MainHero, MBRandom.RandomFloatRanged(1.0f, 2.0f));
                Hero.MainHero.AddSkillXp(DefaultSkills.Charm, MBRandom.RandomInt(2, 4));
            }
            else if (_curDrinkPrice >= 1000 && _curDrinkPrice < 1500)
            {
                GainRenownAction.Apply(Hero.MainHero, MBRandom.RandomFloatRanged(2.0f, 3.5f));
                Hero.MainHero.AddSkillXp(DefaultSkills.Charm, MBRandom.RandomInt(4, 8));
            }
            else if (_curDrinkPrice >= 1500)
            {
                GainRenownAction.Apply(Hero.MainHero, MBRandom.RandomFloatRanged(3.5f, 5.0f));
                Hero.MainHero.AddSkillXp(DefaultSkills.Charm, MBRandom.RandomInt(5, 10));
            }
            InformationManager.DisplayMessage(new InformationMessage("Gained some renown and charm for buying drinks."));
            _boughtDrinksIn.Add(MobileParty.MainParty.CurrentSettlement);
        }
Пример #19
0
        public static EquipmentElement GetEquipmentWithModifier(ItemObject item, float prosperityFactor)
        {
            ItemModifierGroup itemModifierGroup;
            ArmorComponent    armorComponent = item.ArmorComponent;

            if (armorComponent != null)
            {
                itemModifierGroup = armorComponent.ItemModifierGroup;
            }
            else
            {
                itemModifierGroup = null;
            }
            ItemModifierGroup itemModifierGroup1     = itemModifierGroup ?? Campaign.Current.ItemModifierGroupss.FirstOrDefault <ItemModifierGroup>((ItemModifierGroup x) => x.ItemTypeEnum == item.ItemType);
            ItemModifier      itemModifierWithTarget = null;

            if (itemModifierGroup1 != null)
            {
                float prosperityVariance = 1f;
                if (prosperityFactor < 1f)
                {
                    prosperityVariance = MBRandom.RandomFloatRanged(prosperityFactor, 1f);
                }
                else
                {
                    prosperityVariance = MBRandom.RandomFloatRanged(1f, prosperityFactor);
                }

                itemModifierWithTarget = itemModifierGroup1.GetRandomModifierWithTarget(prosperityVariance, 1f);
            }
            //Toss out the bad ones - they suck as prizes
            if (itemModifierWithTarget.PriceMultiplier < 1)
            {
                itemModifierWithTarget = null;
            }
            return(new EquipmentElement(item, itemModifierWithTarget));
        }
Пример #20
0
        private bool CEApplyHeroChanceToEscape(Hero hero)
        {
            if (CESettings.Instance == null)
            {
                return(false);
            }

            bool inSettlement = hero.PartyBelongedToAsPrisoner.IsSettlement;

            if (hero.PartyBelongedToAsPrisoner.LeaderHero == Hero.MainHero || inSettlement && hero.PartyBelongedToAsPrisoner.Settlement.OwnerClan == Clan.PlayerClan)
            {
                bool customCheck = inSettlement ? CESettings.Instance.PrisonerHeroEscapeSettlement : CESettings.Instance.PrisonerHeroEscapeParty;
                if (!customCheck)
                {
                    return(false);
                }
                int numEscapeChance = inSettlement ? CESettings.Instance.PrisonerHeroEscapeChanceSettlement : CESettings.Instance.PrisonerHeroEscapeChanceParty;
                if (MBRandom.RandomInt(100) < numEscapeChance)
                {
                    EndCaptivityAction.ApplyByEscape(hero);
                }
            }
            else
            {
                bool customCheck = CESettings.Instance.PrisonerHeroEscapeOther;
                if (!customCheck)
                {
                    return(false);
                }
                int numEscapeChance = CESettings.Instance.PrisonerHeroEscapeChanceOther;
                if (MBRandom.RandomInt(100) < numEscapeChance)
                {
                    EndCaptivityAction.ApplyByEscape(hero);
                }
            }
            return(true);
        }
        private static TownPatrolData SpawnTownPatrol(string name, string size, PatrolData dat, bool isPlayerSpawn, Settlement spawnSettlement = null)
        {
            MBObjectManager objManager = Game.Current.ObjectManager;
            TextObject      pName      = new TextObject(name);

            PartyTemplateObject templateObject = (PartyTemplateObject)objManager.GetObject <PartyTemplateObject>(dat.templateName + "_" + size);

            spawnSettlement = isPlayerSpawn ? Settlement.CurrentSettlement : spawnSettlement;

            MobileParty patrol = objManager.CreateObject <MobileParty>(dat.templateName + "_" + size + "_" + 1);

            patrol.InitializeMobileParty(MenuUtils.ConstructTroopRoster(templateObject, patrol.Party), new TroopRoster(patrol.Party), isPlayerSpawn ? Settlement.CurrentSettlement.GatePosition : spawnSettlement.GatePosition, 0);

            patrol.SetCustomName(pName);
            patrol.Party.Owner = spawnSettlement.MapFaction.Leader == null?spawnSettlement.OwnerClan.Heroes.ToList().First() : spawnSettlement.OwnerClan.Leader;

            patrol.Party.Visuals.SetMapIconAsDirty();
            patrol.ActualClan     = spawnSettlement.OwnerClan;
            patrol.HomeSettlement = spawnSettlement;
            MenuUtils.CreatePartyTrade(patrol);

            foreach (ItemObject obj in ItemObject.All)
            {
                if (obj.IsFood)
                {
                    int num = MBRandom.RandomInt(patrol.MemberRoster.TotalManCount / 3, patrol.MemberRoster.TotalManCount);
                    if (num > 0)
                    {
                        patrol.ItemRoster.AddToCounts(obj, num);
                    }
                }
            }

            patrol.SetMovePatrolAroundSettlement(spawnSettlement);

            return(new TownPatrolData(pName.ToString(), size, patrol));
        }
Пример #22
0
        public void StartBattleForCombatPerformanceTests(int scene_index, int troop_count = 50)
        {
            int[] playerNumbers = new int[4];
            int[] enemyNumbers  = new int[4];
            if (troop_count == -1)
            {
                for (int index = 0; index < 4; ++index)
                {
                    playerNumbers[index] = MBRandom.RandomInt() % 50 + 25;
                    enemyNumbers[index]  = MBRandom.RandomInt() % 50 + 25;
                }
            }
            else
            {
                for (int index = 0; index < 4; ++index)
                {
                    playerNumbers[index] = troop_count;
                    enemyNumbers[index]  = troop_count;
                }
            }
            BasicCultureObject   playerFaction        = Game.Current.ObjectManager.GetObject <BasicCultureObject>("empire");
            BasicCultureObject   enemyFaction         = Game.Current.ObjectManager.GetObject <BasicCultureObject>("vlandia");
            BasicCharacterObject basicCharacterObject = Game.Current.ObjectManager.GetObject <BasicCharacterObject>("aserai_skirmisher");
            BasicCharacterObject enemyCharacter       = Game.Current.ObjectManager.GetObject <BasicCharacterObject>("aserai_skirmisher");

            CustomBattleCombatant[] customBattleParties = this.GetCustomBattleParties(basicCharacterObject, (BasicCharacterObject)null, enemyCharacter, playerFaction, playerNumbers, (List <BasicCharacterObject>[])null, enemyFaction, enemyNumbers, (List <BasicCharacterObject>[])null, true);
            BannerlordMissions.OpenCustomBattleMission(new string[6]
            {
                "battle_terrain_a",
                "battle_terrain_b",
                "battle_terrain_c",
                "battle_terrain_e",
                "battle_terrain_k",
                "battle_terrain_s"
            }[scene_index], basicCharacterObject, customBattleParties[0], customBattleParties[1], true, (BasicCharacterObject)null);
        }
        public void Randomize()
        {
            this.FactionSelectionGroup.ExecuteRandomize();
            this.CharacterSelectionGroup.ExecuteRandomize();
            this.CompositionGroup.RandomizeArmySize();
            int num1 = MBRandom.RandomInt(100);
            int num2 = MBRandom.RandomInt(100);
            int num3 = MBRandom.RandomInt(100);
            int num4 = MBRandom.RandomInt(100);
            int num5 = num1 + num2 + num3 + num4;
            int num6 = (int)Math.Round(100.0 * ((double)num1 / (double)num5));
            int num7 = (int)Math.Round(100.0 * ((double)num2 / (double)num5));
            int num8 = (int)Math.Round(100.0 * ((double)num3 / (double)num5));
            int num9 = 100 - (num6 + num7 + num8);

            this.CompositionGroup.IsArmyComposition1Enabled = false;
            this.CompositionGroup.IsArmyComposition2Enabled = false;
            this.CompositionGroup.IsArmyComposition3Enabled = false;
            this.CompositionGroup.IsArmyComposition4Enabled = false;
            this.CompositionGroup.ArmyComposition1Value     = num6;
            this.CompositionGroup.ArmyComposition2Value     = num7;
            this.CompositionGroup.ArmyComposition3Value     = num8;
            this.CompositionGroup.ArmyComposition4Value     = num9;
        }
Пример #24
0
        public void RecordSexInfo(Hero sexPartner1, Hero sexPartner2)
        {
            if (sexPartner1 == null || sexPartner1.IsDead || (sexPartner2 == null || sexPartner2.IsDead))
            {
                return;
            }
            CampaignTime nextSexEnableDate = CampaignTime.DaysFromNow((float)MBRandom.RandomInt(Config.Instance.MinSexDelayDays, Config.Instance.MaxSexDelayDays));

            if (this.m_dailySexTimeCountMap.ContainsKey(sexPartner1))
            {
                ++this.m_dailySexTimeCountMap[sexPartner1];
            }
            else
            {
                this.m_dailySexTimeCountMap.Add(sexPartner1, 1);
            }
            if (this.m_dailySexTimeCountMap.ContainsKey(sexPartner2))
            {
                ++this.m_dailySexTimeCountMap[sexPartner2];
            }
            else
            {
                this.m_dailySexTimeCountMap.Add(sexPartner2, 1);
            }
            int index = this.m_sexInformationList.FindIndex((Predicate <PregnancyControlBehavior.SexInfo>)(info => info.m_sexPartner1 == sexPartner1 && info.m_sexPartner2 == sexPartner2 || info.m_sexPartner2 == sexPartner1 && info.m_sexPartner1 == sexPartner2));

            if (index >= 0)
            {
                this.m_sexInformationList[index].m_nextSexEnableDate = (this.m_sexInformationList[index].m_nextSexEnableDate >= nextSexEnableDate) ? this.m_sexInformationList[index].m_nextSexEnableDate : nextSexEnableDate;
            }
            else
            {
                this.m_sexInformationList.Add(new PregnancyControlBehavior.SexInfo(sexPartner1, sexPartner2, nextSexEnableDate));
            }
            Utillty.DebugDisplayMessage("_recordSexInfo Success! Partner1 : " + ((object)sexPartner1.Name).ToString() + " Partner2 : " + ((object)sexPartner2.Name).ToString() + " NexSexEnableDate : " + nextSexEnableDate.ToString());
        }
Пример #25
0
        /*
         * This is a fix for a native bug where the weight function causes MBRandom.ChooseWeight to return null, which means
         * that there is no skillObject passed to HeroDeveloper.AddFocus
         */
        static bool Prefix(Hero hero)
        {
            List <SkillObject> list = (from x in SkillObject.All
                                       where hero.HeroDeveloper.GetFocus(x) < 5
                                       select x).ToList();

            Func <SkillObject, float> weightFunction;

            while (hero.HeroDeveloper.UnspentFocusPoints > 0 && list.Any <SkillObject>())
            {
                IEnumerable <SkillObject> candidates = list;
                weightFunction = (SkillObject skill) => Math.Max(1f, (float)(hero.GetSkillValue(skill) + 20 - 20 * hero.HeroDeveloper.GetFocus(skill)));

                SkillObject skillObject = MBRandom.ChooseWeighted <SkillObject>(candidates, weightFunction);

                hero.HeroDeveloper.AddFocus(skillObject, 1, true);

                if (hero.HeroDeveloper.GetFocus(skillObject) == 5)
                {
                    list.Remove(skillObject);
                }
            }
            return(false);
        }
Пример #26
0
        private static bool Prefix(TournamentFightMissionController __instance, ref List <Equipment> __result, int teamSize)
        {
            List <string>    list;
            List <Equipment> equipment = new List <Equipment>();
            string           stringId  = PlayerEncounter.Settlement.Culture.StringId;

            var list4 = (string[])Traverse.Create(__instance).Field("_weaponTemplatesIdTeamSizeFour").GetValue();
            var list2 = (string[])Traverse.Create(__instance).Field("_weaponTemplatesIdTeamSizeTwo").GetValue();
            var list1 = (string[])Traverse.Create(__instance).Field("_weaponTemplatesIdTeamSizeOne").GetValue();

            if (teamSize == 4)
            {
                //list = __instance._weaponTemplatesIdTeamSizeFour.ToList<string>();
                list = list4.ToList <string>();
            }
            else
            {
                list = (teamSize == 2 ? list2.ToList <string>() : list1.ToList <string>());
            }
            List <string> strs = list;

            strs = strs.FindAll((string x) => x.Contains(stringId));

            var template = MBObjectManager.Instance.GetObject <CharacterObject>(strs[MBRandom.RandomInt(strs.Count)]);
            List <Equipment> battleEquipments = ApplyEquipmentRules(template);

            foreach (Equipment battleEquipment in battleEquipments)
            {
                Equipment equipment1 = new Equipment();
                equipment1.FillFrom(battleEquipment, true);
                equipment.Add(equipment1);
            }
            __result = equipment;

            return(false);
        }
        public void ApplyAoeMoraleEffect(
            Agent affectedAgent,
            WorldPosition affectedAgentPosition,
            WorldPosition affectorAgentPosition,
            Team affectedAgentTeam,
            float moraleChangeAffected,
            float moraleChangeAffector,
            float radius,
            Predicate <Agent> affectedCondition = null,
            Predicate <Agent> affectorCondition = null)
        {
            IEnumerable <Agent> nearbyAgents = this.Mission.GetNearbyAgents(affectedAgentPosition.AsVec2, radius);
            int num1 = 10;
            int val1 = 10;

            foreach (Agent agent in nearbyAgents)
            {
                if (agent.Team != null && agent.Team.IsValid)
                {
                    float distance = agent.GetWorldPosition().GetNavMeshVec3().Distance(affectedAgentPosition.GetNavMeshVec3());
                    if ((double)distance < (double)radius && agent.IsAIControlled)
                    {
                        if (agent.Team.IsEnemyOf(affectedAgentTeam))
                        {
                            if (num1 > 0 && (affectorCondition == null || affectorCondition(agent)))
                            {
                                float changeToCharacter = MissionGameModels.Current.BattleMoraleModel.CalculateMoraleChangeToCharacter(agent, moraleChangeAffector, distance);
                                agent.ChangeMorale(changeToCharacter);
                                --num1;
                            }
                        }
                        else if (val1 > 0 && (affectedCondition == null || affectedCondition(agent)))
                        {
                            float changeToCharacter = MissionGameModels.Current.BattleMoraleModel.CalculateMoraleChangeToCharacter(agent, moraleChangeAffected, distance);
                            agent.ChangeMorale(changeToCharacter);
                            --val1;
                        }
                    }
                }
            }
            if (val1 <= 0)
            {
                return;
            }
            List <IFormationUnit> allUnits = affectedAgent.Formation?.arrangement?.GetAllUnits();

            if (allUnits == null)
            {
                return;
            }
            HashSet <int> intSet = new HashSet <int>();
            int           count  = allUnits.Count;
            int           num2   = Math.Min(val1, allUnits.Count);

            for (int index = count - num2; index < count; ++index)
            {
                int num3 = MBRandom.RandomInt(0, index + 1);
                intSet.Add(intSet.Contains(num3) ? index : num3);
            }
            foreach (int index in intSet)
            {
                if (allUnits[index] is Agent agent1 && agent1.IsActive() && agent1.IsAIControlled)
                {
                    float distance          = agent1.GetWorldPosition().GetNavMeshVec3().Distance(affectedAgentPosition.GetNavMeshVec3());
                    float changeToCharacter = MissionGameModels.Current.BattleMoraleModel.CalculateMoraleChangeToCharacter(agent1, moraleChangeAffected, distance);
                    agent1.ChangeMorale(changeToCharacter);
                }
            }
        }
Пример #28
0
        private void ExecuteStart()
        {
            int  armySize1 = this.PlayerSide.CompositionGroup.ArmySize;
            int  armySize2 = this.EnemySide.CompositionGroup.ArmySize;
            bool flag1     = (int)this.GameTypeSelectionGroup.GetCurrentPlayerSide() == 1;
            bool flag2     = this.GameTypeSelectionGroup.GetCurrentPlayerType() == GameTypeSelectionGroup.PlayerType.Commander;
            BasicCharacterObject basicCharacterObject = (BasicCharacterObject)null;

            if (!flag2)
            {
                List <BasicCharacterObject> list = ((IEnumerable <BasicCharacterObject>) this._charactersList).ToList <BasicCharacterObject>();
                list.Remove(this._charactersList[this.PlayerSide.CharacterSelectionGroup.SelectedIndex]);
                list.Remove(this._charactersList[this.EnemySide.CharacterSelectionGroup.SelectedIndex]);
                basicCharacterObject = (BasicCharacterObject)TaleWorlds.Core.Extensions.GetRandomElement <BasicCharacterObject>((IEnumerable <BasicCharacterObject>)list);
                --armySize1;
            }
            int num1  = armySize1 - 1;
            int num2  = (int)Math.Round((double)this.PlayerSide.CompositionGroup.ArmyComposition2Value / 100.0 * (double)num1);
            int num3  = (int)Math.Round((double)this.PlayerSide.CompositionGroup.ArmyComposition3Value / 100.0 * (double)num1);
            int num4  = (int)Math.Round((double)this.PlayerSide.CompositionGroup.ArmyComposition4Value / 100.0 * (double)num1);
            int num5  = num1 - (num2 + num3 + num4);
            int num6  = armySize2 - 1;
            int num7  = (int)Math.Round((double)this.EnemySide.CompositionGroup.ArmyComposition2Value / 100.0 * (double)num6);
            int num8  = (int)Math.Round((double)this.EnemySide.CompositionGroup.ArmyComposition3Value / 100.0 * (double)num6);
            int num9  = (int)Math.Round((double)this.EnemySide.CompositionGroup.ArmyComposition4Value / 100.0 * (double)num6);
            int num10 = num6 - (num7 + num8 + num9);

            CustomBattleCombatant[] customBattleParties = this._customBattleState.GetCustomBattleParties(this._charactersList[this.PlayerSide.CharacterSelectionGroup.SelectedIndex], basicCharacterObject, this._charactersList[this.EnemySide.CharacterSelectionGroup.SelectedIndex], this._factionList[this.PlayerSide.FactionSelectionGroup.SelectedIndex], new int[4]
            {
                num5,
                num2,
                num3,
                num4
            }, new List <BasicCharacterObject>[4]
            {
                this.PlayerSide.CompositionGroup.SelectedMeleeInfantryTypes,
                this.PlayerSide.CompositionGroup.SelectedRangedInfantryTypes,
                this.PlayerSide.CompositionGroup.SelectedMeleeCavalryTypes,
                this.PlayerSide.CompositionGroup.SelectedRangedCavalryTypes
            }, this._factionList[this.EnemySide.FactionSelectionGroup.SelectedIndex], new int[4]
            {
                num10,
                num7,
                num8,
                num9
            }, new List <BasicCharacterObject>[4]
            {
                this.EnemySide.CompositionGroup.SelectedMeleeInfantryTypes,
                this.EnemySide.CompositionGroup.SelectedRangedInfantryTypes,
                this.EnemySide.CompositionGroup.SelectedMeleeCavalryTypes,
                this.EnemySide.CompositionGroup.SelectedRangedCavalryTypes
            }, (flag1 ? 1 : 0) != 0);
            Game.Current.PlayerTroop = this._charactersList[this.PlayerSide.CharacterSelectionGroup.SelectedIndex];
            bool isSiege = this.GameTypeSelectionGroup.GetCurrentGameType() == GameTypeSelectionGroup.GameType.Siege;
            MapSelectionElement selectedMap = this.MapSelectionGroup.SelectedMap;
            MapSelectionElement mapWithName = this.MapSelectionGroup.GetMapWithName(this.MapSelectionGroup.SearchText);

            if (mapWithName != null && mapWithName != selectedMap)
            {
                selectedMap = mapWithName;
            }
            CustomBattleSceneData customBattleSceneData = selectedMap != null ? ((IEnumerable <CustomBattleSceneData>) this._customBattleScenes).Single <CustomBattleSceneData>((Func <CustomBattleSceneData, bool>)(s => ((object)((CustomBattleSceneData)s).Name).ToString() == selectedMap.MapName)) : ((IEnumerable <CustomBattleSceneData>) this._customBattleScenes).First <CustomBattleSceneData>((Func <CustomBattleSceneData, bool>)(cbs => ((CustomBattleSceneData)cbs).IsSiegeMap == isSiege));
            float num11 = 6f;

            if (this.MapSelectionGroup.IsCurrentMapSiege)
            {
                Dictionary <SiegeEngineType, int> dictionary1 = new Dictionary <SiegeEngineType, int>();
                foreach (CustomBattleSiegeMachineVM attackerMeleeMachine in (Collection <CustomBattleSiegeMachineVM>) this._attackerMeleeMachines)
                {
                    if (attackerMeleeMachine.SiegeEngineType != null)
                    {
                        SiegeEngineType siegeWeaponType = CustomBattleMenuVM.GetSiegeWeaponType(attackerMeleeMachine.SiegeEngineType);
                        if (!dictionary1.ContainsKey(siegeWeaponType))
                        {
                            dictionary1.Add(siegeWeaponType, 0);
                        }
                        dictionary1[siegeWeaponType]++;
                    }
                }
                foreach (CustomBattleSiegeMachineVM attackerRangedMachine in (Collection <CustomBattleSiegeMachineVM>) this._attackerRangedMachines)
                {
                    if (attackerRangedMachine.SiegeEngineType != null)
                    {
                        SiegeEngineType siegeWeaponType = CustomBattleMenuVM.GetSiegeWeaponType(attackerRangedMachine.SiegeEngineType);
                        if (!dictionary1.ContainsKey(siegeWeaponType))
                        {
                            dictionary1.Add(siegeWeaponType, 0);
                        }
                        dictionary1[siegeWeaponType]++;
                    }
                }
                Dictionary <SiegeEngineType, int> dictionary2 = new Dictionary <SiegeEngineType, int>();
                foreach (CustomBattleSiegeMachineVM defenderMachine in (Collection <CustomBattleSiegeMachineVM>) this._defenderMachines)
                {
                    if (defenderMachine.SiegeEngineType != null)
                    {
                        SiegeEngineType siegeWeaponType = CustomBattleMenuVM.GetSiegeWeaponType(defenderMachine.SiegeEngineType);
                        if (!dictionary2.ContainsKey(siegeWeaponType))
                        {
                            dictionary2.Add(siegeWeaponType, 0);
                        }
                        dictionary2[siegeWeaponType]++;
                    }
                }
                int     num12;
                float   num13    = (float)(num12 = int.Parse(((Collection <SelectorItemVM>) this.MapSelectionGroup.WallHitpointSelection.ItemList)[this.MapSelectionGroup.WallHitpointSelection.SelectedIndex].StringItem)) / 100f;
                float[] numArray = new float[2];
                if (num12 == 50)
                {
                    int index = MBRandom.RandomInt(2);
                    numArray[index]     = 0.0f;
                    numArray[1 - index] = 1f;
                }
                else
                {
                    numArray[0] = num13;
                    numArray[1] = num13;
                }
                BannerlordMissions.OpenSiegeMissionWithDeployment(((CustomBattleSceneData)customBattleSceneData).SceneID, this._charactersList[this.PlayerSide.CharacterSelectionGroup.SelectedIndex], customBattleParties[0], customBattleParties[1], this.GameTypeSelectionGroup.GetCurrentPlayerType() == GameTypeSelectionGroup.PlayerType.Commander, numArray, ((IEnumerable <CustomBattleSiegeMachineVM>) this._attackerMeleeMachines).Any <CustomBattleSiegeMachineVM>((Func <CustomBattleSiegeMachineVM, bool>)(mm => mm.SiegeEngineType == DefaultSiegeEngineTypes.SiegeTower)), dictionary1, dictionary2, flag1, int.Parse(this.MapSelectionGroup.SceneLevelSelection.GetCurrentItem().StringItem), this.MapSelectionGroup.SeasonSelection.GetCurrentItem().StringItem.ToLower(), this.MapSelectionGroup.IsSallyOutSelected, false, num11);
            }
            else
            {
                BannerlordMissions.OpenCustomBattleMission(((CustomBattleSceneData)customBattleSceneData).SceneID, this._charactersList[this.PlayerSide.CharacterSelectionGroup.SelectedIndex], customBattleParties[0], customBattleParties[1], flag2, basicCharacterObject, "", this.MapSelectionGroup.SeasonSelection.GetCurrentItem().StringItem.ToLower(), num11);
            }
            Debug.Print("P-Ranged: " + (object)num2 + " P-Mounted: " + (object)num3 + " P-HorseArcher: " + (object)num4 + " P-Infantry: " + (object)num5, 0, (Debug.DebugColor) 5, 17592186044416UL);
            Debug.Print("E-Ranged: " + (object)num7 + " E-Mounted: " + (object)num8 + " E-HorseArcher: " + (object)num9 + " E-Infantry: " + (object)num10, 0, (Debug.DebugColor) 5, 17592186044416UL);
            Debug.Print("EXECUTE START - PRESSED", 0, (Debug.DebugColor) 4, 17592186044416UL);
        }
        private void SpawnMainAgent()
        {
            if (this.mainAgent != null && this.mainAgent.State == AgentState.Active)
            {
                return;
            }
            MatrixFrame frame = new MatrixFrame(Mat3.Identity, new Vec3(200f + (float)MBRandom.RandomInt(15), 200f + (float)MBRandom.RandomInt(15), 1f));

            this.mainAgent = this.Mission.SpawnAgent(new AgentBuildData((IAgentOriginBase) new BasicBattleAgentOrigin(Game.Current.ObjectManager.GetObject <BasicCharacterObject>("main_hero"))).Team(this.Mission.DefenderTeam).InitialFrame(frame).Controller(Agent.ControllerType.Player));
        }
Пример #30
0
 public int RandomInRange() => IsFixed ? Min : MBRandom.RandomInt(Min, Max);