IEnumerable <int> FindAirDefenses()
        {
            airDefenses = AirDefense.Find();

            //After finding air Defenses, Sort them.
            if (airDefenses.Length > 1)
            {
                //Now that we found all Air Defenses, order them in the array with closest AD to Target first.
                Array.Sort(airDefenses, delegate(AirDefense ad1, AirDefense ad2)
                {
                    return(HumanLikeAlgorithms.DistanceFromPoint(ad1, mainTarget.DeployGrunts)
                           .CompareTo(HumanLikeAlgorithms.DistanceFromPoint(ad2, mainTarget.DeployGrunts)));
                });
            }
            else
            {
                Log.Error($"{Tag} Somehow no air defenses were found in Attack Phase. - Surrender.");
                surrender = true;
                yield break;
            }
        }
        IEnumerable <int> FindMainTarget()
        {
            if ((UserSettings.DeadSearch.MinDarkElixir == 0 && Opponent.IsDead()) || (UserSettings.ActiveSearch.MinDarkElixir == 0 && !Opponent.IsDead()))
            {
                //Trophy Push Mode!
                Log.Warning($"{Tag} Min Dark Elixir Setting = 0 - Trophy Push Mode - Target Town Hall Instead of Dark Elixir Storage.");

                var townHall = TownHall.Find(); //start with Cached.. usually always works.

                for (int i = 1; i < 11; i++)
                {
                    if (townHall != null)
                    {
                        break;
                    }

                    Log.Warning($"{Tag} Town Hall Cannot be found. Attempt:{i}  Retrying to Find Town Hall...");
                    //Somehow Town Hall is not found...  (Mabye Hero Walked in Front of it?)
                    yield return(1000);                                //Wait a little between each try

                    townHall = TownHall.Find(CacheBehavior.ForceScan); //Scan again - up to 10 times untill its found.
                }

                if (townHall == null)
                {
                    Log.Error($"{Tag} Town Hall Cannot be found in Attack Phase after 10 attempts! - Targeting the CENTER of the Map instead.");
                    TargetPoint(HumanLikeAlgorithms.Origin);
                }
                else
                {
                    TargetPoint(townHall.Location.GetCenter());
                    Log.Info($"{Tag} Town Hall targeted successfully.");
                }
            }
            else
            {
                mainTarget = HumanLikeAlgorithms.TargetDarkElixirStorage();

                for (int i = 1; i < 11; i++)
                {
                    if (mainTarget.ValidTarget)
                    {
                        break;
                    }

                    Log.Warning($"{Tag} Dark Elixir Storage Cannot be found. Attempt:{i}  Retrying to Find DE Storage...");
                    //Somehow DE Storage is not found on the rescan...  (Mabye Hero Walked in Front of it on Rescan?)
                    yield return(1000);                                                                //Wait a little between each try

                    mainTarget = HumanLikeAlgorithms.TargetDarkElixirStorage(CacheBehavior.ForceScan); //Scan again - up to 10 times untill its found.
                }

                //If DE Storage is STILL not valid... Use the Center of the Map!.
                if (!mainTarget.ValidTarget)
                {
                    Log.Error($"{Tag} Dark Elixir Storage Cannot be found in Attack Phase after 10 attempts! - Targeting the CENTER of the Map instead.");
                    TargetPoint(HumanLikeAlgorithms.Origin);
                }
                else
                {
                    Log.Info($"{Tag} Dark Elixir Storage targeted successfully.");
                }
            }

            //Create the Funnel Points
            deFunnelPoints      = mainTarget.GetFunnelingPoints(30);
            balloonFunnelPoints = mainTarget.GetFunnelingPoints(20);
        }
