Example #1
0
        /// <summary>
        /// Fills the <paramref name="armoury"/> with items of given <paramref name="cultureName"/>, if found.
        /// </summary>
        private void PopulateItemList(ItemRoster armoury, string cultureName)
        {
            XElement cultureElement = _settings.Descendants(cultureName.ToProper()).FirstOrDefault();

            if (cultureElement is null)
            {
                return;
            }

            IEnumerable <XElement> cultureItems = cultureElement.Descendants("Item");

            if (cultureItems.Count() < 1)
            {
                return;
            }

            foreach (XElement item in cultureItems)
            {
                try {
                    int        rng       = MBRandom.RandomInt(item.Attribute("minCount").ToInt(), item.Attribute("maxCount").ToInt());
                    string     itemId    = item.Attribute("name").Value;
                    ItemObject itemToAdd = MBObjectManager.Instance.GetObject <ItemObject>(itemId);

                    armoury.AddToCounts(itemToAdd, rng);
                } catch { }
            }
        }
        /// <summary>
        /// Calculates effect radius and a list of agents to be affected. Ignores cheer limit.
        /// </summary>
        private async Task DoVictoryCheer()
        {
            try {
                var leadership = Agent.Main.Character?.GetSkillValue(DefaultSkills.Leadership) ?? 0;
                _effectRadius = (leadership * 1.5f).Clamp(100, 700);

                var agentList = Mission.GetAgentsInRange(Agent.Main.Position.AsVec2, _effectRadius)
                                .Where(x => x.IsMount == false)
                                .Where(x => x.Health > 0)
                                .Where(x => x.Character != null)
                                .Where(x => x.IsMainAgent == false)
                                .Where(x => x.Team.IsFriendOf(Agent.Main.Team))
                                .ToList();

                _common.ApplyCheerEffects(Agent.Main, _moraleChange);
                await Task.Delay(TimeSpan.FromSeconds(0.65));

                foreach (var a in agentList)
                {
                    _common.ApplyCheerEffects(a, _moraleChange);
                    await Task.Delay(MBRandom.RandomInt(0, 9));
                }
            } catch (Exception ex) {
                if (_config.Cheering.DebugMode)
                {
                    Helpers.Log(ex.Message);
                    Clipboard.SetText(ex.Message + "\n" + ex.StackTrace);
                }
            }
        }
Example #3
0
        private float CalculateRenownToGive()
        {
            int   _rAmount     = MBRandom.RandomInt(1, 10);
            float _givenAmount = _rAmount * 0.1f;

            return(_givenAmount);
        }
