Пример #1
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."));
     }
 }
Пример #2
0
        public void IncreaseRelations()
        {
            PatrolProperties patrolProperties;
            bool             flag = false;

            foreach (Settlement settlement in Settlement.All)
            {
                if (settlement.IsVillage)
                {
                    settlementPatrolProperties.TryGetValue(settlement.StringId, out patrolProperties);
                    if (patrolProperties.patrols.Count > 0 && settlement.OwnerClan == Clan.PlayerClan)
                    {
                        foreach (Hero notable in settlement.Notables)
                        {
                            if (notable.GetRelationWithPlayer() < RelationCap)
                            {
                                // 10% chance of apply increase in relations
                                if (rand.Next(0, 100) < 10)
                                {
                                    ChangeRelationAction.ApplyRelationChangeBetweenHeroes(Hero.MainHero, notable, rand.Next(1, patrolProperties.patrols.Count + 1), NotifyNotableRelations);
                                    flag = true;
                                }
                            }
                        }
                    }
                }
            }
            if (flag)
            {
                InformationManager.DisplayMessage(new InformationMessage(new TextObject("Your relation with notables in some of your settlements increased due to having patrols", null).ToString()));
            }
        }
Пример #3
0
        private void IncreaseLocalRelations(MapEvent m)
        {
            float FinalRelationshipIncrease = KBRRModLibSettings.Instance.RelationshipIncrease;

            if (KBRRModLibSettings.Instance.SizeBonusEnabled)
            {
                FinalRelationshipIncrease = KBRRModLibSettings.Instance.RelationshipIncrease * this.BanditDeathCounter * KBRRModLibSettings.Instance.SizeBonus;
            }
            int FinalRelationshipIncreaseInt = (int)Math.Floor(FinalRelationshipIncrease);

            FinalRelationshipIncreaseInt = FinalRelationshipIncreaseInt < 1 ? 1 : FinalRelationshipIncreaseInt;
            InformationManager.DisplayMessage(new InformationMessage("Final Relationship Increase: " + FinalRelationshipIncreaseInt.ToString(), Color.FromUint(4282569842U)));

            List <Settlement> list = new List <Settlement>();

            foreach (Settlement settlement in Settlement.All)
            {
                if ((settlement.IsVillage || settlement.IsTown) && settlement.Position2D.DistanceSquared(m.Position) <= KBRRModLibSettings.Instance.Radius)
                {
                    list.Add(settlement);
                }
            }
            foreach (Settlement settlement2 in list)
            {
                if (settlement2.Notables.Any <Hero>())
                {
                    Hero h = settlement2.Notables.GetRandomElement <Hero>();
                    ChangeRelationAction.ApplyPlayerRelation(h, relation: FinalRelationshipIncreaseInt, affectRelatives: true, showQuickNotification: false);
                }
            }
            InformationManager.DisplayMessage(new InformationMessage("Your relationship increased with nearby notables.", Color.FromUint(4282569842U)));
        }
 public static void GetCreditForHelping(int relationChange)
 {
     foreach (Hero notable in Settlement.CurrentSettlement.Notables)
     {
         ChangeRelationAction.ApplyPlayerRelation(notable, relationChange);
         notable.AddPower(relationChange);
     }
 }
 /// <summary>
 /// Creates arguments for changing the relationship between entities.
 /// </summary>
 /// <param name="changeRelationAction">The action to be taken.</param>
 /// <param name="childId">The identity of the child element.</param>
 /// <param name="parentId">The identity of the parent element.</param>
 /// <param name="relationId">The identity of the relation between the parent and child.</param>
 public ChangeRelationArgs(ChangeRelationAction changeRelationAction, Guid childId, Guid parentId, Guid relationId)
 {
     // Initialize the object
     this.changeRelationAction = changeRelationAction;
     this.childId    = childId;
     this.parentId   = parentId;
     this.relationId = relationId;
 }
        private void OnHourlyTickEvent(MobileParty mobileParty)
        {
            Hero companion = mobileParty.LeaderHero;

            if (mobileParty == MobileParty.MainParty ||
                companion == null ||
                !mobileParty.IsLordParty ||
                companion.Clan != Clan.PlayerClan)
            {
                return;
            }

            Settlement target = mobileParty.TargetSettlement;

            if (mobileParty.DefaultBehavior != AiBehavior.PatrolAroundPoint ||
                target.OwnerClan != Clan.PlayerClan)
            {
                return;
            }

            if (mobileParty.Position2D.DistanceSquared(target.Position2D) > MinPatrolDistance)
            {
                //InformationManager.DisplayMessage(new InformationMessage(companion.Name + " too far away from " + target.Name));
                mobileParty.SetMoveGoToSettlement(target);
                return;
            }
            //InformationManager.DisplayMessage(new InformationMessage(companion.Name + " patrolling around " + target.Name));

            int companion_relation;

            foreach (Hero notable in target.Notables)
            {
                companion_relation = CharacterRelationManager.GetHeroRelation(companion, notable) + 1;
                if (companion_relation % HoursRequirement == 0)
                {
                    // reset companion personal relation
                    companion_relation = 0;

                    // increase player relation
                    int oldRelation = notable.GetRelation(Hero.MainHero);
                    ChangeRelationAction.ApplyPlayerRelation(notable, 1, false, false);
                    int newRelation     = notable.GetRelation(Hero.MainHero);
                    int relation_change = newRelation - oldRelation;

                    if (relation_change > 0)
                    {
                        TextObject textObject = GameTexts.FindText("str_your_relation_increased_with_notable", null);
                        TextObject heroText   = new TextObject();
                        ZenDzeeCompatibilityHelper.SetTextVariable(heroText, "NAME", notable.Name);
                        ZenDzeeCompatibilityHelper.SetTextVariable(textObject, "HERO", heroText);
                        ZenDzeeCompatibilityHelper.SetTextVariable(textObject, "VALUE", newRelation);
                        ZenDzeeCompatibilityHelper.SetTextVariable(textObject, "MAGNITUDE", relation_change);
                        InformationManager.DisplayMessage(new InformationMessage(textObject.ToString()));
                    }
                }
                CharacterRelationManager.SetHeroRelation(companion, notable, companion_relation);
            }
        }
 private void town_notable_rebellion_consquence()
 {
     RebelliousNotables.Add(Hero.OneToOneConversationHero, Settlement.CurrentSettlement.MapFaction);
     ChangeRelationAction.ApplyRelationChangeBetweenHeroes(Hero.OneToOneConversationHero, Settlement.CurrentSettlement.OwnerClan.Leader, -100);
     if (Settlement.CurrentSettlement.MapFaction.Leader != Settlement.CurrentSettlement.OwnerClan.Leader)
     {
         ChangeRelationAction.ApplyRelationChangeBetweenHeroes(Hero.OneToOneConversationHero, Settlement.CurrentSettlement.MapFaction.Leader, -100);
     }
 }
        private void town_notable_cash_bribe_consequence()
        {
            int required = (int)((Hero.MainHero.GetPerkValue(DefaultPerks.Charm.Diplomacy) ? 0.85 : 1.0f) * (Hero.MainHero.Culture == Hero.OneToOneConversationHero.Culture ? 0.9f : 1.1f) * (10000 + 5000 * (int)Math.Min(2, Math.Max(0, (Hero.OneToOneConversationHero.Power / 100)))));

            Hero.MainHero.Gold -= required;
            InformationManager.DisplayMessage(new InformationMessage(required + " <img src=\"Icons\\Coin@2x\">gold spent giving finical support to " + Hero.OneToOneConversationHero.Name.ToString()));
            ChangeRelationAction.ApplyPlayerRelation(Hero.OneToOneConversationHero, 20);
            Hero.OneToOneConversationHero.AddPower(25);
            Hero.OneToOneConversationHero.SupporterOf = Hero.MainHero.Clan;
        }
        private void town_notable_political_bribe_consequence()
        {
            int required = (int)((Hero.MainHero.GetPerkValue(DefaultPerks.Charm.Diplomacy) ? 0.85 : 1.0f) * (Hero.MainHero.Culture == Hero.OneToOneConversationHero.Culture ? 0.9f : 1.1f) * (100 + 50 * (int)Math.Min(2, Math.Max(0, (Hero.OneToOneConversationHero.Power / 100)))));

            Hero.MainHero.Clan.Influence -= required;
            ChangeRelationAction.ApplyPlayerRelation(Hero.OneToOneConversationHero, 20);
            Hero.OneToOneConversationHero.AddPower(25);
            Hero.OneToOneConversationHero.SupporterOf = Hero.MainHero.Clan;
            InformationManager.DisplayMessage(new InformationMessage(required + GameTexts.FindText("str_html_influence_icon").ToString() + " influence spent giving political support to " + Hero.OneToOneConversationHero.Name.ToString()));
        }