Exemple #3
0
        public override IEnumerable <int> AttackRoutine()
        {
            Log.Info($"{Tag}Deploy start - V.{Assembly.GetExecutingAssembly().GetName().Version.ToString()}");
            Log.Debug($"{Tag}Attack Identifier: [{AttackId}] - (Links Debug Images to Log File)");

            var attackStartTime = DateTime.UtcNow;

            //Write out all the Current Algorithm Settings...
            var settings = $"{Tag}Current Custom Settings Values:{Environment.NewLine}";

            foreach (var setting in AllCurrentSettings)
            {
                settings += $"{setting.InstanceType} Setting - '{setting.Name}' Value: {setting.Value}{Environment.NewLine}";
            }
            Log.Debug(settings);

            var waveCounter = 1;

            //Check if we can snipe the town hall, and if so, what are the Deployment points for Gruns/Ranged.
            TownHall townHall = TownHall.Find(CacheBehavior.Default);

            Target townHallTarget = townHall.GetSnipeDeployPoints();

            // Get starting resources
            LootResources preLoot = Opponent.GetAvailableLoot();

            if (preLoot == null)
            {
                Log.Error($"{Tag}Could not read available starting loot");
                Attack.Surrender();
                yield break;
            }
            Log.Info($"{Tag}Pre-attack resources - G: {preLoot.Gold}, E: {preLoot.Elixir}, DE: {preLoot.DarkElixir}");

            var collectorCacheBehavior = CacheBehavior.ForceScan;
            var collectorCount         = 0;
            var acceptableTargetRange  = CurrentSetting("Acceptable Target Range");

            acceptableTargetRange = acceptableTargetRange * acceptableTargetRange;
            var activeBase         = !Opponent.IsDead();
            var clanCastleDeployed = false;

            bool watchHeroes    = false;
            bool kingDeployed   = false;
            bool queenDeployed  = false;
            bool wardenDeployed = false;

            // Loop until surrender conditions are met
            while (true)
            {
                // Get all the units available
                Log.Info($"{Tag}Scanning troops for wave {waveCounter}");

                var allElements    = Attack.GetAvailableDeployElements();
                var deployElements = allElements.Where(x => x.UnitData != null).ToArray();
                var rangedUnits    = deployElements.Where(x => x.IsRanged == true && x.ElementType == DeployElementType.NormalUnit && x.UnitData.AttackType == AttackType.Damage);

                IEnumerable <DeployElement> gruntUnits = null;
                IEnumerable <DeployElement> tankUnits  = null;

                if (CurrentSetting("Use Valkyries as Tanks") == 0)
                {
                    gruntUnits = deployElements.Where(x => x.IsRanged == false && x.ElementType == DeployElementType.NormalUnit && x.UnitData.AttackType == AttackType.Damage);
                    tankUnits  = deployElements.Where(x => x.IsRanged == false && x.ElementType == DeployElementType.NormalUnit && x.UnitData.AttackType == AttackType.Tank);
                }
                else
                {
                    //Reclassify Valks as Tanks!
                    gruntUnits = deployElements.Where(x => x.IsRanged == false && x.ElementType == DeployElementType.NormalUnit && x.UnitData.AttackType == AttackType.Damage && x.Id != DeployId.Valkyrie);
                    tankUnits  = deployElements.Where(x => (x.IsRanged == false && x.ElementType == DeployElementType.NormalUnit && x.UnitData.AttackType == AttackType.Tank) || x.Id == DeployId.Valkyrie);
                }

                List <DeployElement> king      = allElements.Where(x => x.IsHero && x.Name.ToLower().Contains("king")).ToList();
                List <DeployElement> queen     = allElements.Where(x => x.IsHero && x.Name.ToLower().Contains("queen")).ToList();
                List <DeployElement> warden    = allElements.Where(x => x.IsHero && x.Name.ToLower().Contains("warden")).ToList();
                List <DeployElement> allHeroes = new List <DeployElement>();
                allHeroes.AddRange(king);
                allHeroes.AddRange(queen);
                allHeroes.AddRange(warden);

                //Write out all the unit pretty names we found...
                Log.Debug($"{Tag}Deployable Troops (wave {waveCounter}): {ToUnitString(allElements)}");

                var    outputDebugImage = (CurrentSetting("Debug Mode") == 1);
                double avgFillState     = 0;
                double avgCollectorLvl  = 0;

                //First time through force a Scan... after the first wave always recheck for Destroyed ones...
                Target[] targets = HumanLikeAlgorithms.GenerateTargets(algorithmName, acceptableTargetRange, IgnoreGold, IgnoreElixir, AttackId, out avgFillState, out avgCollectorLvl, collectorCacheBehavior, outputDebugImage, activeBase);

                collectorCount = targets.Length;

                Target reminderTarget = null;
                if (collectorCount > 0)
                {
                    reminderTarget = targets[0];
                }

                //Reorder the Deploy points so they look more human like when attacking.
                var groupedTargets = targets.ReorderToClosestNeighbor().GroupCloseTargets();

                collectorCacheBehavior = CacheBehavior.CheckForDestroyed;

                if (collectorCount < 1)
                {
                    Log.Info($"{Tag}Collectors Remaining = {collectorCount} - Deployment Done. Exiting Attack Loop.");
                    break;
                }

                int meleCount   = 0;
                int rangedCount = 0;
                int tankCount   = 0;

                if (CurrentSetting("Deploy All Troops Mode") == 0)
                {
                    //Determine Counts of each type of unit to use...
                    meleCount   = CurrentSetting("Ground Units Per Target");
                    rangedCount = CurrentSetting("Ranged Units Per Target");
                    tankCount   = CurrentSetting("Tank Units Per Target");
                }
                else
                {
                    //Get the total count of Valid Targets. (Including Town Hall if there is one.)
                    int totalTargetCount = targets.Length;

                    if (townHallTarget.ValidTarget)
                    {
                        totalTargetCount++;
                    }

                    //Will be the largest int without remainder.
                    meleCount   = gruntUnits.TotalUnitCount() / totalTargetCount;
                    rangedCount = rangedUnits.TotalUnitCount() / totalTargetCount;
                    tankCount   = tankUnits.TotalUnitCount() / totalTargetCount;

                    //Make sure if there are less than 1 per target, but still more than zero. set to 1.
                    if (tankCount <= 0 && tankUnits.TotalUnitCount() > 0)
                    {
                        tankCount = 1;
                    }
                    if (rangedCount <= 0 && rangedUnits.TotalUnitCount() > 0)
                    {
                        rangedCount = 1;
                    }
                    if (meleCount <= 0 && gruntUnits.TotalUnitCount() > 0)
                    {
                        meleCount = 1;
                    }
                }

                if (townHallTarget.ValidTarget)
                {
                    //Drop some Grunt and Ranged troups on the TH as well as collectors.
                    //If there are Teslas around it, oh well. we only spent 9-12 units  of each type trying.
                    if (gruntUnits.Any())
                    {
                        Log.Info($"{Tag}TH Snipe Dead {meleCount} Grunts Near: X:{townHallTarget.DeployGrunts.X} Y:{townHallTarget.DeployGrunts.Y}");
                        foreach (var t in Deploy.AtPoints(gruntUnits.FilterTypesByCount(), townHallTarget.DeployGrunts.RandomPointsInArea(_thDeployRadius, meleCount), 1))
                        {
                            yield return(t);
                        }
                        yield return(Rand.Int(300, 500)); //Wait
                    }

                    if (rangedUnits.Any())
                    {
                        Log.Info($"{Tag}TH Snipe Dead {rangedCount} Ranged Near: X:{townHallTarget.DeployRanged.X} Y:{townHallTarget.DeployRanged.Y}");
                        foreach (var t in Deploy.AtPoints(rangedUnits.FilterTypesByCount(), townHallTarget.DeployRanged.RandomPointsInArea(_thDeployRadius, rangedCount), 1))
                        {
                            yield return(t);
                        }
                        yield return(Rand.Int(300, 500)); //Wait
                    }

                    if (UserSettings.UseClanTroops)
                    {
                        var clanCastle = allElements.FirstOrDefault(u => u.ElementType == DeployElementType.ClanTroops);

                        clanCastleDeployed = true;

                        if (clanCastle?.Count > 0)
                        {
                            Log.Info($"{Tag}Deploying Clan Castle Near Town Hall");
                            foreach (var t in Deploy.AtPoint(clanCastle, townHallTarget.DeployRanged, clanCastle.Count))
                            {
                                yield return(t);
                            }
                        }
                        else
                        {
                            Log.Info($"{Tag}No Clan Castle Troops found to Deploy on Town Hall...");
                        }
                    }

                    //Only do this once.
                    townHallTarget.ValidTarget = false;
                }

                //Determine the index of the 1st and 2nd largest set of targets all in a row.
                var largestSetIndex       = -1;
                int largestSetCount       = 0;
                var secondLargestSetIndex = -1;
                int secondLargestSetCount = 0;

                for (int i = 0; i < groupedTargets.Count; i++)
                {
                    if (groupedTargets[i].Length > largestSetCount)
                    {
                        secondLargestSetCount = largestSetCount;
                        secondLargestSetIndex = largestSetIndex;
                        largestSetCount       = groupedTargets[i].Length;
                        largestSetIndex       = i;
                    }
                    else if (groupedTargets[i].Length > secondLargestSetCount)
                    {
                        secondLargestSetCount = groupedTargets[i].Length;
                        secondLargestSetIndex = i;
                    }
                }

                Log.Info($"{Tag}{groupedTargets.Count} Target Groups, Largest has {largestSetCount} targets, Second Largest {secondLargestSetCount} targets.");

                if (largestSetCount <= 1)
                {
                    Log.Info($"{Tag}No group of two or more targets found - Skipping deploy of Heros & Clan Castle.");
                }

                //Deploy Barch Units - In Groups on Sets of collectors that are close together.
                for (int p = 0; p < groupedTargets.Count; p++)
                {
                    //Deploy Tanks on the Set of Targets. (If any exist)
                    for (int i = 0; i < groupedTargets[p].Length; i++)
                    {
                        var gruntDeployPoint = groupedTargets[p][i].DeployGrunts;

                        //First Deploy tanks
                        if (tankUnits.Any())
                        {
                            Log.Debug($"{Tag}Deploying {tankCount} Tank Units on {groupedTargets[p][i].Name} {p + 1}-{i}");
                            foreach (var t in Deploy.AtPoints(tankUnits.FilterTypesByCount(), gruntDeployPoint.RandomPointsInArea(_collectorDeployRadius, tankCount), 1))
                            {
                                yield return(t);
                            }
                            yield return(Rand.Int(10, 40)); //Wait
                        }
                    }

                    if (gruntUnits.Any())
                    {
                        //Pause inbetween switching units.
                        yield return(Rand.Int(90, 100)); //Wait
                    }

                    //Deploy Grunts on the Set of Targets.
                    for (int i = 0; i < groupedTargets[p].Length; i++)
                    {
                        var gruntDeployPoint = groupedTargets[p][i].DeployGrunts;

                        //Next Deploy Ground troops
                        if (gruntUnits.Any())
                        {
                            Log.Debug($"{Tag}Deploying {meleCount} Ground Units on {groupedTargets[p][i].Name} {p + 1}-{i}");
                            foreach (var t in Deploy.AtPoints(gruntUnits.FilterTypesByCount(), gruntDeployPoint.RandomPointsInArea(_collectorDeployRadius, meleCount), 1))
                            {
                                yield return(t);
                            }
                            yield return(Rand.Int(10, 40)); //Wait
                        }
                    }

                    if (rangedUnits.Any())
                    {
                        //Pause inbetween switching units.
                        yield return(Rand.Int(90, 100)); //Wait
                    }

                    //Deploy Ranged units on same set of Targets.
                    for (int i = 0; i < groupedTargets[p].Length; i++)
                    {
                        var rangedDeployPoint = groupedTargets[p][i].DeployRanged;

                        if (rangedUnits.Any())
                        {
                            Log.Debug($"{Tag}Deploying {rangedCount} Ranged Units on {groupedTargets[p][i].Name} {p + 1}-{i}");
                            foreach (var t in Deploy.AtPoints(rangedUnits.FilterTypesByCount(), rangedDeployPoint.RandomPointsInArea(_collectorDeployRadius, rangedCount), 1))
                            {
                                yield return(t);
                            }
                            yield return(Rand.Int(40, 50)); //Wait
                        }
                    }

                    if (largestSetIndex == p && largestSetCount >= 2 && waveCounter == 1)
                    {
                        //We are currently deploying to the largest set of Targets - AND its a set of 2 or more.
                        //Preferrably Drop All Heros on this set (2nd Target in the set.)
                        reminderTarget = groupedTargets[p][1];

                        if (!clanCastleDeployed && UserSettings.UseClanTroops)
                        {
                            var clanCastle = allElements.FirstOrDefault(u => u.ElementType == DeployElementType.ClanTroops);

                            if (clanCastle?.Count > 0)
                            {
                                Log.Info($"{Tag}Deploying Clan Castle on Largest set of Targets: {largestSetCount} targets.");
                                foreach (var t in Deploy.AtPoint(clanCastle, groupedTargets[p][1].DeployRanged, clanCastle.Count))
                                {
                                    yield return(t);
                                }
                            }
                            else
                            {
                                Log.Info($"{Tag}No Clan Castle Troops found to Deploy...");
                            }
                            clanCastleDeployed = true;
                        }

                        if (UserSettings.UseKing && king.Any() && !kingDeployed)
                        {
                            yield return(Rand.Int(90, 100)); //Wait before dropping King

                            Log.Info($"{Tag}Deploying King on largest set of targets: {largestSetCount} targets.");
                            foreach (var t in Deploy.AtPoint(king[0], groupedTargets[p][1].DeployGrunts))
                            {
                                yield return(t);
                            }
                            yield return(Rand.Int(200, 500)); //Wait

                            kingDeployed = true;
                            watchHeroes  = true;
                        }

                        if (UserSettings.UseQueen && queen.Any() && !queenDeployed)
                        {
                            yield return(Rand.Int(90, 100)); //Wait before dropping Queen

                            Log.Info($"{Tag}Deploying Queen on largest set of targets: {largestSetCount} targets.");
                            foreach (var t in Deploy.AtPoint(queen[0], groupedTargets[p][1].DeployRanged))
                            {
                                yield return(t);
                            }
                            yield return(Rand.Int(200, 500)); //Wait

                            queenDeployed = true;
                            watchHeroes   = true;
                        }

                        if (UserSettings.UseWarden && warden.Any() && !wardenDeployed)
                        {
                            Log.Info($"{Tag}Deploying Warden on largest set of targets: {largestSetCount} targets.");
                            foreach (var t in Deploy.AtPoint(warden[0], groupedTargets[p][1].DeployRanged))
                            {
                                yield return(t);
                            }
                            yield return(Rand.Int(200, 500)); //Wait

                            wardenDeployed = true;
                            watchHeroes    = true;
                        }

                        //Now that the first round of deploying is done, watch any heros if necessary.
                        if (watchHeroes)
                        {
                            //Watch Heros and Hit ability when they get low.
                            Log.Info($"{Tag}Watching heros to activate abilities when health gets Low.");
                            Deploy.WatchHeroes(allHeroes);
                            watchHeroes = false; //Only do this once through the loop.
                        }
                    }

                    yield return(Rand.Int(90, 100)); //Wait before switching units back to Grutns and deploying on next set of targets.
                }

                //If Deploy ALL Troops is turned on,
                if (CurrentSetting("Deploy All Troops Mode") == 1 && reminderTarget != null)
                {
                    //Deploy the Reminder of troops on the LARGEST Group of targets.

                    //First Deploy tanks
                    foreach (var units in tankUnits)
                    {
                        if (units?.Count > 0)
                        {
                            Log.Debug($"{Tag}Deploying Reminder of {units.PrettyName} Tank Units ({units.Count}) on {reminderTarget.Name}");
                            foreach (var t in Deploy.AtPoint(units, reminderTarget.DeployGrunts, units.Count))
                            {
                                yield return(t);
                            }
                            yield return(Rand.Int(2000, 3000)); //Wait
                        }
                    }

                    //Next Deploy Grunts
                    foreach (var units in gruntUnits)
                    {
                        if (units?.Count > 0)
                        {
                            Log.Debug($"{Tag}Deploying Reminder of {units.PrettyName} Mele Units ({units.Count}) on {reminderTarget.Name}");
                            foreach (var t in Deploy.AtPoint(units, reminderTarget.DeployGrunts, units.Count))
                            {
                                yield return(t);
                            }
                            yield return(Rand.Int(100, 200)); //Wait
                        }
                    }

                    //Next Deploy Ranged
                    foreach (var units in rangedUnits)
                    {
                        if (units?.Count > 0)
                        {
                            Log.Debug($"{Tag}Deploying Reminder of {units.PrettyName} Ranged Units ({units.Count}) on {reminderTarget.Name}");
                            foreach (var t in Deploy.AtPoint(units, reminderTarget.DeployRanged, units.Count))
                            {
                                yield return(t);
                            }
                            yield return(Rand.Int(100, 200)); //Wait
                        }
                    }

                    //There is only ONE wave in Deploy all troops mode...
                    break;
                }

                //wait a random number of seconds before the next round on all Targets...
                yield return(Rand.Int(5000, 7000));

                // Get starting resources, cache needs to be false to force a new check
                LootResources postLoot = Opponent.GetAvailableLoot(false);
                if (postLoot == null)
                {
                    Log.Warning($"{Tag}could not read available loot this wave");
                    postLoot = new LootResources()
                    {
                        Gold = -1, Elixir = -1, DarkElixir = -1
                    };
                }

                Log.Info($"{Tag}Wave {waveCounter} resources - G: {postLoot.Gold}, E: {postLoot.Elixir}, DE: {postLoot.DarkElixir}");
                int newGold   = preLoot.Gold - postLoot.Gold;
                int newElixir = preLoot.Elixir - postLoot.Elixir;
                int newDark   = preLoot.DarkElixir - postLoot.DarkElixir;
                Log.Info($"{Tag}Wave {waveCounter} resource diff - G: {newGold}, E: {newElixir}, DE: {newDark}, Collectors: {collectorCount}");

                //Check to see if we are getting enough Resources...
                if (postLoot.Gold + postLoot.Elixir + postLoot.DarkElixir >= 0)
                {
                    if (newGold + newElixir < 3000 * collectorCount)
                    {
                        Log.Info($"{Tag}Stopping Troop Deployment because gained resources isn't enough");
                        break;
                    }
                    preLoot = postLoot;
                }

                waveCounter++;
            }

            if (CurrentSetting("Debug Mode") == 1)
            {
                Log.Debug($"{Tag}Deployment End. Taking last debug Screenshot.");
                HumanLikeAlgorithms.SaveBasicDebugScreenShot(algorithmName, AttackId, "Battle End");
            }

            //We broke out of the attack loop - allow attack to end how specified in the General Bot Settings...
            Log.Info($"{Tag} <<<<<< End of Human Barch Algorithm >>>>>>");
        }