Example #4
0
        public override void StartEvent()
        {
            try
            {
                int numberToInjure = MBRandom.RandomInt(minTroopsToInjure, maxTroopsToInjure);
                numberToInjure = Math.Min(numberToInjure, maxTroopsToInjure);

                MobileParty.MainParty.MemberRoster.WoundNumberOfTroopsRandomly(numberToInjure);

                InformationManager.ShowInquiry(
                    new InquiryData("Undercooked",
                                    $"Some of your troops fall ill to bad food, although you're unsure of what caused it, you're glad it wasn't you.",
                                    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}");
            }
        }
Example #5
0
        internal void ConsequenceChangeCaptorRenown(Companion companion, Hero hero)
        {
            if (!companion.MultipleRestrictedListOfConsequences.Contains(RestrictedListOfConsequences.ChangeCaptorRenown))
            {
                return;
            }

            if (hero.PartyBelongedToAsPrisoner.LeaderHero == null)
            {
                return;
            }

            try
            {
                if (!string.IsNullOrEmpty(companion.RenownTotal))
                {
                    _dynamics.RenownModifier(new CEVariablesLoader().GetIntFromXML(companion.RenownTotal), hero.PartyBelongedToAsPrisoner.LeaderHero);
                }
                else
                {
                    CECustomHandler.LogToFile("Missing RenownTotal");
                    _dynamics.RenownModifier(MBRandom.RandomInt(-5, 5), hero.PartyBelongedToAsPrisoner.LeaderHero);
                }
            }
            catch (Exception) { CECustomHandler.LogToFile("Invalid RenownTotal"); }
        }
Example #6
0
        public void DailyTick()
        {
            if (this._sneaker == null || this._sneaker.IsDead)
            {
                Settlement randomSettlement = Settlement.All.Where(obj => obj.IsTown).GetRandomElement();

                CultureObject culture = randomSettlement.Culture;

                CharacterObject co = CharacterObject.CreateFrom(culture.FemaleBeggar, true);
                CharacterObject characterObject = MBObjectManager.Instance.CreateObject <CharacterObject>();
                characterObject.Culture = co.Culture;
                characterObject.Age     = (float)MBRandom.RandomInt(22, 30);
                characterObject.DefaultFormationGroup   = co.DefaultFormationGroup;
                characterObject.StaticBodyPropertiesMin = co.StaticBodyPropertiesMin;
                characterObject.StaticBodyPropertiesMax = co.StaticBodyPropertiesMax;
                characterObject.IsFemale  = true;
                characterObject.Level     = co.Level;
                characterObject.HairTags  = co.HairTags;
                characterObject.BeardTags = co.BeardTags;
                characterObject.InitializeEquipmentsOnLoad(co.AllEquipments.ToList <Equipment>());
                characterObject.Name = co.Name;

                this._sneaker      = HeroCreator.CreateSpecialHero(characterObject, randomSettlement);
                this._sneaker.Name = new TextObject("\"偷袭者\"" + this._sneaker.Name.ToString(), null);
                HeroInitPropertyUtils.InitAttributeAndFouse(this._sneaker);
                HeroInitPropertyUtils.FillBattleEquipment(this._sneaker);

                randomSettlement = Hero.MainHero.CurrentSettlement;
                if (null != randomSettlement && randomSettlement.IsTown)
                {
                    CharacterChangeLocation(this._sneaker, this._sneaker.CurrentSettlement, randomSettlement);
                    InformationManager.DisplayMessage(new InformationMessage(this._sneaker.Name.ToString() + " 出现在" + randomSettlement.Name, Colors.Blue));
                }
            }
        }
Example #7
0
        private Settlement GetPlaguedSettlement()
        {
            if (MobileParty.MainParty.CurrentSettlement != null)
            {
                // If the player is in a settlement, use this one for the event so there's a higher chance a medic will help
                return(MobileParty.MainParty.CurrentSettlement);
            }
            else
            {
                List <Settlement> eligibleSettlements = new List <Settlement>();

                foreach (Settlement s in Hero.MainHero.Clan.Settlements)
                {
                    if (s.IsTown || s.IsCastle)
                    {
                        eligibleSettlements.Add(s);
                    }
                }

                // Randomly pick one of the eligible settlements
                int index = MBRandom.RandomInt(0, eligibleSettlements.Count);

                return(eligibleSettlements[index]);
            }
        }
Example #8
0
        internal void ConsequenceChangeMorale(Companion companion, Hero hero)
        {
            if (!companion.MultipleRestrictedListOfConsequences.Contains(RestrictedListOfConsequences.ChangeMorale))
            {
                return;
            }

            PartyBase party = hero.IsPrisoner
                ? hero.PartyBelongedToAsPrisoner //captive
                : hero.PartyBelongedTo?.Party;   //random, captor

            try
            {
                if (!string.IsNullOrEmpty(companion.MoraleTotal))
                {
                    _dynamics.MoraleChange(new CEVariablesLoader().GetIntFromXML(companion.MoraleTotal), party);
                }
                else
                {
                    CECustomHandler.LogToFile("Missing MoralTotal");
                    _dynamics.MoraleChange(MBRandom.RandomInt(-5, 5), party);
                }
            }
            catch (Exception) { CECustomHandler.LogToFile("Invalid MoralTotal"); }
        }
Example #9
0
        public static bool Prefix(MobileParty __instance, PartyTemplateObject pt, int troopNumberLimit)
        {
            if (__instance.IsBandit) // TaleWorlds hardcoding strikes again
            {
                double num1 = 0.4 + 0.8 * MiscHelper.GetGameProcess();
                int    num2 = MBRandom.RandomInt(2);
                double num3 = num2 == 0 ? MBRandom.RandomFloat : (MBRandom.RandomFloat * MBRandom.RandomFloat * MBRandom.RandomFloat * 4.0);
                double num4 = num2 == 0 ? (num3 * 0.8 + 0.2) : 1 + num3;

                foreach (PartyTemplateStack stack in pt.Stacks)
                {
                    int numTroopsToAdd = MBRandom.RoundRandomized((float)(stack.MinValue + num1 * num4 * MBRandom.RandomFloat * (stack.MaxValue - stack.MinValue)));
                    __instance.AddElementToMemberRoster(stack.Character, numTroopsToAdd);
                }
            }
            else if (__instance.IsVillager)
            {
                int index = MBRandom.RandomInt(pt.Stacks.Count);
                for (int troopCount = 0; troopCount < troopNumberLimit; troopCount++)
                {
                    __instance.AddElementToMemberRoster(pt.Stacks[index].Character, 1);
                    index = MBRandom.RandomInt(pt.Stacks.Count);
                }
            }
            else // everything else looks fine; hand stack filling to original method
            {
                return(true);
            }

            return(false);
        }
        public override void StartEvent()
        {
            if (Settings.GeneralSettings.DebugMode)
            {
                InformationManager.DisplayMessage(new InformationMessage($"Starting {this.RandomEventData.EventType}", RandomEventsSubmodule.textColor));
            }

            int        prisonerAmount = MBRandom.RandomInt(minPrisonerGain, maxPrisonerGain);
            Settlement settlement     = GetRandomSettlement();

            MobileParty prisoners = PartySetup.CreateBanditParty();

            prisoners.MemberRoster.Clear();
            PartySetup.AddRandomCultureUnits(prisoners, prisonerAmount, GetCultureToSpawn());

            settlement.Party.AddPrisoners(prisoners.MemberRoster);

            prisoners.RemoveParty();

            InformationManager.ShowInquiry(
                new InquiryData("Bunch of Prisoners",
                                $"You receive word that your guards have expertly stopped a force inciting violence at {settlement.Name}, they have been put in cells",
                                true,
                                false,
                                "Done",
                                null,
                                null,
                                null
                                ),
                true);

            StopEvent();
        }
        public void SetRandomParamsExceptKeys(int gender, int minAge, out float scale)
        {
            int hairNum         = 0;
            int beardNum        = 0;
            int faceTextureNum  = 0;
            int mouthTextureNum = 0;
            int eyebrowNum      = 0;
            int soundNum        = 0;
            int faceTattooNum   = 0;

            scale = 0.0f;
            MBBodyProperties.GetParamsMax(gender, minAge, ref hairNum, ref beardNum, ref faceTextureNum, ref mouthTextureNum, ref faceTattooNum, ref soundNum, ref eyebrowNum, ref scale);
            this._currentHair               = MBRandom.RandomInt(hairNum);
            this._curBeard                  = MBRandom.RandomInt(beardNum);
            this._curFaceTexture            = MBRandom.RandomInt(faceTextureNum);
            this._curMouthTexture           = MBRandom.RandomInt(mouthTextureNum);
            this._curFaceTattoo             = MBRandom.RandomInt(faceTattooNum);
            this._currentVoice              = MBRandom.RandomInt(soundNum);
            this._voicePitch                = MBRandom.RandomFloat;
            this._curEyebrow                = MBRandom.RandomInt(eyebrowNum);
            this._curSkinColorOffset        = MBRandom.RandomFloat;
            this._curHairColorOffset        = MBRandom.RandomFloat;
            this._curEyeColorOffset         = MBRandom.RandomFloat;
            this._curFaceTattooColorOffset1 = MBRandom.RandomFloat;
            this._heightMultiplier          = MBRandom.RandomFloat;
        }
Example #12
0
        private void HourlyTick(MBCampaignEvent campaignevent, object[] delegateparams)
        {
            currentForageHours++;
            if (currentForageHours < forageHours)
            {
                return;
            }

            int gatheredMeat   = MBRandom.RandomInt(minFoodAmount, maxFoodAmount);
            int gatheredGrapes = MBRandom.RandomInt(minFoodAmount, maxFoodAmount);

            ItemObject grape = MBObjectManager.Instance.GetObject <ItemObject>("grape");
            ItemObject meat  = MBObjectManager.Instance.GetObject <ItemObject>("meat");

            MobileParty.MainParty.ItemRoster.AddToCounts(grape, gatheredGrapes);
            MobileParty.MainParty.ItemRoster.AddToCounts(meat, gatheredMeat);

            Campaign.Current.TimeControlMode = CampaignTimeControlMode.Stop;

            InformationManager.ShowInquiry(new InquiryData(eventTitle, $"Your troop managed to forage {gatheredMeat} slabs of meat and {gatheredGrapes} baskets of grapes!", true, false, "Done", null, null, null), true);

            hourlyTickEvent.Unregister(this);
            hourlyTickEvent = null;

            MobileParty.MainParty.IsActive = true;

            StopEvent();
        }
        // protected override Type ConfigType => typeof(SettingsBase);

        protected override void ExecuteInternal(ReplyContext context, object config,
                                                Action <string> onSuccess,
                                                Action <string> onFailure)
        {
            var settings    = (SettingsBase)config;
            var adoptedHero = BLTAdoptAHeroCampaignBehavior.Current.GetAdoptedHero(context.UserName);

            if (adoptedHero == null)
            {
                onFailure(AdoptAHero.NoHeroMessage);
                return;
            }

            int availableGold = BLTAdoptAHeroCampaignBehavior.Current.GetHeroGold(adoptedHero);

            if (availableGold < settings.GoldCost)
            {
                onFailure(Naming.NotEnoughGold(settings.GoldCost, availableGold));
                return;
            }

            int amount = MBRandom.RandomInt(settings.AmountLow, settings.AmountHigh);

            (bool success, string description) = Improve(context.UserName, adoptedHero, amount, settings, context.Args);
            if (success)
            {
                onSuccess(description);
                BLTAdoptAHeroCampaignBehavior.Current.ChangeHeroGold(adoptedHero, -settings.GoldCost);
            }
            else
            {
                onFailure(description);
            }
        }
Example #14
0
        public override void StartEvent()
        {
            try
            {
                int        randomElement = MBRandom.RandomInt(eligibleSettlements.Count);
                Settlement settlement    = eligibleSettlements[randomElement];

                settlement.Town.CurrentBuilding.BuildingProgress += settlement.Town.CurrentBuilding.GetConstructionCost() - settlement.Town.CurrentBuilding.BuildingProgress;
                settlement.Town.CurrentBuilding.LevelUp();
                settlement.Town.BuildingsInProgress.Dequeue();

                InformationManager.ShowInquiry(
                    new InquiryData("Ahead of Time!",
                                    $"You receive word that {settlement} has completed its current project earlier than expected.",
                                    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}");
            }
        }
Example #15
0
        private void ReadySpawnPointLogic()
        {
            List <GameEntity> list1 = Mission.Current.GetActiveEntitiesWithScriptComponentOfType <HideoutSpawnPointGroup>().ToList <GameEntity>();

            if (!list1.Any <GameEntity>())
            {
                return;
            }
            HideoutSpawnPointGroup[] hideoutSpawnPointGroupArray = new HideoutSpawnPointGroup[list1.Count];
            foreach (GameEntity gameEntity in list1)
            {
                HideoutSpawnPointGroup firstScriptOfType = gameEntity.GetFirstScriptOfType <HideoutSpawnPointGroup>();
                hideoutSpawnPointGroupArray[firstScriptOfType.PhaseNumber - 1] = firstScriptOfType;
            }
            List <HideoutSpawnPointGroup> list2 = ((IEnumerable <HideoutSpawnPointGroup>)hideoutSpawnPointGroupArray).ToList <HideoutSpawnPointGroup>();

            list2.RemoveAt(0);
            for (int index = 0; index < 3; ++index)
            {
                list2.RemoveAt(MBRandom.RandomInt(list2.Count));
            }
            this._spawnPointFrames = new Stack <MatrixFrame[]>();
            for (int index = 0; index < hideoutSpawnPointGroupArray.Length; ++index)
            {
                if (!list2.Contains(hideoutSpawnPointGroupArray[index]))
                {
                    this._spawnPointFrames.Push(hideoutSpawnPointGroupArray[index].GetSpawnPointFrames());
                    Debug.Print("Spawn " + (object)hideoutSpawnPointGroupArray[index].PhaseNumber + " is active.", color: Debug.DebugColor.Green, debugFilter: 64UL);
                }
                hideoutSpawnPointGroupArray[index].RemoveWithAllChildren();
            }
            this.CreateSpawnPoints();
        }
        public static Settlement SelectARandomSettlementForLooterParty()
        {
            int num = 0;

            foreach (Settlement settlement in Settlement.All)
            {
                if (settlement.IsTown || settlement.IsVillage)
                {
                    int num2 = CalculateDistanceScore(settlement.Position2D.DistanceSquared(MobileParty.MainParty.Position2D));
                    num += num2;
                }
            }
            int num3 = MBRandom.RandomInt(num);

            foreach (Settlement settlement2 in Settlement.All)
            {
                if (settlement2.IsTown || settlement2.IsVillage)
                {
                    int num4 = CalculateDistanceScore(settlement2.Position2D.DistanceSquared(MobileParty.MainParty.Position2D));
                    num3 -= num4;
                    if (num3 <= 0)
                    {
                        return(settlement2);
                    }
                }
            }
            return(null);
        }
Example #17
0
 private void DoTellStories(ToldStoriesTo village)
 {
     if (village._battleStoriesTold < _notableBattlesWon)
     {
         float _renownToGive = CalculateRenownToGive();
         GainRenownAction.Apply(Hero.MainHero, _renownToGive, true);
         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 >= 0.9)
         {
             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)
                 {
                     ChangeRelationAction.ApplyPlayerRelation(notablePerson, +1, false, true);
                 }
             }
         }
     }
     else
     {
         InformationManager.DisplayMessage(new InformationMessage("You do not have new stories to tell to these villagers."));
     }
 }