Пример #10
0
        private void ApplyAddRelation(Hero hero, Clan clan, int daysToNow)
        {
            var relation = GetExpectRelation(hero, clan, daysToNow);
            var cost     = GetExpectGoldCostOfRelation(clan, relation);

            if (Hero.MainHero.Gold > cost * 1.2 && CharacterRelationManager.GetHeroRelation(Hero.MainHero, clan.Leader) < 100)
            {
                ChangeRelationAction.ApplyPlayerRelation(clan.Leader, GetExpectRelation(hero, clan, daysToNow, false));
                GiveGoldAction.ApplyBetweenCharacters(Hero.MainHero, clan.Leader, cost);
            }
        }
Пример #11
0
 private void TransferSettlementAction(Clan clan)
 {
     ChangeOwnerOfSettlementAction.ApplyByBarter(clan.Leader, Settlement.CurrentSettlement);
     if (Settlement.CurrentSettlement.IsTown)
     {
         ChangeRelationAction.ApplyPlayerRelation(clan.Leader, 40);
     }
     else if (Settlement.CurrentSettlement.IsCastle)
     {
         ChangeRelationAction.ApplyPlayerRelation(clan.Leader, 20);
     }
 }
        public void OnDetection(Settlement settlement)
        {
            try
            {
                int   stealRelationPenalty           = KleptomaniaSubModule.settings.StealRelationPenalty;
                float currentTownStealCrimeRating    = KleptomaniaSubModule.settings.TownStealCrimeRating;
                float currentVillageStealCrimeRating = KleptomaniaSubModule.settings.VillageStealCrimeRating;

                if (Hero.MainHero.MapFaction != null && settlement.MapFaction != null)
                {
                    if (Hero.MainHero.MapFaction == settlement.MapFaction)     //if from player faction: realtion penalty x2, decreases relation with players faction leader
                    {
                        stealRelationPenalty *= 2;
                        ChangeRelationAction.ApplyRelationChangeBetweenHeroes(Hero.MainHero, settlement.MapFaction.Leader, stealRelationPenalty, true);
                        KleptomaniaSubModule.Log.Info("Stealing | Faction Leader Hero " + settlement.MapFaction.Leader.Name + "decreases relation with player by " + stealRelationPenalty.ToString());
                    }
                }

                if (settlement.OwnerClan.Leader != null)
                {
                    ChangeRelationAction.ApplyRelationChangeBetweenHeroes(Hero.MainHero, settlement.OwnerClan.Leader, stealRelationPenalty, true);        //decreases relation with settlement owner
                    KleptomaniaSubModule.Log.Info("Stealing | Settlement owner Hero " + settlement.OwnerClan.Leader.Name + "decreases relation with player by " + stealRelationPenalty.ToString());
                }

                if (settlement.Notables != null)
                {
                    foreach (Hero notableHero in settlement.Notables)     //decreases relation with notables
                    {
                        if (notableHero != null && !notableHero.IsGangLeader)
                        {
                            ChangeRelationAction.ApplyRelationChangeBetweenHeroes(Hero.MainHero, notableHero, stealRelationPenalty, true);
                            KleptomaniaSubModule.Log.Info("Stealing | Notable Hero " + notableHero.Name + "decreases relation with player by " + stealRelationPenalty.ToString());
                        }
                    }
                }

                if (settlement.IsTown)
                {
                    ChangeCrimeRatingAction.Apply(settlement.MapFaction, currentTownStealCrimeRating, true);
                    KleptomaniaSubModule.Log.Info("Stealing | Faction " + settlement.MapFaction.Name + " crime rating increases with player by " + currentTownStealCrimeRating.ToString());
                }
                else if (settlement.IsVillage)
                {
                    ChangeCrimeRatingAction.Apply(settlement.MapFaction, currentVillageStealCrimeRating, true);
                    KleptomaniaSubModule.Log.Info("Stealing | Faction " + settlement.Name + " crime rating increases with player by " + currentVillageStealCrimeRating.ToString());
                }
            }
            catch (Exception ex)
            {
                InformationManager.DisplayMessage(new InformationMessage("Kleptomania: An error occured adding consequences for detection. Check the Log file.", Colors.Red));
                KleptomaniaSubModule.Log.Info("Stealing | Exception in DetectionConsequence: " + ex.Message);
            }
        }