Exemple #4
0
        public override double ShouldAccept()
        {
            bool accept = true;

            // check if the base meets ALL the user's requirements
            if (!PassesBasicAcceptRequirements())
            {
                if (!Opponent.IsForcedAttack)
                {
                    return(0);
                }
            }

            //Check to see if the settings are favoring Gold or Elixir...
            IgnoreGold   = (CurrentSetting("Ignore Gold") == 1);
            IgnoreElixir = (CurrentSetting("Ignore Elixir") == 1);

            var minTargets = CurrentSetting("Minimum Exposed Targets");

            //If ignoring Gold, Reduce the min required targets by half.
            if (IgnoreGold)
            {
                Log.Info($"{Tag}Ignoring Gold Storages/Collectors");
            }

            //If ignoring Gold, Reduce the min required targets by half.
            if (IgnoreElixir)
            {
                Log.Info($"{Tag}Ignoring Elixir Storages/Collectors");
            }

            var acceptableTargetRange = CurrentSetting("Acceptable Target Range");

            acceptableTargetRange = acceptableTargetRange * acceptableTargetRange;

            int    ripeCollectors   = 0;
            double avgfillState     = 0;
            double avgCollectorLvel = 0;
            var    activeBase       = !Opponent.IsDead();

            //Check how many Collectors are Ripe for the taking (outside walls)
            ripeCollectors = HumanLikeAlgorithms.CountRipeCollectors(algorithmName, acceptableTargetRange, IgnoreGold, IgnoreElixir, AttackId, out avgfillState, out avgCollectorLvel, CacheBehavior.Default, activeBase);

            if (activeBase)
            {
                var minFillLevel = (double)(CurrentSetting("Min Collector Fill Level"));
                if (Opponent.IsForcedAttack)
                {
                    Log.Info($"{Tag}Forced Attack! Actual Fillstate: {(avgfillState * 10).ToString("F1")} Normal FillState Req: {minFillLevel}.");
                }
                else if ((avgfillState * 10) < minFillLevel)
                {
                    //FillState is too Low. Skip
                    Log.Warning($"{Tag}Skipping - Avg fillstate is too low: {(avgfillState * 10).ToString("F1")}. Must be > {minFillLevel}.");
                    accept = false;
                }
                else
                {
                    Log.Info($"{Tag}Avg Collector Fillstate Accepted: {(avgfillState * 10).ToString("F1")} > {minFillLevel}.");
                }

                var minAvgCollectorLevel = CurrentSetting("Min Average Collector Level");
                if (Opponent.IsForcedAttack)
                {
                    Log.Info($"{Tag}Forced Attack! Avg Collector Level: {avgCollectorLvel.ToString("F1")} Normal Collector Lvl Req: {minAvgCollectorLevel}.");
                }
                else if (avgCollectorLvel < minAvgCollectorLevel && accept)
                {
                    //Level of Collectors is too low.
                    Log.Warning($"{Tag}Skipping - Avg Collector Level is too low: {avgCollectorLvel.ToString("F1")}. Must be > {minAvgCollectorLevel}.");
                    accept = false;
                }
                else if (accept)
                {
                    Log.Info($"{Tag}Avg Collector Level Accepted: {avgCollectorLvel.ToString("F1")} > {minAvgCollectorLevel}.");
                }
            }
            else
            {
                //Log some info about the AvgCollectorLevel and Fill State
                Log.Info($"{Tag}Avg Collector Fillstate: {(avgfillState * 10).ToString("F1")}");
                Log.Info($"{Tag}Avg Collector Level: {avgCollectorLvel.ToString("F1")}");
            }


            if (Opponent.IsForcedAttack)
            {
                Log.Info($"{Tag}Forced Attack! {ripeCollectors} targets found outside walls. Normal Min={minTargets}");
            }
            else if (ripeCollectors < minTargets && accept)
            {
                Log.Warning($"{Tag}Skipping - {ripeCollectors} targets were found outside the wall. Min={minTargets}");
                accept = false;
            }
            else if (accept)
            {
                Log.Debug($"{Tag}{ripeCollectors} targets found outside walls. Min={minTargets}");
            }

            double returnVal = 0;

            if (accept || Opponent.IsForcedAttack)
            {
                returnVal = .99;
            }

            return(returnVal);
        }
        public override double ShouldAccept()
        {
            int returnVal = 0;

            // check if the base meets ALL the user's requirements
            if (!Opponent.MeetsRequirements(BaseRequirements.All))
            {
                return(0);
            }

            //Check if the base is dead.
            if (Opponent.IsDead(true))
            {
                //Check to see if the settings are favoring Gold or Elixir.. (if a resource is set to ZERO, Ignore that resource when searching for targets)
                if (!UserSettings.DeadSearch.NeedsOnlyOneRequirementForAttack)
                {
                    IgnoreGold   = (UserSettings.DeadSearch.MinGold == 0);
                    IgnoreElixir = (UserSettings.DeadSearch.MinElixir == 0);
                }

                var minTargets = _minimumExposedTargets;

                //If ignoring Gold, Reduce the min required targets by half.
                if (IgnoreGold)
                {
                    Log.Info($"[Human Barch] Minimum Gold = 0  - Ignoring Gold Storages/Collectors");
                    minTargets = (int)Math.Floor(Convert.ToDouble(minTargets) / 2d);
                }

                //If ignoring Gold, Reduce the min required targets by half.
                if (IgnoreElixir)
                {
                    Log.Info($"[Human Barch] Minimum Elixir = 0  - Ignoring Elixir Storages/Collectors");
                    minTargets = (int)Math.Floor(Convert.ToDouble(minTargets) / 2d);;
                }
                if (minTargets == 0)
                {
                    minTargets = 1; //if Gold AND Elixir are Ignored, there should be at least 1 target (DE) in order to attack.
                }
                //Check how many Collectors are Ripe for the taking (outside walls)
                int ripeCollectors = HumanLikeAlgorithms.CountRipeCollectors(_minimumDistanceToCollectors, IgnoreGold, IgnoreElixir);

                Log.Info($"[Human Barch] {ripeCollectors} targets found outside walls. Min={minTargets}");

                if (ripeCollectors < minTargets)
                {
                    Log.Info($"[Human Barch] Skipping - {ripeCollectors} targets were found outside the wall. Min={minTargets}");
                    returnVal = 0;
                }
                else
                {
                    return(1);
                }
            }
            else
            {
                //Check to see if the settings are favoring Gold or Elixir.. (if a resource is set to ZERO, Ignore that resource when searching for targets)
                if (!UserSettings.ActiveSearch.NeedsOnlyOneRequirementForAttack)
                {
                    IgnoreGold   = (UserSettings.ActiveSearch.MinGold == 0);
                    IgnoreElixir = (UserSettings.ActiveSearch.MinElixir == 0);
                }

                TownHall townHall = TownHall.Find(CacheBehavior.Default);

                if (townHall.CanSnipe())
                {
                    //The TH is positioned so we might be able to snipe it.
                    Log.Info($"[Human Barch] Sniping Active Town Hall!");
                    return(1);
                }
                else
                {
                    Log.Info($"[Human Barch] Skipping Active Base, TH is not Snipable.");
                    //This is a live base, and we can't snipe the TH.  Ignore the Loot Requirements, and always Skip.
                    returnVal = 0;
                }
            }

            return(returnVal);
        }
        public override IEnumerable <int> AttackRoutine()
        {
            Log.Info($"[Human Barch] Deploy start - V.{Assembly.GetExecutingAssembly().GetName().Version.ToString()}");

            var waveCounter = 1;

            //Check if we can snipe the town hall, and if so, what are the Deployment points for Gruns/Ranged.
            TownHall townHall = TownHall.Find(CacheBehavior.Default);

            Target townHallTarget = townHall.GetSnipeDeployPoints();

            // Get starting resources
            LootResources preLoot = Opponent.GetAvailableLoot();

            if (preLoot == null)
            {
                Log.Error("[Human Barch] Could not read available starting loot");
                Attack.Surrender();
                yield break;
            }
            Log.Info($"[Human Barch] Pre-attack resources - G: {preLoot.Gold}, E: {preLoot.Elixir}, DE: {preLoot.DarkElixir}");

            var collectorCacheBehavior = CacheBehavior.Default;
            var collectorCount         = 0;
            var isDead = Opponent.IsDead(true);

            // Loop until surrender conditions are met
            while (true)
            {
                // Get all the units available
                Log.Info($"[Human Barch] Scanning troops for wave {waveCounter}");

                var allElements                = Attack.GetAvailableDeployElements();
                var deployElements             = allElements.Where(x => x.UnitData != null).ToArray();
                var rangedUnits                = deployElements.Where(x => x.IsRanged == true && x.ElementType == DeployElementType.NormalUnit && x.UnitData.AttackType == AttackType.Damage);
                var gruntUnits                 = deployElements.Where(x => x.IsRanged == false && x.ElementType == DeployElementType.NormalUnit && x.UnitData.AttackType == AttackType.Damage);
                List <DeployElement> king      = allElements.Where(x => x.IsHero && x.Name.ToLower().Contains("king")).ToList();
                List <DeployElement> queen     = allElements.Where(x => x.IsHero && x.Name.ToLower().Contains("queen")).ToList();
                List <DeployElement> allHeroes = new List <DeployElement>();
                allHeroes.AddRange(king);
                allHeroes.AddRange(queen);

                bool watchHeroes = false;

                //Dont Deploy any Tank Units... even if we have them.

                if (!isDead)
                {
                    if (townHallTarget.ValidTarget)
                    {
                        //Before we enter the main attack routine... If there is an exposed TH, Snipe it.
                        //If there are Teslas around it, oh well. we only spent 9-12 units  of each type trying.
                        if (gruntUnits.Any())
                        {
                            var gruntsToDeploy = Rand.Int(5, 15);
                            Log.Info($"[Human Barch] Sniping Town Hall {gruntsToDeploy} Grunts Near: X:{townHallTarget.DeployGrunts.X} Y:{townHallTarget.DeployGrunts.Y}");
                            foreach (var t in Deploy.AtPoints(gruntUnits.FilterTypesByCount(), townHallTarget.DeployGrunts.RandomPointsInArea(_thDeployRadius, gruntsToDeploy), 1, Rand.Int(10, 40), Rand.Int(10, 40)))
                            {
                                yield return(t);
                            }
                            //Wait almost a second
                            yield return(Rand.Int(300, 500)); //Wait
                        }

                        if (rangedUnits.Any())
                        {
                            var rangedToDeploy = Rand.Int(5, 15);
                            Log.Info($"[Human Barch] Sniping Town Hall {rangedToDeploy} Ranged Near: X:{townHallTarget.DeployRanged.X} Y:{townHallTarget.DeployRanged.Y}");
                            foreach (var t in Deploy.AtPoints(rangedUnits.FilterTypesByCount(), townHallTarget.DeployRanged.RandomPointsInArea(_thDeployRadius, rangedToDeploy), 1, Rand.Int(10, 40), Rand.Int(10, 40)))
                            {
                                yield return(t);
                            }
                            //Wait almost a second
                            yield return(Rand.Int(300, 500)); //Wait
                        }

                        //If we dont have a star yet, Drop the King...
                        if (!Attack.HaveAStar())
                        {
                            if (UserSettings.UseKing && king.Any())
                            {
                                Log.Info($"[Human Barch] Deploying King at: X:{townHallTarget.DeployGrunts.X} Y:{townHallTarget.DeployGrunts.Y}");
                                foreach (var t in Deploy.AtPoint(king[0], townHallTarget.DeployGrunts))
                                {
                                    yield return(t);
                                }
                                yield return(Rand.Int(900, 1000)); //Wait

                                watchHeroes = true;
                            }

                            //Deploy the Queen
                            if (UserSettings.UseQueen && queen.Any())
                            {
                                Log.Info($"[Human Barch] Deploying Queen at: X:{townHallTarget.DeployRanged.X} Y:{townHallTarget.DeployRanged.Y}");
                                foreach (var t in Deploy.AtPoint(queen[0], townHallTarget.DeployRanged))
                                {
                                    yield return(t);
                                }
                                yield return(Rand.Int(900, 1000)); //Wait

                                watchHeroes = true;
                            }

                            if (watchHeroes)
                            {
                                //Watch Heros and Hit ability when they get low.
                                Deploy.WatchHeroes(allHeroes);
                                watchHeroes = false; //Only do this once through the loop.
                            }
                        }

                        //Only try once to snipe the town hall when deploying waves.
                        townHallTarget.ValidTarget = false;
                    }
                }
                else
                {
                    //First time through use cached... after the first wave always recheck for Destroyed ones...
                    Target[] targets = HumanLikeAlgorithms.GenerateTargets(_minimumAttackDistanceToCollectors, IgnoreGold, IgnoreElixir, collectorCacheBehavior);
                    collectorCount = targets.Length;

                    //Reorder the Deploy points so they look more human like when attacking.
                    var groupedTargets = targets.ReorderToClosestNeighbor().GroupCloseTargets();

                    collectorCacheBehavior = CacheBehavior.CheckForDestroyed;

                    if (collectorCount < 1)
                    {
                        Log.Info($"[Human Barch] Surrendering - Collectors Remaining = {collectorCount}");

                        // Wait for the wave to finish
                        Log.Info("[Human Barch] Deploy done. Waiting to finish...");
                        var x = Attack.WatchResources(10d).Result;

                        break;
                    }

                    if (townHallTarget.ValidTarget)
                    {
                        //Drop some Grunt and Ranged troups on the TH as well as collectors.
                        //If there are Teslas around it, oh well. we only spent 9-12 units  of each type trying.
                        if (gruntUnits.Any())
                        {
                            var gruntsToDeploy = Rand.Int(4, 6);
                            Log.Info($"[Human Barch] + TH Snipe Dead {gruntsToDeploy} Grunts Near: X:{townHallTarget.DeployGrunts.X} Y:{townHallTarget.DeployGrunts.Y}");
                            foreach (var t in Deploy.AtPoints(gruntUnits.FilterTypesByCount(), townHallTarget.DeployGrunts.RandomPointsInArea(_thDeployRadius, gruntsToDeploy), 1, Rand.Int(10, 40), Rand.Int(10, 40)))
                            {
                                yield return(t);
                            }
                            yield return(Rand.Int(300, 500)); //Wait
                        }

                        if (rangedUnits.Any())
                        {
                            var rangedToDeploy = Rand.Int(4, 6);
                            Log.Info($"[Human Barch] + TH Snipe Dead {rangedToDeploy} Ranged Near: X:{townHallTarget.DeployRanged.X} Y:{townHallTarget.DeployRanged.Y}");
                            foreach (var t in Deploy.AtPoints(rangedUnits.FilterTypesByCount(), townHallTarget.DeployRanged.RandomPointsInArea(_thDeployRadius, rangedToDeploy), 1, Rand.Int(10, 40), Rand.Int(10, 40)))
                            {
                                yield return(t);
                            }
                            yield return(Rand.Int(300, 500)); //Wait
                        }

                        //Only do this once.
                        townHallTarget.ValidTarget = false;
                    }

                    //Determine the index of the 1st and 2nd largest set of targets all in a row.
                    var largestSetIndex       = -1;
                    int largestSetCount       = 0;
                    var secondLargestSetIndex = -1;
                    int secondLargestSetCount = 0;

                    for (int i = 0; i < groupedTargets.Count; i++)
                    {
                        if (groupedTargets[i].Length > largestSetIndex)
                        {
                            secondLargestSetCount = largestSetCount;
                            secondLargestSetIndex = largestSetIndex;
                            largestSetCount       = groupedTargets[i].Length;
                            largestSetIndex       = i;
                        }
                        else if (groupedTargets[i].Length > secondLargestSetIndex)
                        {
                            secondLargestSetCount = groupedTargets[i].Length;
                            secondLargestSetIndex = i;
                        }
                    }

                    Log.Info($"[Human Barch] {groupedTargets.Count} Target Groups, Largest has {largestSetCount} targets, Second Largest {secondLargestSetCount} targets.");

                    //Deploy Barch Units - In Groups on Sets of collectors that are close together.
                    for (int p = 0; p < groupedTargets.Count; p++)
                    {
                        //Deploy Grunts on the Set of Targets.
                        for (int i = 0; i < groupedTargets[p].Length; i++)
                        {
                            var gruntDeployPoint = groupedTargets[p][i].DeployGrunts;

                            if (gruntUnits.Any())
                            {
                                int decreaseFactor = 0;
                                if (i > 0)
                                {
                                    decreaseFactor = (int)Math.Ceiling(i / 2d);
                                }

                                var gruntsAtCollector = (Rand.Int(6, 8) - decreaseFactor);
                                Log.Info($"[Human Barch] {gruntsAtCollector} Grunts Around Point: X:{gruntDeployPoint.X} Y:{gruntDeployPoint.Y}");
                                foreach (var t in Deploy.AtPoints(gruntUnits.FilterTypesByCount(), gruntDeployPoint.RandomPointsInArea(_collectorDeployRadius, gruntsAtCollector), 1, Rand.Int(10, 40)))
                                {
                                    yield return(t);
                                }
                                yield return(Rand.Int(10, 40)); //Wait
                            }
                        }

                        //Pause inbetween switching units.
                        yield return(Rand.Int(90, 100)); //Wait

                        if (secondLargestSetIndex == p && secondLargestSetCount >= 3)
                        {
                            //We are currently deploying to the 2nd largest set of Targets - AND its a set of 3 or more.
                            //Drop the King on the 2nd Target in the set.

                            if (UserSettings.UseKing && king.Any())
                            {
                                Log.Info($"[Human Barch] Deploying King at: X:{groupedTargets[p][1].DeployGrunts.X} Y:{groupedTargets[p][1].DeployGrunts.Y}");
                                foreach (var t in Deploy.AtPoint(king[0], groupedTargets[p][1].DeployGrunts))
                                {
                                    yield return(t);
                                }
                                yield return(Rand.Int(900, 1000)); //Wait

                                watchHeroes = true;
                            }
                        }

                        if (largestSetIndex == p && largestSetCount >= 3)
                        {
                            //We are currently deploying to the largest set of Targets - AND its a set of 3 or more.
                            //Drop the Queen on the 2nd Target in the set.

                            if (UserSettings.UseQueen && queen.Any())
                            {
                                yield return(Rand.Int(90, 100)); //Wait before dropping Queen

                                Log.Info($"[Human Barch] Deploying Queen at: X:{groupedTargets[p][1].DeployRanged.X} Y:{groupedTargets[p][1].DeployRanged.Y}");
                                foreach (var t in Deploy.AtPoint(queen[0], groupedTargets[p][1].DeployRanged))
                                {
                                    yield return(t);
                                }
                                yield return(Rand.Int(900, 1000)); //Wait

                                watchHeroes = true;
                            }
                        }

                        if (watchHeroes)
                        {
                            //Watch Heros and Hit ability when they get low.
                            Deploy.WatchHeroes(allHeroes);
                            watchHeroes = false; //Only do this once through the loop.
                        }


                        //Deploy Ranged units on same set of Targets.
                        for (int i = 0; i < groupedTargets[p].Length; i++)
                        {
                            var rangedDeployPoint = groupedTargets[p][i].DeployRanged;

                            if (rangedUnits.Any())
                            {
                                int decreaseFactor = 0;
                                if (i > 0)
                                {
                                    decreaseFactor = (int)Math.Ceiling(i / 2d);
                                }

                                var rangedAtCollector = (Rand.Int(5, 7) - decreaseFactor);
                                Log.Info($"[Human Barch] {rangedAtCollector} Ranged Around Point: X:{rangedDeployPoint.X} Y:{rangedDeployPoint.Y}");
                                foreach (var t in Deploy.AtPoints(rangedUnits.FilterTypesByCount(), rangedDeployPoint.RandomPointsInArea(_collectorDeployRadius, rangedAtCollector), 1, Rand.Int(10, 40)))
                                {
                                    yield return(t);
                                }
                                yield return(Rand.Int(40, 50)); //Wait
                            }
                        }

                        yield return(Rand.Int(90, 100)); //Wait before switching units back to Grutns and deploying on next set of targets.
                    }
                }

                //Never deploy any Healing type Units.


                //wait a random number of seconds before the next round on all Targets...
                yield return(Rand.Int(2000, 5000));

                // Get starting resources, cache needs to be false to force a new check
                LootResources postLoot = Opponent.GetAvailableLoot(false);
                if (postLoot == null)
                {
                    Log.Warning($"[Human Barch] Human Barch Deploy could not read available loot this wave");
                    postLoot = new LootResources()
                    {
                        Gold = -1, Elixir = -1, DarkElixir = -1
                    };
                }

                Log.Info($"[Human Barch] Wave {waveCounter} resources - G: {postLoot.Gold}, E: {postLoot.Elixir}, DE: {postLoot.DarkElixir}");
                int newGold   = preLoot.Gold - postLoot.Gold;
                int newElixir = preLoot.Elixir - postLoot.Elixir;
                int newDark   = preLoot.DarkElixir - postLoot.DarkElixir;
                Log.Info($"[Human Barch] Wave {waveCounter} resource diff - G: {newGold}, E: {newElixir}, DE: {newDark}, Collectors: {collectorCount}");

                if (isDead)
                {
                    if (postLoot.Gold + postLoot.Elixir + postLoot.DarkElixir >= 0)
                    {
                        if (newGold + newElixir < 3000 * collectorCount)
                        {
                            Log.Info("[Human Barch] Surrendering because gained resources isn't enough");
                            break;
                        }
                        preLoot = postLoot;
                    }
                }
                else
                {
                    if (Attack.HaveAStar())
                    {
                        Log.Info("[Human Barch] We have a star! TH Sniped!");

                        //Check the Delta in Resources.
                        if (newGold + newElixir < (preLoot.Gold + preLoot.Elixir) * .05f) //Less than 5% of what is available.
                        {
                            //Switch the attack mode to Dead - so we get some of the collectors.
                            Log.Info($"[Human Barch] Not much loot gained from Snipe(G:{newGold} E:{newElixir} out of G:{preLoot.Gold} E:{preLoot.Elixir}) - Try to Loot Collectors also...");
                            isDead = true;
                        }
                        else
                        {
                            //Halt the Attack.
                            break;
                        }
                    }

                    if (waveCounter > 10)
                    {
                        Log.Info("[Human Barch] Fail! TH Not Sniped! our troops died - Surrendering...");
                        break;
                    }
                }

                waveCounter++;
            }

            //TODO - Can we destroy some trash buildings to get a star if we dont already have one?

            //Last thing Call ZapDarkElixterDrills... This uses the Clashbot settings for when to zap, and what level drills to zap.
            Log.Info("[Human Barch] Checking to see if we can Zap DE Drills...");
            foreach (var t in ZapDarkElixirDrills())
            {
                yield return(t);
            }

            //We broke out of the attack loop...
            Attack.Surrender();
        }