Example #18
0
        private static uint TakeRandomColor(List <uint> colors)
        {
            int  index = MBRandom.RandomInt(colors.Count);
            uint color = colors[index];

            colors.RemoveAt(index);
            return(color);
        }
 private static Equipment GetRandomEquipment(CharacterObject ch)
 {
     if (ch.IsHero)
     {
         return(ch.FirstBattleEquipment);
     }
     return(ch.BattleEquipments.ToList <Equipment>()[MBRandom.RandomInt(ch.BattleEquipments.Count <Equipment>())]);
 }
Example #20
0
 protected EnhancedBattleTestAgentOrigin(IBattleCombatant combatant, IEnhancedBattleTestTroopSupplier troopSupplier, BattleSideEnum side, int rank = -1, UniqueTroopDescriptor uniqueNo = default)
 {
     _troopSupplier  = troopSupplier;
     _side           = side;
     BattleCombatant = combatant;
     _descriptor     = !uniqueNo.IsValid ? new UniqueTroopDescriptor(TaleWorlds.Core.Game.Current.NextUniqueTroopSeed) : uniqueNo;
     Rank            = rank == -1 ? MBRandom.RandomInt(10000) : rank;
 }
Example #21
0
        private void GiveRandomSkillXP()
        {
            List <SkillObject> allSkills = DefaultSkills.GetAllSkills().ToList();
            int index = MBRandom.RandomInt(allSkills.Count);

            float xpToGive = Settings.GeneralSettings.GeneralLevelXpMultiplier * Hero.MainHero.GetSkillValue(allSkills[index]);

            Hero.MainHero.AddSkillXp(allSkills[index], xpToGive);
        }