Пример #13
0
        private void ExecutePropose()
        {
            GiveGoldToClanAction.ApplyFromHeroToClan(Hero.MainHero, _clan, IntValue);

            var relationValue = GetBaseRelationValueOfCurrentGoldCost();

            if (relationValue > 0)
            {
                ChangeRelationAction.ApplyPlayerRelation(_clan.Leader, relationValue);
            }

            _onFinalize();
        }
Пример #14
0
        private Kingdom GoRebelKingdom(IEnumerable <Clan> clans)
        {
            var ruler = clans.First();
            // create a new kingdom for the clan
            TextObject kingdomIntroText = new TextObject("{=Separatism_Kingdom_Intro_National}{RebelKingdom} was found in {Year} when {Culture} people of {Kingdom} have made a declaration of independence.", null);

            try
            {
                kingdomIntroText.SetTextVariable("Year", CampaignTime.Now.GetYear);
                kingdomIntroText.SetTextVariable("Culture", ruler.Culture.Name);
                kingdomIntroText.SetTextVariable("Kingdom", ruler.Kingdom.Name);
            }
            catch (Exception e)
            {
                // prevent mysterious rare crash
                GameLog.Error(e);
                return(null);
            }
            var capital = ruler.Settlements.OrderByDescending(x => x.Prosperity).First();
            var kingdom = ruler.CreateKingdom(capital, kingdomIntroText);

            // keep policies from the old clan kingdom
            foreach (var policy in ruler.Kingdom.ActivePolicies)
            {
                kingdom.AddPolicy(policy);
            }
            // move all clans into the new kingdom
            foreach (var clan in clans)
            {
                clan.ChangeKingdom(kingdom, true);
            }
            // make relation changes for participating clans
            int relationChange = SeparatismConfig.Settings.RelationChangeNationalRebellionClans;

            if (relationChange != 0)
            {
                Queue <Clan> clanQueue = new Queue <Clan>(clans);
                while (clanQueue.Count > 1)
                {
                    var c1 = clanQueue.Dequeue();
                    foreach (var c2 in clanQueue)
                    {
                        ChangeRelationAction.ApplyRelationChangeBetweenHeroes(c1.Leader, c2.Leader, relationChange, true);
                    }
                }
            }

            return(kingdom);
        }
        private static void ApplyInternal(Hero hero, Hero toHero, int relation, int cap, bool showQuickNotification = true)
        {
            if (!MercenarySettings.Instance.ApplyRelationshipRulesToNPC && hero != Hero.MainHero)
            {
                return;
            }

            //var contractorKingdomHeroRelation = hero.GetRelation(toHero);
            var contractorKingdomHeroRelation = CharacterRelationManager.GetHeroRelation(hero, toHero);

            if (contractorKingdomHeroRelation + relation < cap)
            {
                ChangeRelationAction.ApplyRelationChangeBetweenHeroes(hero, toHero, relation, showQuickNotification && hero == Hero.MainHero);
            }
        }
Пример #16
0
        public static void Apply(Settlement settlement, Clan grantedClan)
        {
            ChangeOwnerOfSettlementAction.ApplyByDefault(grantedClan.Leader, settlement);

            int relationChange = CalculateBaseRelationChange(settlement);

            ChangeRelationAction.ApplyPlayerRelation(grantedClan.Leader, relationChange);

            foreach (Clan clan in Clan.PlayerClan.Kingdom.Clans.Where(clan => clan != grantedClan && clan != Clan.PlayerClan))
            {
                ChangeRelationAction.ApplyPlayerRelation(clan.Leader, Settings.Instance.GrantFiefRelationPenalty);
            }

            Events.Instance.OnFiefGranted(settlement.Town);
        }
Пример #17
0
        public override void DoEnd()
        {
            var plot = Goal.Plot;

            var name         = new TextObject(plot.Target.ToKingdom().InformalName + " Seperatists");
            var informalName = new TextObject(plot.Leader.ToHero().Clan.InformalName.ToString());

            var oldKingdom = plot.Target.ToKingdom();
            var rebel      = KingdomHelper.CreateKingdom(plot.Leader.ToHero(), name, informalName, plot.Leader.ToHero().Clan.Banner, true);

            foreach (var member in plot.Members.Where(member => member.ToHero().Clan.Kingdom != rebel))
            {
                ChangeKingdomAction.ApplyByJoinToKingdom(member.ToHero().Clan, rebel);
            }

            DeclareWarAction.Apply(rebel, oldKingdom);

            foreach (var hero in oldKingdom.Lords)
            {
                var warRelationChange  = Settings.WarRelationshipChange;
                var allyRelationChange = Settings.AllyRelationshipChange / 2;

                if (hero.IsFactionLeader())
                {
                    warRelationChange  *= Settings.LeaderRelationshipChangeFactor;
                    allyRelationChange *= Settings.LeaderRelationshipChangeFactor;
                }

                foreach (var ally in oldKingdom.Lords)
                {
                    ChangeRelationAction.ApplyRelationChangeBetweenHeroes(hero, ally, (int)allyRelationChange);
                }

                foreach (var enemy in rebel.Lords)
                {
                    ChangeRelationAction.ApplyRelationChangeBetweenHeroes(hero, enemy, (int)warRelationChange);
                }

                foreach (var ally in rebel.Lords)
                {
                    ChangeRelationAction.ApplyRelationChangeBetweenHeroes(hero, ally, (int)allyRelationChange);
                }
            }

            InformationManager.AddNotice(new WarMapNotification(rebel, oldKingdom, new TextObject($"Civil War breaks out in {oldKingdom.Name}")));

            LogHelper.Log("Successful Revolt created: " + rebel.Name);
        }