Exemple #7
0
        public override double ShouldAccept()
        {
            if (!PassesBasicAcceptRequirements())
            {
                return(0);
            }

            //TODO - Check which kind of army we have trained. Calculate an Air Offense Score, and Ground Offense Score.

            //TODO - Find all Base Defenses, and calculate an AIR and Ground Defensive Score.

            //TODO - From Collector/Storage fill levels, determine if loot is in Collectors, or Storages... (Will help to decide which alg to use.)

            //Verify that the Attacking Army contains at least 6 Dragons.
            deployElements = Deploy.GetTroops();
            var dragons = deployElements.FirstOrDefault(u => u.Id == DeployId.Dragon);

            if (dragons == null || dragons?.Count < 6)
            {
                Log.Error($"{Tag} Army not correct! - Dark Dragon Deploy Requires at least 6 Dragons to function Properly. (You have {dragons?.Count ?? 0} dragons)");
                return(0);
            }

            //Verify that there are enough spells to take out at least ONE air defense.
            var lightningSpells = deployElements.FirstOrDefault(u => u.ElementType == DeployElementType.Spell && u.Id == DeployId.Lightning);
            List <DeployElement> earthquakeSpells = deployElements.Where(u => u.ElementType == DeployElementType.Spell && u.Id == DeployId.Earthquake).ToList();

            var lightningCount  = lightningSpells?.Count ?? 0;
            var earthquakeCount = 0;

            //Get a count of all earthquake spells... donated, or brewed...
            foreach (var spell in earthquakeSpells.Where(s => s.Count > 0))
            {
                earthquakeCount += spell.Count;
            }

            if (lightningCount < 2 || lightningCount < 3 && earthquakeCount < 1)
            {
                //We dont have the Spells to take out the Closest Air Defense... Surrender before we drop any Dragons!
                Log.Error($"{Tag} We don't have enough spells to take out at least 1 air defense... Lightning Spells:{lightningCount}, Earthquake Spells:{earthquakeCount}");
                return(0);
            }

            if (deployElements.Count >= 11)
            {
                //Possibly Too Many Deployment Elements!  Bot Doesnt Scroll - Change Army Composition to have less than 12 unit types!
                Log.Warning($"{Tag} Warning! Full Army! - The Bot does not scroll through choices when deploying units... If your army has more than 11 unit types, The bot will not see them all, and cannot deploy everything!)");
            }

            //Write out all the unit pretty names we found...
            Log.Debug($"{Tag} Deployable Troops: {ToUnitString(deployElements)}");

            Log.Info($"{Tag} Base meets minimum Requirements... Checking DE Storage/Air Defense Locations...");

            //Grab the Locations of the DE Storage
            darkElixirStorage = HumanLikeAlgorithms.TargetDarkElixirStorage();

            if (!darkElixirStorage.ValidTarget)
            {
                Log.Warning($"{Tag} No Dark Elixir Storage Found - Skipping");
                return(0);
            }

            //Get the locaiton of all Air Defenses
            var airDefensesTest = AirDefense.Find();

            if (airDefensesTest.Length == 0)
            {
                Log.Warning($"{Tag} Could not find ANY air defenses - Skipping");
                return(0);
            }

            Log.Info($"{Tag} Found {airDefensesTest.Length} Air Defense Buildings.. Continuing Attack..");

            if (airDefensesTest.Length > 1)
            {
                //Now that we found all Air Defenses, order them in the array with closest AD to Target first.
                Array.Sort(airDefensesTest, delegate(AirDefense ad1, AirDefense ad2)
                {
                    return(HumanLikeAlgorithms.DistanceFromPoint(ad1, darkElixirStorage.DeployGrunts)
                           .CompareTo(HumanLikeAlgorithms.DistanceFromPoint(ad2, darkElixirStorage.DeployGrunts)));
                });
            }

            //Create the Funnel Points
            deFunnelPoints      = darkElixirStorage.GetFunnelingPoints(30);
            balloonFunnelPoints = darkElixirStorage.GetFunnelingPoints(20);

#if DEBUG
            //During Debug, Create an Image of the base including what we found.
            CreateDebugImages();
#endif

            //We are Good to attack!
            return(1);
        }