Example #22
0
        public static Settlement PickRandomSettlementOfKingdom(List <Kingdom> f, List <Data.SpawnSettlementType> preferredTypes = null) //instead of PicKRandomSettlementOfCulture, does not prioritize types over kingdom
        {
            int num = 0;
            List <Settlement> permissible = new List <Settlement>();

            if (preferredTypes.Count != 0)
            {
                foreach (Settlement s in Settlement.All)
                {
                    if (f.Contains(s.MapFaction))
                    {
                        foreach (var type in preferredTypes)
                        {
                            if (SettlementIsOfValidType(s, type))
                            {
                                permissible.Add(s);
                                break;
                            }
                        }
                    }
                }
            }
            if (permissible.Count == 0)
            {
                if (preferredTypes.Count != 0)
                {
                    ModDebug.ShowMessage("Spawn type checking for kingdom spawn did not find any valid settlements. Falling back to kingdom.", DebugMessageType.Spawn);
                }
                foreach (Settlement s in Settlement.All)
                {
                    if ((s.IsTown || s.IsVillage) && f.Contains(s.MapFaction))
                    {
                        permissible.Add(s);
                    }
                }
            }
            permissible.Randomize();
            foreach (Settlement s in permissible)
            {
                int num2 = TaleWorldsCode.BanditsCampaignBehaviour.CalculateDistanceScore(s.Position2D.DistanceSquared(MobileParty.MainParty.Position2D));
                num += num2;
            }
            int num3 = MBRandom.RandomInt(num);

            foreach (Settlement s in permissible)
            {
                int num4 = TaleWorldsCode.BanditsCampaignBehaviour.CalculateDistanceScore(s.Position2D.DistanceSquared(MobileParty.MainParty.Position2D)); //makes it more likely that the spawn will be further to the player.
                num3 -= num4;
                if (num3 <= 0)
                {
                    return(s);
                }
            }
            ModDebug.ShowMessage("Unable to find proper faction settlement of" + f.ToString() + " for some reason.", DebugMessageType.Spawn);
            return(permissible.Count == 0 ? Settlement.All[0] : permissible[0]);
        }
        private static int FindNumberOfMercenariesToAdd()
        {
            float troopMultipler    = Settings.Settings.Instance.TroopMultiplier;
            int   minNumberOfTroops = Settings.Settings.Instance.MinNumberOfTroops;
            int   maxNumberOfTroops = Settings.Settings.Instance.MaxNumberOfTroops + 1;           // if set at 15 will never get 15 need this + 1
            float numOfMercs        = MBRandom.RandomInt(minNumberOfTroops, maxNumberOfTroops);

            numOfMercs *= troopMultipler;
            return(MBRandom.RoundRandomized(numOfMercs));
        }