Пример #18
0
        public override void OnAgentRemoved(Agent affectedAgent, Agent affectorAgent, AgentState agentState, KillingBlow blow)
        {
            if (!_config.AI.PersonalEffects.Enabled)
            {
                return;
            }
            if (Campaign.Current == null)
            {
                return;
            }
            if (affectedAgent.Character == null)
            {
                return;
            }
            if (!affectedAgent.IsHero)
            {
                return;
            }

            if (_personalDeathEffectAgentList.Contains(affectedAgent) && affectorAgent == Agent.Main)
            {
                try {
                    var killedHero = Hero.FindFirst(x => x.StringId == affectedAgent.Character.StringId);
                    var playerHero = Hero.FindFirst(x => x.StringId == affectorAgent.Character.StringId);

                    ChangeRelationAction.ApplyPlayerRelation(killedHero, _config.AI.PersonalEffects.RelationshipChange, false, true);
                    playerHero.Clan.AddRenown(_config.AI.PersonalEffects.RenownGain);

                    Helpers.Say("{=death_personal_effect}" + _strings.Lord.DeathPersonalEffect
                                .Replace("$NAME$", affectedAgent?.Name ?? "")
                                .Replace("$RENOWN$", _config.AI.PersonalEffects.RenownGain.ToString())
                                .Replace("$RELATIONSHIPHIT$", _config.AI.PersonalEffects.RelationshipChange.ToString()),
                                new Dictionary <string, TextObject> {
                        { "NAME", new TextObject(affectedAgent?.Name ?? "") },
                        { "RENOWN", new TextObject(_config.AI.PersonalEffects.RenownGain.ToString()) },
                        { "RELATIONSHIPHIT", new TextObject(_config.AI.PersonalEffects.RelationshipChange.ToString()) }
                    });
                } catch (Exception ex) {
                    if (_config.Cheering.DebugMode)
                    {
                        Helpers.Log($"{ex.Message}");
                        Helpers.Log($"{ex.StackTrace}");
                    }
                }
            }
        }
Пример #19
0
        private static void AdjustRelations(Clan usurpingClan, List <Clan> clans, int baseValue)
        {
            Hero leader = usurpingClan.Leader;

            foreach (Clan clan in clans)
            {
                if (usurpingClan == clan)
                {
                    continue;
                }

                Hero otherLeader = clan.Leader;
                int  honor       = otherLeader.GetHeroTraits().Honor;
                int  calculating = otherLeader.GetHeroTraits().Calculating;
                int  value       = honor >= calculating ? baseValue : default;
                ChangeRelationAction.ApplyRelationChangeBetweenHeroes(leader, otherLeader, -value);
            }
        }
        public static void Apply(Settlement settlement, Clan grantedClan)
        {
            ChangeOwnerOfSettlementAction.ApplyByDefault(grantedClan.Leader, settlement);

            var relationChange = CalculateBaseRelationChange(settlement);

            ChangeRelationAction.ApplyPlayerRelation(grantedClan.Leader, relationChange);

            foreach (var clan in Clan.PlayerClan.Kingdom.Clans.Where(c => c != grantedClan && c != Clan.PlayerClan))
            {
                ChangeRelationAction.ApplyPlayerRelation(clan.Leader, Settings.Instance !.GrantFiefRelationPenalty);
            }

            // gain generosity when granting fief
            PlayerCharacterTraitEventExperience.FiefGranted.Apply();

            Events.Instance.OnFiefGranted(settlement.Town);
        }
Пример #21
0
        private void EndQuestBySidingWithMerchantConsequence()
        {
            var garrisonParty   = QuestGiver.CurrentSettlement.Town.GarrisonParty;
            var jawwalPrisoners = GetJawwalPrisoners();
            var reward          = 0;

            foreach (var prisoner in jawwalPrisoners)
            {
                garrisonParty.AddPrisoner(prisoner, 1);
                EnterSettlementAction.ApplyForPrisoner(prisoner.HeroObject, QuestGiver.CurrentSettlement);
                CampaignEvents.Instance.OnPlayerDonatedHeroPrisoner(prisoner.HeroObject, QuestGiver.CurrentSettlement);
                reward += 1000;
            }

            Hero.MainHero.ChangeHeroGold(reward);
            ChangeRelationAction.ApplyPlayerRelation(QuestGiver, 50);
            CompleteQuestWithSuccess();
        }
Пример #22
0
        public static void Postfix(Clan mercenaryClan, Kingdom kingdom, bool showNotification)
        {
            // Let NPC's logic control leaving for now.
            if (/*!MercenaryContractOptions.ApplyRelationshipRulesToNPC && */ mercenaryClan != Clan.PlayerClan)
            {
                return;
            }

            var isAtWar = FactionManager.GetEnemyFactions(kingdom).Any();

            foreach (var contractorClan in kingdom.Clans)
            {
                ChangeRelationAction.ApplyRelationChangeBetweenHeroes(
                    mercenaryClan.Leader,
                    contractorClan.Leader,
                    isAtWar ? MercenarySettings.Instance.LeavingLossWar : MercenarySettings.Instance.LeavingLossPeace,
                    true);
            }
        }
        private void ArmSeperatists()
        {
            List <InquiryElement> inquiryElements = new List <InquiryElement>();

            foreach (ItemRosterElement item in PartyBase.MainParty.ItemRoster)
            {
                if (isWeapon(item.EquipmentElement.Item))
                {
                    inquiryElements.Add(new InquiryElement((object)new Tuple <EquipmentElement, int>(item.EquipmentElement, item.Amount), (item.EquipmentElement.ItemModifier == null ? item.EquipmentElement.Item.Name.ToString() : (item.EquipmentElement.ItemModifier.Name.ToString()) + item.EquipmentElement.Item.Name.ToString()) + " - " + item.Amount, new ImageIdentifier(item.EquipmentElement.Item)));
                }
            }
            if (inquiryElements.Count < 1)
            {
                InformationManager.ShowInquiry(new InquiryData("No weapons in inventory", "", true, false, "OK", "", (Action)null, (Action)null), true);
                GameMenu.SwitchToMenu("town");
            }
            else
            {
                InformationManager.ShowMultiSelectionInquiry(new MultiSelectionInquiryData("", "Select Weapons to give seperatists", inquiryElements, true, 1000, "Continue", (string)null, (Action <List <InquiryElement> >)(args =>
                {
                    List <InquiryElement> source = args;
                    if (source != null && !source.Any <InquiryElement>())
                    {
                        return;
                    }
                    InformationManager.HideInquiry();
                    float WeaponsValue = 0;
                    IEnumerable <Tuple <EquipmentElement, int> > selected = args.Select <InquiryElement, Tuple <EquipmentElement, int> >((Func <InquiryElement, Tuple <EquipmentElement, int> >)(element => element.Identifier as Tuple <EquipmentElement, int>));
                    foreach (Tuple <EquipmentElement, int> pair in selected)
                    {
                        WeaponsValue += pair.Item2 * (2 + Math.Min((int)pair.Item1.Item.Tierf, 6));
                        PartyBase.MainParty.ItemRoster.Remove(new ItemRosterElement(pair.Item1, pair.Item2));
                    }
                    Settlement.CurrentSettlement.Militia += WeaponsValue / 2;
                    float loyaltyChange = Math.Min(100 * (WeaponsValue / Math.Max(Settlement.CurrentSettlement.Town.Prosperity, 1)), Settlement.CurrentSettlement.Town.Loyalty);
                    Settlement.CurrentSettlement.Town.Loyalty -= loyaltyChange;
                    ChangeRelationAction.ApplyPlayerRelation(Settlement.CurrentSettlement.OwnerClan.Leader, (int)(-1 * loyaltyChange));
                    ChangeCrimeRatingAction.Apply(Settlement.CurrentSettlement.MapFaction, loyaltyChange);
                    Hero.MainHero.AddSkillXp(DefaultSkills.Roguery, WeaponsValue * 10);
                }), (Action <List <InquiryElement> >)null));
            }
        }
Пример #24
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."));
     }
 }
Пример #25
0
        public override void OnDelivery()
        {
            CPSModule.DebugMessage("OnDelivery called.", log);
            float relationWithSender = (float)Recipient.GetRelation(Sender);
            float roll = MBRandom.RandomFloat;

            CPSModule.DebugMessage($"relationWithSender: {relationWithSender}, roll: {roll}", log);
            if (roll <= (100.0f - relationWithSender) / 100.0f)
            {
                if (Hero.MainHero == Sender)
                {
                    CPSModule.InfoMessage($"{Recipient} appreciated your letter.");
                }

                ChangeRelationAction.ApplyRelationChangeBetweenHeroes(Sender, Recipient, 1);
            }
            else if (Hero.MainHero == Sender)
            {
                CPSModule.InfoMessage($"{Recipient} received your letter.");
            }
        }
Пример #26
0
        private void InitializeSiege(Hero leader, Clan clan, Settlement target, MobileParty party)
        {
            try
            {
                FactionManager.DeclareWar(leader.MapFaction, target.MapFaction);

                Campaign.Current.FactionManager.RegisterCampaignWar(leader.MapFaction, target.MapFaction);

                ChangeRelationAction.ApplyRelationChangeBetweenHeroes(leader, clan.Leader, -20, false);

                ChangeRelationAction.ApplyRelationChangeBetweenHeroes(leader, clan.Kingdom.Leader, -20, false);

                party.Ai.SetDoNotMakeNewDecisions(true);

                SetPartyAiAction.GetActionForBesiegingSettlement(party, target);
            }
            catch (Exception e)
            {
                Log.Info("Exception when trying to siege settlement");
                Log.Error(e);
            }
        }
        public void ApplyAssassinationFailedConsequences(Settlement settlement, Hero assassin, Hero victim)
        {
            ChangeRelationAction.ApplyRelationChangeBetweenHeroes(assassin, victim, -100, true);

            DeclareWarBetweenHeros(assassin, victim, out var declareWarMessage);

            TakeGoldFromHero(assassin, victim.Clan, out var goldLossMessage);

            TakeHeroCaptive(settlement, assassin, out var takeCaptiveMessage);

            var message = goldLossMessage.ToString()
                          + $"\n{declareWarMessage}"
                          + $"\n{takeCaptiveMessage}";

            var inquiry = new InquiryData(
                "Captured",
                message,
                true,
                false,
                "Continue",
                string.Empty,
                null,
                null
                );

            InformationManager.ShowInquiry(inquiry);

            _assassinationHistoryService.AddAssassinationEvent(new AssassinationEvent()
            {
                Settlement   = settlement,
                Assassin     = assassin,
                Victim       = victim,
                Succeeded    = false,
                CampaignTime = CampaignTime.Now
            });
        }
Пример #28
0
        public void CreateVassal()
        {
            //Settlement settlement = GetCandidateSettlements().FirstOrDefault<Settlement>();
            if (targetSettlement == null)
            {
                return;
            }
            Hero hero = Hero.OneToOneConversationHero;

            if (hero == null)
            {
                return;
            }
            Kingdom kingdom = Hero.MainHero.MapFaction as Kingdom;

            if (kingdom == null)
            {
                return;
            }

            CultureObject culture  = targetSettlement.Culture;
            TextObject    clanName = NameGenerator.Current.GenerateClanName(culture, targetSettlement);
            string        str      = Guid.NewGuid().ToString().Replace("-", "");

            if (null == hero.LastSeenPlace)
            {
                hero.CacheLastSeenInformation(hero.HomeSettlement, true);
                hero.SyncLastSeenInformation();
            }
            //RemoveCompanionAction.ApplyByFire(Hero.MainHero.Clan, hero);
            //for  1.4.3 200815
            HeroOperation.DealApplyByFire(Hero.MainHero.Clan, hero);

            HeroOperation.SetOccupationToLord(hero);
            hero.ChangeState(Hero.CharacterStates.Active);
            Clan   clan   = TaleWorlds.ObjectSystem.MBObjectManager.Instance.CreateObject <Clan>("sue_clan_" + str);
            Banner banner = Banner.CreateRandomClanBanner(-1);

            clan.InitializeClan(clanName, clanName, culture, banner);
            clan.SetLeader(hero);

            //clan.Tier = 5; 修改家族等级
            FieldInfo fieldInfoId = clan.GetType().GetField("_tier", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance);

            if (null != fieldInfoId)
            {
                fieldInfoId.SetValue(clan, selectClanTier);
            }
            //增加一些影响力
            clan.AddRenown(50 * selectClanTier, true);


            hero.Clan        = clan;
            hero.CompanionOf = null;
            hero.IsNoble     = true;
            hero.SetTraitLevel(DefaultTraits.Commander, 1);

            MobileParty mobileParty = clan.CreateNewMobileParty(hero);

            mobileParty.ItemRoster.AddToCounts(DefaultItems.Grain, 10);
            mobileParty.ItemRoster.AddToCounts(DefaultItems.Meat, 5);

            ChangeOwnerOfSettlementAction.ApplyByKingDecision(hero, targetSettlement);
            clan.UpdateHomeSettlement(targetSettlement);


            int takeMoney = TakeMoneyByTier(selectClanTier);

            if (targetSpouse != null)
            {
                GiveGoldAction.ApplyBetweenCharacters(Hero.MainHero, hero, takeMoney / 2, false);
            }
            else
            {
                GiveGoldAction.ApplyBetweenCharacters(Hero.MainHero, hero, takeMoney, false);
            }

            //关系处理
            //新晋家族关系增加
            int shipIncreate = ShipIncreateByTier(selectClanTier);

            ChangeRelationAction.ApplyPlayerRelation(hero, shipIncreate, true, true);
            if (targetSpouse != null)
            {
                ChangeRelationAction.ApplyPlayerRelation(targetSpouse, shipIncreate, true, true);
            }

            //以前家族关系减低,
            int     shipReduce = ShipReduceByTier(selectClanTier);
            Kingdom kindom     = Hero.MainHero.MapFaction as Kingdom;

            if (null != kindom && shipReduce > 0)
            {
                kindom.Clans.ToList().ForEach((obj) =>
                {
                    if (obj != Clan.PlayerClan)
                    {
                        ChangeRelationAction.ApplyPlayerRelation(obj.Leader, shipReduce * -1, true, true);
                    }
                }
                                              );
            }

            if (targetSpouse != null)
            {
                targetSpouse.Spouse = hero;
                InformationManager.AddQuickInformation(new TextObject($"{hero.Name} marry with {targetSpouse.Name}"), 0, null, "event:/ui/notification/quest_finished");

                HeroOperation.DealApplyByFire(Hero.MainHero.Clan, targetSpouse);
                //RemoveCompanionAction.ApplyByFire(Hero.MainHero.Clan, targetSpouse);

                targetSpouse.ChangeState(Hero.CharacterStates.Active);
                targetSpouse.IsNoble = true;
                HeroOperation.SetOccupationToLord(targetSpouse);
                targetSpouse.CompanionOf = null;
                targetSpouse.Clan        = clan;
                targetSpouse.SetTraitLevel(DefaultTraits.Commander, 1);
                //AddCompanionAction.Apply(clan, targetSpouse);

                MobileParty targetSpouseMobileParty = clan.CreateNewMobileParty(targetSpouse);

                targetSpouseMobileParty.ItemRoster.AddToCounts(DefaultItems.Grain, 10);
                targetSpouseMobileParty.ItemRoster.AddToCounts(DefaultItems.Meat, 5);
                GiveGoldAction.ApplyBetweenCharacters(Hero.MainHero, targetSpouse, takeMoney / 2, false);
            }

            // 他们孩子处理
            if (isTogetherWithThireChildren)
            {
                DealTheirChildren(hero, clan);
            }


            //加入王国
            ChangeKingdomAction.ApplyByJoinToKingdom(clan, kingdom, true);
        }