Example #24
0
        private float CalculateRenownToGive(int num)
        {
            int _rAmount = MBRandom.RandomInt(1, 20);

            InformationManager.DisplayMessage(new InformationMessage("Random Result: " + _rAmount.ToString() + " Charm Skill Bonus: " + num.ToString()));
            _rAmount += num;
            InformationManager.DisplayMessage(new InformationMessage("Total Result: " + _rAmount.ToString()));

            return((float)_rAmount * 0.1f);
        }
        public void RandomizeMap()
        {
            MBBindingList <MapItemVM> mapSearchResults = MapSearchResults;

            // ISSUE: explicit non-virtual call
            if (mapSearchResults != null && mapSearchResults.Count > 0)
            {
                MapSearchResults[MBRandom.RandomInt(MapSearchResults.Count)].ExecuteSelection();
            }
        }
Example #26
0
        private void InitializeMorale()
        {
            float num  = 35f;
            int   num2 = MBRandom.RandomInt(30);
            float num3 = num + num2;

            num3   = MissionGameModels.Current.BattleMoraleModel.GetEffectiveInitialMorale(Agent, num3);
            num3   = MBMath.ClampFloat(num3, 15f, 100f);
            Morale = num3;
        }
        public static Mission OpenMission(IEnhancedBattleTestCombatant playerParty,
                                          IEnhancedBattleTestCombatant enemyParty, BattleConfig config, string map)
        {
            if (config.PlayerTeamConfig.HasGeneral)
            {
                Game.Current.PlayerTroop = config.PlayerTeamConfig.General.CharacterObject;
            }
            if (config.BattleTypeConfig.BattleType == BattleType.Siege && config.PlayerTeamConfig.HasGeneral)
            {
                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 if (config.BattleTypeConfig.BattleType == BattleType.Field || config.BattleTypeConfig.BattleType == BattleType.Village)
            {
                //var characterObject = (config.PlayerTeamConfig.General as SPCharacterConfig)?.ActualCharacterObject;
                //EnhancedBattleTestPartyController.PlayerParty.Party.Owner = characterObject.HeroObject;
                //foreach(BasicCharacterObject player in playerParty.Characters)
                //{
                //    if (player.IsPlayerCharacter)
                //    {
                //        playerchar = player;
                //        break;
                //    }
                //}
                return(OpenEnhancedBattleTestField(map, config, playerParty, enemyParty));
            }
            return(null);
        }
Example #28
0
        public override void StartEvent()
        {
            if (Settings.GeneralSettings.DebugMode)
            {
                InformationManager.DisplayMessage(new InformationMessage($"Starting {this.RandomEventData.EventType}", RandomEventsSubmodule.textColor));
            }

            List <InquiryElement> inquiryElements = new List <InquiryElement>();

            inquiryElements.Add(new InquiryElement("a", "Break it up.", null, true, "Where do these fools think this food comes from?"));
            inquiryElements.Add(new InquiryElement("b", "Join in!", null, true, "You were done eating anyway."));

            MultiSelectionInquiryData msid = new MultiSelectionInquiryData(
                eventTitle,                                                    // Title
                $"While your party is eating, a large food fight breaks out.", // Description
                inquiryElements,                                               // Options
                false,                                                         // Can close menu without selecting an option. Should always be false.
                1,                                                             // Force a single option to be selected. Should usually be true
                "Okay",                                                        // The text on the button that continues the event
                null,                                                          // The text to display on the "cancel" button, shouldn't ever need it.
                (elements) =>                                                  // How to handle the selected option. Will only ever be a single element unless force single option is off.
            {
                if ((string)elements[0].Identifier == "a")
                {
                    MobileParty.MainParty.RecentEventsMorale -= moraleLoss;

                    InformationManager.ShowInquiry(new InquiryData(eventTitle, "You command that everyone stops this nonsense. Although the party looks displeased, at least you saved the food.", true, false, "Done", null, null, null), true);
                }
                else if ((string)elements[0].Identifier == "b")
                {
                    string extraDialogue = "";

                    float xpToGive = Settings.GeneralSettings.GeneralLevelXpMultiplier * Hero.MainHero.GetSkillValue(DefaultSkills.Throwing) * 0.5f;
                    Hero.MainHero.AddSkillXp(DefaultSkills.Throwing, xpToGive);

                    int foodToRemove  = MBRandom.RandomInt(minFoodLoss, maxFoodLoss);
                    bool runOutOfFood = RemoveFood(foodToRemove);
                    if (runOutOfFood)
                    {
                        extraDialogue = " Quickly you realise that there is no food left. If you can't source some more soon there may be trouble.";
                    }

                    InformationManager.ShowInquiry(new InquiryData(eventTitle, $"You decide to join in on the fun! You even manage to deal out some black eyes. Did you go too far? Probably.{extraDialogue}", true, false, "Done", null, null, null), true);
                }
                else
                {
                    MessageBox.Show($"Error while selecting option for \"{this.RandomEventData.EventType}\"");
                }
            },
                null);                 // What to do on the "cancel" button, shouldn't ever need it.

            InformationManager.ShowMultiSelectionInquiry(msid, true);

            StopEvent();
        }
Example #29
0
        public static TroopRoster ConstructTroopRoster(PartyTemplateObject template, PartyBase party)
        {
            TroopRoster roster = new TroopRoster(party);

            foreach (PartyTemplateStack stack in template.Stacks)
            {
                int num = MBRandom.RandomInt(stack.MinValue, stack.MaxValue);
                roster.AddToCounts(stack.Character, num);
            }
            return(roster);
        }
Example #30
0
        public static Settlement PickRandomSettlementOfCulture(List <CultureCode> c, List <Data.SpawnSettlementType> preferredTypes = null, List <Settlement> exceptions = null)
        {
            int num = 0;
            List <Settlement> permissible = new List <Settlement>();

            if (exceptions == null)
            {
                exceptions = new List <Settlement>();
            }

            if (preferredTypes != null)
            {
                foreach (Settlement s in Settlement.All)
                {
                    foreach (var type in preferredTypes)
                    {
                        if (SettlementIsOfValidType(s, type) && !exceptions.Contains(s))
                        {
                            permissible.Add(s);
                            break;
                        }
                    }
                }
            }
            if (permissible.Count == 0)
            {
                foreach (Settlement s in Settlement.All)
                {
                    if (!exceptions.Contains(s) && (s.IsTown || s.IsVillage) && (c.Contains(s.Culture.GetCultureCode())))
                    {
                        permissible.Add(s);
                    }
                }
            }
            permissible.Randomize();
            foreach (Settlement s in permissible)
            {
                int num2 = TaleWorldsCode.BanditsCampaignBehaviour.CalculateDistanceScore(s.Position2D.DistanceSquared(MobileParty.MainParty.Position2D));
                num += num2;
            }
            int num3 = MBRandom.RandomInt(num);

            foreach (Settlement s in permissible)
            {
                int num4 = TaleWorldsCode.BanditsCampaignBehaviour.CalculateDistanceScore(s.Position2D.DistanceSquared(MobileParty.MainParty.Position2D)); //makes it more likely that the spawn will be further to the player.
                num3 -= num4;
                if (num3 <= 0)
                {
                    return(s);
                }
            }
            //ModDebug.ShowMessage("Unable to find proper settlement of" + c.ToString() + " for some reason.", DebugMessageType.Spawn);
            return(null);
        }