Пример #29
0
        private bool CheckWarState(KingdomInfo kingdomInfo, List <Clan> clans)
        {
            var loyalClans    = new List <Clan>();
            var plottingClans = new List <Clan>();

            foreach (var clan in clans)
            {
                var clanLeader     = clan.Leader;
                var clanLeaderInfo = Managers.Character.Get(clanLeader.CharacterObject);

                if (clanLeaderInfo.PlotState == PlotState.IsLoyal)
                {
                    loyalClans.Add(clan);
                }
                else if (clanLeaderInfo.PlotState == PlotState.IsPlotting)
                {
                    plottingClans.Add(clan);
                }
            }

            if (plottingClans.Count == 0)
            {
                if (RevolutionsSettings.Instance.DebugMode)
                {
                    InformationManager.DisplayMessage(new InformationMessage($"Revolutions.CivilWars: There are no plotting clans.", ColorHelper.Gray));
                }

                return(true);
            }

            var loyalTroopWeight = kingdomInfo.Kingdom.RulingClan.TotalStrength;

            foreach (var loyalClan in loyalClans)
            {
                loyalTroopWeight += loyalClan.TotalStrength;
            }

            var plottersTroopWeight = 0f;

            foreach (var plotterClan in plottingClans)
            {
                plottersTroopWeight += plotterClan.TotalStrength;
            }

            var plotLeadingClan = plottingClans.OrderByDescending(go => go.Tier).FirstOrDefault();

            if (plotLeadingClan == null)
            {
                return(true);
            }

            var kingdomLeader  = kingdomInfo.Kingdom.Leader;
            var plottingLeader = plotLeadingClan.Leader;

            var kingdomLeaderGenerosity  = kingdomLeader.GetHeroTraits().Generosity;
            var kingdomLeaderMercy       = kingdomLeader.GetHeroTraits().Mercy;
            var kingdomLeaderValor       = kingdomLeader.GetHeroTraits().Valor;
            var kingdomLeaderCalculating = kingdomLeader.GetHeroTraits().Calculating;

            var plottingLeaderGenerosity  = plottingLeader.GetHeroTraits().Generosity;
            var plottingLeaderMercy       = plottingLeader.GetHeroTraits().Mercy;
            var plottingLeaderValor       = plottingLeader.GetHeroTraits().Valor;
            var plottingLeaderCalculating = plottingLeader.GetHeroTraits().Calculating;

            float personalityTraits   = plottingLeaderGenerosity + kingdomLeaderGenerosity + plottingLeaderMercy + kingdomLeaderMercy;
            var   personalityWeight   = MathF.Pow(RevolutionsSettings.Instance.CivilWarsWarPersonalityMultiplier, -personalityTraits);
            var   troopWeight         = plottersTroopWeight / loyalTroopWeight;
            float valorModifier       = 1 + (plottingLeaderValor <= 0 ? 1 : plottingLeaderValor * 2);
            float clanCountModifier   = plottingClans.Count / (loyalClans.Count + 1);
            float calculatingModifier = 1 + (plottingLeaderCalculating <= 0 ? 1 : plottingLeaderCalculating);

            var warChance = RevolutionsSettings.Instance.CivilWarsWarBaseChance * personalityWeight * (troopWeight * valorModifier) * MathF.Pow(clanCountModifier, calculatingModifier);

            if (RevolutionsSettings.Instance.DebugMode)
            {
                InformationManager.DisplayMessage(new InformationMessage($"Revolutions.CivilWars: War Chance is {warChance}%.", ColorHelper.Gray));
            }

            if (warChance > new Random().Next(0, 100))
            {
                if (kingdomInfo.Id == Hero.MainHero.Clan.Kingdom?.StringId && EventManager.Instance.InEvent)
                {
                    return(true);
                }

                if (kingdomInfo.Id == Hero.MainHero.Clan.Kingdom?.StringId && kingdomLeader.StringId != Hero.MainHero.StringId)
                {
                    new WarEvent();
                }

                loyalClans.Clear();
                plottingClans.Clear();
                foreach (var clan in clans)
                {
                    var clanLeader     = clan.Leader;
                    var clanLeaderInfo = Managers.Character.Get(clanLeader.CharacterObject);

                    if (clanLeaderInfo.PlotState == PlotState.IsLoyal)
                    {
                        loyalClans.Add(clan);
                    }
                    else if (clanLeaderInfo.PlotState == PlotState.IsPlotting)
                    {
                        plottingClans.Add(clan);
                    }
                }

                if (plottingClans.Count == 0)
                {
                    if (RevolutionsSettings.Instance.DebugMode)
                    {
                        InformationManager.DisplayMessage(new InformationMessage($"Revolutions.CivilWars: There are no plotting clans.", ColorHelper.Gray));
                    }

                    return(true);
                }

                Managers.Character.Get(plottingLeader.CharacterObject).IsCivilWarKingdomLeader = true;

                var settlementInfo = Managers.Settlement.Get(plotLeadingClan.HomeSettlement);
                var bannerInfo     = Managers.Banner.GetBanner(settlementInfo);

                var textObject = new TextObject(Localization.GameTexts.CivilWarsKingdom);
                textObject.SetTextVariable("CLAN", plottingLeader.Name);
                var plotKingdom = Managers.Kingdom.CreateKingdom(plotLeadingClan.Leader, textObject, textObject, bannerInfo != null ? new Banner(bannerInfo.BannerId) : plotLeadingClan.Banner, false);
                Managers.Kingdom.Get(plotKingdom).IsCivilWarKingdom = true;

                ChangeRelationAction.ApplyRelationChangeBetweenHeroes(plottingLeader, kingdomLeader, -(int)(RevolutionsSettings.Instance.CivilWarsRelationshipChange * (RevolutionsSettings.Instance.CivilWarsRelationshipChangeMultiplier * 2)), false);

                foreach (var clan1 in clans.Where(c1 => c1.StringId != plotLeadingClan.StringId))
                {
                    var clanLeader1 = Managers.Character.Get(clan1.Leader.CharacterObject);
                    if (clanLeader1.PlotState == PlotState.IsLoyal)
                    {
                        ChangeRelationAction.ApplyRelationChangeBetweenHeroes(clan1.Leader, kingdomLeader, (int)(RevolutionsSettings.Instance.CivilWarsRelationshipChange * RevolutionsSettings.Instance.CivilWarsRelationshipChangeMultiplier), false);
                        ChangeRelationAction.ApplyRelationChangeBetweenHeroes(clan1.Leader, plottingLeader, -(int)(RevolutionsSettings.Instance.CivilWarsRelationshipChange * RevolutionsSettings.Instance.CivilWarsRelationshipChangeMultiplier), false);
                    }
                    else if (clanLeader1.PlotState == PlotState.IsPlotting)
                    {
                        ChangeRelationAction.ApplyRelationChangeBetweenHeroes(clan1.Leader, plottingLeader, (int)(RevolutionsSettings.Instance.CivilWarsRelationshipChange * RevolutionsSettings.Instance.CivilWarsRelationshipChangeMultiplier), false);
                        ChangeRelationAction.ApplyRelationChangeBetweenHeroes(clan1.Leader, kingdomLeader, -(int)(RevolutionsSettings.Instance.CivilWarsRelationshipChange * RevolutionsSettings.Instance.CivilWarsRelationshipChangeMultiplier), false);
                    }

                    foreach (var clan2 in clans.Where(c2 => c2.StringId != clan1.StringId && c2.StringId != plotLeadingClan.StringId))
                    {
                        var clanLeader2 = Managers.Character.Get(clan2.Leader.CharacterObject);

                        if (clanLeader1.PlotState == clanLeader2.PlotState)
                        {
                            ChangeRelationAction.ApplyRelationChangeBetweenHeroes(clan1.Leader, clan2.Leader, RevolutionsSettings.Instance.CivilWarsRelationshipChange, false);
                        }
                        else
                        {
                            ChangeRelationAction.ApplyRelationChangeBetweenHeroes(clan1.Leader, clan2.Leader, -RevolutionsSettings.Instance.CivilWarsRelationshipChange, false);
                        }
                    }
                }

                textObject = new TextObject(Localization.GameTexts.CivilWarsWarMapNotification);
                textObject.SetTextVariable("PLOTKINGDOM", plotKingdom.Name);
                textObject.SetTextVariable("KINGDOM", kingdomInfo.Kingdom.Name);
                InformationManager.AddNotice(new WarMapNotification(plotKingdom, kingdomInfo.Kingdom, textObject));

                textObject = new TextObject(Localization.GameTexts.CivilWarsQuickNotification);
                textObject.SetTextVariable("KINGDOM", kingdomInfo.Kingdom.Name);
                textObject.SetTextVariable("LEADER", plotLeadingClan.Leader.Name);
                textObject.SetTextVariable("CLAN", plotLeadingClan.Name);
                InformationManager.AddQuickInformation(textObject);

                var otherPlottingClans = plottingClans.Where(go => go.StringId != plotLeadingClan.StringId);
                if (otherPlottingClans.Count() == 0)
                {
                    textObject = new TextObject(Localization.GameTexts.CivilWarsLeaderAlone);
                    textObject.SetTextVariable("LEADER", plotLeadingClan.Leader.Name);
                    textObject.SetTextVariable("CLAN", plotLeadingClan.Name);
                    InformationManager.DisplayMessage(new InformationMessage(textObject.ToString(), ColorHelper.Orange));
                }

                foreach (var plottingClan in otherPlottingClans)
                {
                    textObject = new TextObject(Localization.GameTexts.CivilWarsJoinsConspirators);
                    textObject.SetTextVariable("LEADER", plottingClan.Leader.Name);
                    textObject.SetTextVariable("CLAN", plottingClan.Name);
                    InformationManager.DisplayMessage(new InformationMessage(textObject.ToString(), ColorHelper.Orange));

                    ChangeKingdomAction.ApplyByJoinToKingdom(plottingClan, plotKingdom, false);
                }

                foreach (var loyalClan in loyalClans)
                {
                    textObject = new TextObject(Localization.GameTexts.CivilWarsJoinsConspirators);
                    textObject.SetTextVariable("LEADER", loyalClan.Leader.Name);
                    textObject.SetTextVariable("CLAN", loyalClan.Name);
                    InformationManager.DisplayMessage(new InformationMessage(textObject.ToString(), ColorHelper.Orange));
                }

                DeclareWarAction.Apply(plotKingdom, kingdomInfo.Kingdom);

                if (RevolutionsSettings.Instance.CivilWarsKeepExistingWars)
                {
                    foreach (var enemyFaction in FactionManager.GetEnemyFactions(kingdomInfo.Kingdom).ToList())
                    {
                        if (!enemyFaction.Equals(plotKingdom))
                        {
                            DeclareWarAction.Apply(plotKingdom, enemyFaction);
                        }
                    }
                }

                Managers.CivilWar.CivilWars.Add(new CivilWar(kingdomInfo.Kingdom, clans));
                kingdomInfo.HasCivilWar = true;
            }

            return(false);
        }
Пример #30
0
        private void OnDailyTickClan(Clan clan)
        {
            var kingdom = clan.Kingdom;

            if (kingdom == null ||
                clan == Clan.PlayerClan ||
                clan.IsUnderMercenaryService ||
                !clan.Leader.IsAlive ||
                clan.Leader.IsPrisoner ||
                clan.Fortifications.Any(x => x.IsUnderSiege) ||
                clan.Parties.Any(x => x.MapEvent != null))
            {
                return;
            }
            var ruler = kingdom.Ruler;

            if (clan.Leader != ruler)
            {
                if (!SeparatismConfig.Settings.LordRebellionsEnabled)
                {
                    return;
                }

                var hasReason      = !clan.Leader.HasGoodRelationWith(ruler);
                var kingdomFiefs   = kingdom.GetFiefsAmount();
                var kingdomClans   = kingdom.Clans.Count(x => !x.IsUnderMercenaryService);
                var clanFiefs      = clan.GetFiefsAmount();
                var hasEnoughFiefs = (kingdomFiefs > 0 &&
                                      ((SeparatismConfig.Settings.AverageAmountOfKingdomFiefsIsEnoughToRebel && clanFiefs >= (float)kingdomFiefs / kingdomClans) ||
                                       SeparatismConfig.Settings.MinimalAmountOfKingdomFiefsToRebel <= clanFiefs));
                var rebelRightNow = SeparatismConfig.Settings.DailyLordRebellionChance >= 1 ||
                                    (MBRandom.RandomFloat <= SeparatismConfig.Settings.DailyLordRebellionChance);

                if (hasReason && hasEnoughFiefs && rebelRightNow)
                {
                    var rebelKingdom = GoRebelKingdom(clan);
                    var textObject   = new TextObject("{=Separatism_Clan_Rebel}The {ClanName} have broken from {Kingdom} to found the {RebelKingdom}.", null);
                    textObject.SetTextVariable("ClanName", clan.Name);
                    textObject.SetTextVariable("Kingdom", kingdom.Name);
                    textObject.SetTextVariable("RebelKingdom", rebelKingdom.Name);
                    GameLog.Warn(textObject.ToString());
                }
            }
            else
            {
                if (kingdom.Clans.Where(x => x.Leader.IsAlive).Count() == 1) // kingdom has the only one ruler clan
                {
                    if (clan.Settlements.Count() == 0)                       // no any fiefs
                    {
                        clan.ChangeKingdom(null, false);
                        var textObject = new TextObject("{=Separatism_Kingdom_Abandoned}The {Kingdom} has been destroyed and the {ClanName} are in search of a new sovereign.", null);
                        textObject.SetTextVariable("Kingdom", kingdom.Name);
                        textObject.SetTextVariable("ClanName", clan.Name);
                        GameLog.Warn(textObject.ToString());
                    }
                    else                     // look for ally
                    {
                        var enemies         = FactionManager.GetEnemyKingdoms(kingdom).ToArray();
                        var potentialAllies = enemies
                                              .SelectMany(x => FactionManager.GetEnemyKingdoms(x))
                                              .Distinct()
                                              .Except(enemies)
                                              .Intersect(clan.CloseKingdoms())
                                              .Where(x => x != kingdom && x.Settlements.Count() > 0)
                                              .ToArray();
                        foreach (var pa in potentialAllies)
                        {
                            if (kingdom.Leader.HasGoodRelationWith(pa.Leader) &&
                                pa.Leader.Clan.Tier >= clan.Tier)
                            {
                                var commonEnemies = FactionManager.GetEnemyKingdoms(pa)
                                                    .Intersect(enemies)
                                                    .Where(x => x.Settlements.Count() > 0)
                                                    .ToArray();
                                foreach (var enemy in commonEnemies)
                                {
                                    var kingdomDistance  = enemy.FactionMidPoint.Distance(kingdom.FactionMidPoint);
                                    var paDistance       = enemy.FactionMidPoint.Distance(pa.FactionMidPoint);
                                    var allianceDistance = kingdom.FactionMidPoint.Distance(pa.FactionMidPoint);

                                    if (allianceDistance <= Math.Sqrt(kingdomDistance * kingdomDistance + paDistance * paDistance) ||
                                        (kingdom.IsInsideKingdomTeritory(enemy) && pa.IsInsideKingdomTeritory(enemy)))
                                    {
                                        clan.ChangeKingdom(pa, false);
                                        var textObject = new TextObject("{=Separatism_Kingdom_Union}The {Kingdom} has joined to the {Ally} to fight against common enemy the {Enemy}.", null);
                                        textObject.SetTextVariable("Kingdom", kingdom.Name);
                                        textObject.SetTextVariable("Ally", pa.Name);
                                        textObject.SetTextVariable("Enemy", enemy.Name);
                                        GameLog.Warn(textObject.ToString());
                                        return;
                                    }
                                }
                            }
                        }
                        // no ally kingdoms found, so look for friendly clans at least
                        var allyClan = Clan.All.ReadyToGo().Where(c =>
                                                                  c.Tier <= clan.Tier &&
                                                                  c.Leader.HasGoodRelationWith(clan.Leader))
                                       .OrderByDescending(c => c.TotalStrength)
                                       .FirstOrDefault();
                        if (allyClan != null)
                        {
                            allyClan.ChangeKingdom(kingdom, false);
                            int relationChange = SeparatismConfig.Settings.RelationChangeRulerWithSupporter;
                            if (relationChange != 0)
                            {
                                ChangeRelationAction.ApplyRelationChangeBetweenHeroes(clan.Leader, allyClan.Leader, relationChange, true);
                            }
                            var textObject = new TextObject("{=Separatism_Clan_Support}The {ClanName} have joined the {Kingdom} to support {Ruler}.", null);
                            textObject.SetTextVariable("ClanName", allyClan.Name);
                            textObject.SetTextVariable("Kingdom", kingdom.Name);
                            textObject.SetTextVariable("Ruler", kingdom.Ruler.Name);
                            GameLog.Warn(textObject.ToString());
                        }
                    }
                }
            }
        }