From c587329f6a90b0d461ce4bce7ee475fb7c437265 Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Thu, 28 Apr 2022 22:12:25 +0700 Subject: [PATCH 01/16] make update village task less sus --- TbsCore/Tasks/LowLevel/UpdateVillage.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/TbsCore/Tasks/LowLevel/UpdateVillage.cs b/TbsCore/Tasks/LowLevel/UpdateVillage.cs index 851ab2956..4d0ca942d 100644 --- a/TbsCore/Tasks/LowLevel/UpdateVillage.cs +++ b/TbsCore/Tasks/LowLevel/UpdateVillage.cs @@ -30,7 +30,6 @@ public override async Task Execute(Account acc) await UpdateTroopsResearchedAndLevels(acc); - await NavigationHelper.ToDorf2(acc); await Task.Delay(AccountHelper.Delay(acc)); await UpdateTroopsTraining(acc); From f23142ddbd8db9b5fd4c818cb611687d558d0122 Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 12:51:40 +0700 Subject: [PATCH 02/16] rework celebration task --- TbsCore/Helpers/NavigationHelper.cs | 3 +- TbsCore/Parsers/TimeParser.cs | 20 -- TbsCore/Tasks/LowLevel/Celebration.cs | 230 +++++++++++++++++++--- TbsCore/Tasks/LowLevel/UpdateVillage.cs | 6 - TbsCore/Tasks/LowLevel/UpgradeBuilding.cs | 2 +- 5 files changed, 209 insertions(+), 52 deletions(-) diff --git a/TbsCore/Helpers/NavigationHelper.cs b/TbsCore/Helpers/NavigationHelper.cs index c299374bb..44a7bd677 100644 --- a/TbsCore/Helpers/NavigationHelper.cs +++ b/TbsCore/Helpers/NavigationHelper.cs @@ -411,7 +411,8 @@ public static async Task ToOverview(Account acc, OverviewTab tab, TroopOve public static async Task SwitchVillage(Account acc, Village vill) { - await DriverHelper.WaitPageLoaded(acc); + var result = await DriverHelper.WaitPageLoaded(acc); + if (!result) return false; var active = acc.Villages.FirstOrDefault(x => x.Active); if (active != null && active.Id != vill.Id) { diff --git a/TbsCore/Parsers/TimeParser.cs b/TbsCore/Parsers/TimeParser.cs index 76a8d244d..d2e1d5406 100644 --- a/TbsCore/Parsers/TimeParser.cs +++ b/TbsCore/Parsers/TimeParser.cs @@ -58,25 +58,5 @@ public static DateTime GetServerTime(HtmlDocument html) var dur = TimeParser.ParseDuration(timer.InnerText); return DateTime.Today.Add(dur); } - - /// - /// Gets the TimeSpan when the current celebration will end - /// - /// Html - /// When celebration will end - public static DateTime GetCelebrationTime(HtmlDocument html) - { - var underProgress = html.GetElementbyId("under_progress"); // T4.4 - - if (underProgress == null) // T4.5 - { - var content = html.GetElementbyId("content"); - underProgress = content.Descendants().FirstOrDefault(x => x.HasClass("under_progress")); - } - - if (underProgress == null) return DateTime.MinValue; // No celebration is under progress - - return DateTime.Now + TimeParser.ParseTimer(underProgress); - } } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/Celebration.cs b/TbsCore/Tasks/LowLevel/Celebration.cs index 2a39baece..7d506593d 100644 --- a/TbsCore/Tasks/LowLevel/Celebration.cs +++ b/TbsCore/Tasks/LowLevel/Celebration.cs @@ -6,57 +6,239 @@ using TbsCore.Models.VillageModels; using TbsCore.TravianData; using TbsCore.Parsers; +using static TbsCore.Helpers.Classificator; +using HtmlAgilityPack; +using OpenQA.Selenium; namespace TbsCore.Tasks.LowLevel { public class Celebration : BotTask { + private bool bigCeleb; + private readonly Random rand = new Random(); + public override async Task Execute(Account acc) { - if (!await NavigationHelper.EnterBuilding(acc, Vill, Classificator.BuildingEnum.TownHall)) - return TaskRes.Executed; + StopFlag = false; - var celebrationEnd = TimeParser.GetCelebrationTime(acc.Wb.Html); - if (DateTime.Now <= celebrationEnd) + do { - // We already have a celebration running - Vill.Expansion.CelebrationEnd = celebrationEnd; - this.NextExecute = celebrationEnd; - return TaskRes.Executed; + if (StopFlag) return TaskRes.Executed; + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Moving into TownHall ...", this); + var result = await MoveIntoBuilding(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Check current celebration ..."); + var result = IsFreeSlot(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Check enough resource ...", this); + var result = IsEnoughRes(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Click start celebration ...", this); + var result = await StartCelebration(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Post check ...", this); + var result = PostCheck(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + } while (true); + } + + private async Task MoveIntoBuilding(Account acc) + { + acc.Logger.Information($"Checking current village ..."); + { + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (!result) + { + Retry(acc, "Cannot switch village"); + return false; + } } - var buildingNode = acc.Wb.Html.GetElementbyId("build"); - (_, var level) = InfrastructureParser.UpgradeBuildingGetInfo(buildingNode); + await AccountHelper.DelayWait(acc); - var bigCeleb = Vill.Expansion.Celebrations == CelebrationEnum.Big && 10 <= level; + { + var result = await NavigationHelper.EnterBuilding(acc, Vill, BuildingEnum.TownHall); + if (!result) + { + Retry(acc, "Cannot enter TownHall"); + return false; + } + } + return true; + } - // Check if enough resources to start a celebration - if (!MiscCost.EnoughResForCelebration(Vill, bigCeleb)) + private bool IsFreeSlot(Account acc) + { + HtmlNode underProgressNode; + switch (acc.AccInfo.ServerVersion) { - ResourcesHelper.NotEnoughRes(acc, Vill, MiscCost.CelebrationCost(bigCeleb), this); - return TaskRes.Executed; + case ServerVersionEnum.TTwars: + underProgressNode = acc.Wb.Html.GetElementbyId("under_progress"); + break; + + case ServerVersionEnum.T4_5: + { + var content = acc.Wb.Html.GetElementbyId("content"); + underProgressNode = content.Descendants("table").FirstOrDefault(x => x.HasClass("under_progress")); + } + break; + + default: + underProgressNode = null; + break; } - await StartCelebration(acc, bigCeleb); + if (underProgressNode == null) return true; // No celebration is under progress + + var celebrationEnd = DateTime.Now + TimeParser.ParseTimer(underProgressNode); + Vill.Expansion.CelebrationEnd = celebrationEnd; + NextExecute = celebrationEnd; + acc.Logger.Information($"There is under progress celebration. [{celebrationEnd}]"); + StopFlag = true; + return false; + } + + private bool IsEnoughRes(Account acc) + { + var townHall = Vill.Build.Buildings.FirstOrDefault(x => x.Type == BuildingEnum.TownHall); + if (townHall == null) + { + Retry(acc, "Townhall disappear from database"); + return false; + } - // Post task check for celebration duration - Vill.Expansion.CelebrationEnd = TimeParser.GetCelebrationTime(acc.Wb.Html); + bigCeleb = Vill.Expansion.Celebrations == CelebrationEnum.Big && 10 <= townHall.Level; + var arrayCost = MiscCost.CelebrationCost(bigCeleb); + var cost = ResourcesHelper.ArrayToResources(arrayCost); + acc.Logger.Information($"Need {cost}"); + if (ResourcesHelper.IsEnoughRes(Vill, arrayCost)) + { + return true; + } - if (Vill.Expansion.Celebrations != CelebrationEnum.None) this.NextExecute = Vill.Expansion.CelebrationEnd; + if (ResourcesHelper.IsStorageTooLow(acc, Vill, cost)) + { + var building = Vill.Build.CurrentlyBuilding.FirstOrDefault(x => x.Building == BuildingEnum.Warehouse || x.Building == BuildingEnum.Granary); + if (building == null) + { + acc.Logger.Warning($"Storage is too low. Added storage upgrade."); + } + else + { + acc.Logger.Warning($"Storage is too low. Next building will be contructed after {building.Building} - level {building.Level} complete. ({NextExecute})"); + NextExecute = TimeHelper.RanDelay(acc, building.Duration); + } + } + else + { + var stillNeededRes = ResourcesHelper.SubtractResources(cost.ToArray(), Vill.Res.Stored.Resources.ToArray(), true); + acc.Logger.Information($"Not enough resources to build. Still need {stillNeededRes}"); + acc.Logger.Information($"Bot will try finish the task later"); + DateTime enoughRes = TimeHelper.EnoughResToUpgrade(Vill, stillNeededRes); + NextExecute = TimeHelper.RanDelay(acc, enoughRes); + } - return TaskRes.Executed; + StopFlag = true; + return false; } - private async Task StartCelebration(Account acc, bool big) + private async Task StartCelebration(Account acc) { var nodes = acc.Wb.Html.DocumentNode.Descendants("div").Where(x => x.HasClass("research")); - var node = big ? nodes.LastOrDefault() : nodes.FirstOrDefault(); - if (node == null) return; + var node = bigCeleb ? nodes.LastOrDefault() : nodes.FirstOrDefault(); + if (node == null) + { + Retry(acc, "Cannot find button box"); + return false; + } var button = node.Descendants("button").FirstOrDefault(); + if (node == null) + { + Retry(acc, "Cannot find button"); + return false; + } + + var elementButton = acc.Wb.Driver.FindElement(By.XPath(button.XPath)); + elementButton.Click(); + await Task.Delay(rand.Next(1200, 2000)); + return true; + } + + private bool PostCheck(Account acc) + { + HtmlNode underProgressNode; + switch (acc.AccInfo.ServerVersion) + { + case ServerVersionEnum.TTwars: + underProgressNode = acc.Wb.Html.GetElementbyId("under_progress"); + break; + + case ServerVersionEnum.T4_5: + { + var content = acc.Wb.Html.GetElementbyId("content"); + underProgressNode = content.Descendants("table").FirstOrDefault(x => x.HasClass("under_progress")); + } + break; + + default: + underProgressNode = null; + break; + } + + if (underProgressNode == null) return true; // No celebration is under progress - await DriverHelper.ExecuteScript(acc, $"document.getElementById('{button.Id}').click()"); + var celebrationEnd = DateTime.Now + TimeParser.ParseTimer(underProgressNode); + Vill.Expansion.CelebrationEnd = celebrationEnd; + NextExecute = celebrationEnd; + StopFlag = true; + return false; } } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/UpdateVillage.cs b/TbsCore/Tasks/LowLevel/UpdateVillage.cs index 4d0ca942d..526c6e4dd 100644 --- a/TbsCore/Tasks/LowLevel/UpdateVillage.cs +++ b/TbsCore/Tasks/LowLevel/UpdateVillage.cs @@ -37,12 +37,6 @@ public override async Task Execute(Account acc) Vill.Troops.TroopToTrain = firstTroop; Vill.Troops.Researched.Add(firstTroop); - if (await NavigationHelper.EnterBuilding(acc, Vill, Classificator.BuildingEnum.TownHall)) - { - // Village has town hall, parse celebration duration - Vill.Expansion.CelebrationEnd = TimeParser.GetCelebrationTime(acc.Wb.Html); - } - return TaskRes.Executed; } diff --git a/TbsCore/Tasks/LowLevel/UpgradeBuilding.cs b/TbsCore/Tasks/LowLevel/UpgradeBuilding.cs index b406edfc0..999a01d16 100644 --- a/TbsCore/Tasks/LowLevel/UpgradeBuilding.cs +++ b/TbsCore/Tasks/LowLevel/UpgradeBuilding.cs @@ -616,7 +616,7 @@ private async Task IsEnoughRes(Account acc) } var stillNeededRes = ResourcesHelper.SubtractResources(cost.ToArray(), Vill.Res.Stored.Resources.ToArray(), true); - acc.Logger.Information("Not enough resources to build."); + acc.Logger.Information($"Not enough resources to build. Still need {stillNeededRes}"); if (Vill.Settings.UseHeroRes && acc.AccInfo.ServerVersion == ServerVersionEnum.T4_5) // Only T4.5 has resources in hero inv { var heroRes = HeroHelper.GetHeroResources(acc); From f5a82f4d5fc1bff7012173f4d4e6570d283d97ff Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 14:10:58 +0700 Subject: [PATCH 03/16] sort task --- TbsCore/Tasks/{LowLevel => }/BotTask.cs | 262 ++-- .../Tasks/{LowLevel => }/BotTaskTemplate.cs | 26 +- .../{LowLevel => Browser}/ChangeAccess.cs | 52 +- .../{LowLevel => Browser}/CheckAttacks.cs | 270 ++-- .../{LowLevel => Browser}/ReopenDriver.cs | 94 +- .../{LowLevel => Browser}/RestartChrome.cs | 0 .../Tasks/{LowLevel => Browser}/TaskSleep.cs | 0 .../Tasks/{LowLevel => Browser}/TimeSleep.cs | 0 TbsCore/Tasks/{LowLevel => Farm}/AddFarm.cs | 94 +- .../{SecondLevel => Farm}/AttackOasis.cs | 0 .../Tasks/{LowLevel => Farm}/ImproveTroop.cs | 184 +-- .../{LowLevel => Farm}/ReadFarmScoutReport.cs | 0 .../Tasks/{LowLevel => Farm}/ResearchTroop.cs | 134 +- .../{SecondLevel => Farm}/ScoutPlayer.cs | 0 .../Tasks/{SecondLevel => Farm}/SendDeff.cs | 166 +-- .../Tasks/{SecondLevel => Farm}/SendFLs.cs | 118 +- .../Tasks/{LowLevel => Farm}/SendFarmlist.cs | 220 +-- .../Tasks/{SecondLevel => Farm}/SendRaid.cs | 0 .../SendReinforcementScouts.cs | 0 .../Tasks/{LowLevel => Farm}/SendTroops.cs | 234 +-- TbsCore/Tasks/{LowLevel => Farm}/SendWaves.cs | 486 +++---- .../TTWarsAddNatarsToFL.cs | 108 +- .../TTWarsAddNatarsToNonGoldFL.cs | 0 .../{LowLevel => Farm}/TrainExchangeRes.cs | 76 +- .../Tasks/{LowLevel => Farm}/TrainTroops.cs | 408 +++--- .../{SecondLevel => Farm}/TransitToMainAcc.cs | 68 +- .../{LowLevel => Farm}/UpdateFarmLists.cs | 152 +- .../{LowLevel => Others}/ChangeVillageName.cs | 144 +- .../{LowLevel => Others}/DonateAllyBonus.cs | 88 +- .../{LowLevel => Others}/EditPreferences.cs | 80 +- .../Tasks/{LowLevel => Others}/HeroEquip.cs | 180 +-- .../{LowLevel => Others}/HeroSetPoints.cs | 110 +- .../Tasks/{LowLevel => Others}/LoginTask.cs | 246 ++-- .../Tasks/{LowLevel => Others}/RandomTask.cs | 146 +- .../Tasks/{LowLevel => Others}/ReviveHero.cs | 96 +- .../{LowLevel => Others}/SellOnAuctions.cs | 238 +-- .../{LowLevel => Others}/SendResFillTroops.cs | 142 +- .../{LowLevel => Others}/SendResToMain.cs | 74 +- .../{LowLevel => Others}/SendResources.cs | 88 +- .../Tasks/{LowLevel => Others}/SetCapital.cs | 0 .../{LowLevel => Others}/StartAdventure.cs | 138 +- .../TTWars => Others}/TTWarsBuyAdventure.cs | 44 +- .../TTWars => Others}/TTWarsExpandStorage.cs | 82 +- .../TTWars => Others}/TTWarsGetAnimals.cs | 72 +- .../TTWars => Others}/TTWarsGetRes.cs | 90 +- .../TTWars => Others}/TTWarsPlusAndBoost.cs | 52 +- .../Tasks/{LowLevel => Sim}/Celebration.cs | 486 +++---- .../{LowLevel => Sim}/ClaimBeginnerTask.cs | 72 +- .../ClaimBeginnerTask2021.cs | 90 +- .../Tasks/{LowLevel => Sim}/ClaimDailyTask.cs | 62 +- .../{LowLevel => Sim}/DemolishBuilding.cs | 176 +-- .../{LowLevel => Sim}/ExtendProtection.cs | 32 +- .../{LowLevel => Sim}/FindVillageToSettle.cs | 120 +- .../Tasks/{LowLevel => Sim}/InstaUpgrade.cs | 82 +- TbsCore/Tasks/{LowLevel => Sim}/NPC.cs | 150 +- .../Tasks/{LowLevel => Sim}/SendSettlers.cs | 156 +- .../Tasks/{LowLevel => Sim}/TrainSettlers.cs | 600 ++++---- .../{LowLevel => Sim}/UpgradeBuilding.cs | 1288 ++++++++--------- .../{LowLevel => Update}/CheckProfile.cs | 0 .../{LowLevel => Update}/GetServerInfo.cs | 48 +- .../Tasks/{LowLevel => Update}/GetTribe.cs | 176 +-- .../{LowLevel => Update}/HeroUpdateInfo.cs | 108 +- .../Tasks/{LowLevel => Update}/ReadMessage.cs | 70 +- .../Tasks/{LowLevel => Update}/UpdateDorf1.cs | 64 +- .../Tasks/{LowLevel => Update}/UpdateDorf2.cs | 40 +- .../{LowLevel => Update}/UpdateTaskUseRes.cs | 0 .../{LowLevel => Update}/UpdateTroops.cs | 116 +- .../{LowLevel => Update}/UpdateVillage.cs | 218 +-- 68 files changed, 4708 insertions(+), 4708 deletions(-) rename TbsCore/Tasks/{LowLevel => }/BotTask.cs (96%) rename TbsCore/Tasks/{LowLevel => }/BotTaskTemplate.cs (96%) rename TbsCore/Tasks/{LowLevel => Browser}/ChangeAccess.cs (98%) rename TbsCore/Tasks/{LowLevel => Browser}/CheckAttacks.cs (97%) rename TbsCore/Tasks/{LowLevel => Browser}/ReopenDriver.cs (96%) rename TbsCore/Tasks/{LowLevel => Browser}/RestartChrome.cs (100%) rename TbsCore/Tasks/{LowLevel => Browser}/TaskSleep.cs (100%) rename TbsCore/Tasks/{LowLevel => Browser}/TimeSleep.cs (100%) rename TbsCore/Tasks/{LowLevel => Farm}/AddFarm.cs (97%) rename TbsCore/Tasks/{SecondLevel => Farm}/AttackOasis.cs (100%) rename TbsCore/Tasks/{LowLevel => Farm}/ImproveTroop.cs (97%) rename TbsCore/Tasks/{LowLevel => Farm}/ReadFarmScoutReport.cs (100%) rename TbsCore/Tasks/{LowLevel => Farm}/ResearchTroop.cs (97%) rename TbsCore/Tasks/{SecondLevel => Farm}/ScoutPlayer.cs (100%) rename TbsCore/Tasks/{SecondLevel => Farm}/SendDeff.cs (97%) rename TbsCore/Tasks/{SecondLevel => Farm}/SendFLs.cs (97%) rename TbsCore/Tasks/{LowLevel => Farm}/SendFarmlist.cs (97%) rename TbsCore/Tasks/{SecondLevel => Farm}/SendRaid.cs (100%) rename TbsCore/Tasks/{SecondLevel => Farm}/SendReinforcementScouts.cs (100%) rename TbsCore/Tasks/{LowLevel => Farm}/SendTroops.cs (97%) rename TbsCore/Tasks/{LowLevel => Farm}/SendWaves.cs (97%) rename TbsCore/Tasks/{SecondLevel => Farm}/TTWarsAddNatarsToFL.cs (97%) rename TbsCore/Tasks/{SecondLevel => Farm}/TTWarsAddNatarsToNonGoldFL.cs (100%) rename TbsCore/Tasks/{LowLevel => Farm}/TrainExchangeRes.cs (97%) rename TbsCore/Tasks/{LowLevel => Farm}/TrainTroops.cs (97%) rename TbsCore/Tasks/{SecondLevel => Farm}/TransitToMainAcc.cs (96%) rename TbsCore/Tasks/{LowLevel => Farm}/UpdateFarmLists.cs (97%) rename TbsCore/Tasks/{LowLevel => Others}/ChangeVillageName.cs (97%) rename TbsCore/Tasks/{LowLevel => Others}/DonateAllyBonus.cs (96%) rename TbsCore/Tasks/{LowLevel => Others}/EditPreferences.cs (96%) rename TbsCore/Tasks/{LowLevel => Others}/HeroEquip.cs (97%) rename TbsCore/Tasks/{LowLevel => Others}/HeroSetPoints.cs (97%) rename TbsCore/Tasks/{LowLevel => Others}/LoginTask.cs (97%) rename TbsCore/Tasks/{LowLevel => Others}/RandomTask.cs (97%) rename TbsCore/Tasks/{LowLevel => Others}/ReviveHero.cs (97%) rename TbsCore/Tasks/{LowLevel => Others}/SellOnAuctions.cs (97%) rename TbsCore/Tasks/{LowLevel => Others}/SendResFillTroops.cs (97%) rename TbsCore/Tasks/{LowLevel => Others}/SendResToMain.cs (97%) rename TbsCore/Tasks/{LowLevel => Others}/SendResources.cs (97%) rename TbsCore/Tasks/{LowLevel => Others}/SetCapital.cs (100%) rename TbsCore/Tasks/{LowLevel => Others}/StartAdventure.cs (97%) rename TbsCore/Tasks/{LowLevel/TTWars => Others}/TTWarsBuyAdventure.cs (97%) rename TbsCore/Tasks/{LowLevel/TTWars => Others}/TTWarsExpandStorage.cs (97%) rename TbsCore/Tasks/{LowLevel/TTWars => Others}/TTWarsGetAnimals.cs (97%) rename TbsCore/Tasks/{LowLevel/TTWars => Others}/TTWarsGetRes.cs (97%) rename TbsCore/Tasks/{LowLevel/TTWars => Others}/TTWarsPlusAndBoost.cs (97%) rename TbsCore/Tasks/{LowLevel => Sim}/Celebration.cs (97%) rename TbsCore/Tasks/{LowLevel => Sim}/ClaimBeginnerTask.cs (97%) rename TbsCore/Tasks/{LowLevel => Sim}/ClaimBeginnerTask2021.cs (97%) rename TbsCore/Tasks/{LowLevel => Sim}/ClaimDailyTask.cs (97%) rename TbsCore/Tasks/{LowLevel => Sim}/DemolishBuilding.cs (97%) rename TbsCore/Tasks/{LowLevel => Sim}/ExtendProtection.cs (96%) rename TbsCore/Tasks/{LowLevel => Sim}/FindVillageToSettle.cs (97%) rename TbsCore/Tasks/{LowLevel => Sim}/InstaUpgrade.cs (96%) rename TbsCore/Tasks/{LowLevel => Sim}/NPC.cs (97%) rename TbsCore/Tasks/{LowLevel => Sim}/SendSettlers.cs (97%) rename TbsCore/Tasks/{LowLevel => Sim}/TrainSettlers.cs (97%) rename TbsCore/Tasks/{LowLevel => Sim}/UpgradeBuilding.cs (97%) rename TbsCore/Tasks/{LowLevel => Update}/CheckProfile.cs (100%) rename TbsCore/Tasks/{LowLevel => Update}/GetServerInfo.cs (97%) rename TbsCore/Tasks/{LowLevel => Update}/GetTribe.cs (97%) rename TbsCore/Tasks/{LowLevel => Update}/HeroUpdateInfo.cs (97%) rename TbsCore/Tasks/{LowLevel => Update}/ReadMessage.cs (97%) rename TbsCore/Tasks/{LowLevel => Update}/UpdateDorf1.cs (96%) rename TbsCore/Tasks/{LowLevel => Update}/UpdateDorf2.cs (96%) rename TbsCore/Tasks/{LowLevel => Update}/UpdateTaskUseRes.cs (100%) rename TbsCore/Tasks/{LowLevel => Update}/UpdateTroops.cs (97%) rename TbsCore/Tasks/{LowLevel => Update}/UpdateVillage.cs (97%) diff --git a/TbsCore/Tasks/LowLevel/BotTask.cs b/TbsCore/Tasks/BotTask.cs similarity index 96% rename from TbsCore/Tasks/LowLevel/BotTask.cs rename to TbsCore/Tasks/BotTask.cs index b1997dfc7..4d319081d 100644 --- a/TbsCore/Tasks/LowLevel/BotTask.cs +++ b/TbsCore/Tasks/BotTask.cs @@ -1,132 +1,132 @@ -using System; -using System.Threading; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.VillageModels; - -namespace TbsCore.Tasks -{ - public abstract class BotTask - { - /// - /// If of the village to execute the task. If null, don't change village before executing the task - /// - public Village Vill { get; set; } - - /// - /// Stage in which task is currently in. - /// - public TaskStage Stage { get; set; } - - /// - /// When to execute the task - /// - public DateTime ExecuteAt { get; set; } - - /// - /// When we want to re-execute a continuous task (build/demolish building, improve unit etc.) - /// - public DateTime? NextExecute { get; set; } - - /// - /// BotTask to be executed right after this one. Used only is specific cases. - /// - public BotTask NextTask { get; set; } - - /// - /// After each execution, if return bool is true, there has to be a new browser load event. Bot will wait for that event. - /// If there is no browser load event (just parsing some data eg. GetMapSize, return false and browser will navigate to dorf1/2. - /// - /// Account - /// TaskRes - public abstract Task Execute(Account acc); - - /// - /// Counts how many times we retried executing the task. After 3rd try, stop retrying. Something is clearly wrong - /// Used in TaskExecutor and TaskTimer - /// - public int RetryCounter { get; set; } = 0; - - /// - /// How high of a priority does this task have. - /// Tasks like attacking and deffending (waves) have highest priority and should as such be executed first - /// - public TaskPriority Priority { get; set; } - - private long stopFlag; - - public bool StopFlag - { - get - { - return Interlocked.Read(ref stopFlag) == 1; - } - set - { - Interlocked.Exchange(ref stopFlag, Convert.ToInt64(value)); - } - } - - protected async Task Update(Account acc) - { - if (!await DriverHelper.WaitPageLoaded(acc)) - { - StopFlag = true; - return false; - } - return true; - } - - protected void Retry(Account acc, string message) - { - if (RetryCounter < 4) - { - RetryCounter++; - acc.Logger.Information($"{message}. Try again. ({RetryCounter} time(s))", this); - } - else - { - acc.Logger.Information($"{message}.", this); - acc.Logger.Warning($"Already tries 3 times. Considering there is error, please check account's browser.", this); - StopFlag = true; - } - } - - public enum TaskRes - { - Executed, - Retry - } - - public enum TaskStage - { - Start, - Executing, - } - - /// - /// Priority of the task - /// - public enum TaskPriority - { - /// - /// For tasks that can wait few hours. For example updating hero items, - /// account info, TOP10, dorf1 (for attacks) etc. - /// - Low, - - /// - /// For normal tasks, not urgent. For example building, adventures, - /// sending resources etc. Selected by default. - /// - Medium, - - /// - /// Time-critical tasks, for example sending catapult waves, sending - /// deff troops - tasks that require to-second precision. - /// - High - } - } +using System; +using System.Threading; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.VillageModels; + +namespace TbsCore.Tasks +{ + public abstract class BotTask + { + /// + /// If of the village to execute the task. If null, don't change village before executing the task + /// + public Village Vill { get; set; } + + /// + /// Stage in which task is currently in. + /// + public TaskStage Stage { get; set; } + + /// + /// When to execute the task + /// + public DateTime ExecuteAt { get; set; } + + /// + /// When we want to re-execute a continuous task (build/demolish building, improve unit etc.) + /// + public DateTime? NextExecute { get; set; } + + /// + /// BotTask to be executed right after this one. Used only is specific cases. + /// + public BotTask NextTask { get; set; } + + /// + /// After each execution, if return bool is true, there has to be a new browser load event. Bot will wait for that event. + /// If there is no browser load event (just parsing some data eg. GetMapSize, return false and browser will navigate to dorf1/2. + /// + /// Account + /// TaskRes + public abstract Task Execute(Account acc); + + /// + /// Counts how many times we retried executing the task. After 3rd try, stop retrying. Something is clearly wrong + /// Used in TaskExecutor and TaskTimer + /// + public int RetryCounter { get; set; } = 0; + + /// + /// How high of a priority does this task have. + /// Tasks like attacking and deffending (waves) have highest priority and should as such be executed first + /// + public TaskPriority Priority { get; set; } + + private long stopFlag; + + public bool StopFlag + { + get + { + return Interlocked.Read(ref stopFlag) == 1; + } + set + { + Interlocked.Exchange(ref stopFlag, Convert.ToInt64(value)); + } + } + + protected async Task Update(Account acc) + { + if (!await DriverHelper.WaitPageLoaded(acc)) + { + StopFlag = true; + return false; + } + return true; + } + + protected void Retry(Account acc, string message) + { + if (RetryCounter < 4) + { + RetryCounter++; + acc.Logger.Information($"{message}. Try again. ({RetryCounter} time(s))", this); + } + else + { + acc.Logger.Information($"{message}.", this); + acc.Logger.Warning($"Already tries 3 times. Considering there is error, please check account's browser.", this); + StopFlag = true; + } + } + + public enum TaskRes + { + Executed, + Retry + } + + public enum TaskStage + { + Start, + Executing, + } + + /// + /// Priority of the task + /// + public enum TaskPriority + { + /// + /// For tasks that can wait few hours. For example updating hero items, + /// account info, TOP10, dorf1 (for attacks) etc. + /// + Low, + + /// + /// For normal tasks, not urgent. For example building, adventures, + /// sending resources etc. Selected by default. + /// + Medium, + + /// + /// Time-critical tasks, for example sending catapult waves, sending + /// deff troops - tasks that require to-second precision. + /// + High + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/BotTaskTemplate.cs b/TbsCore/Tasks/BotTaskTemplate.cs similarity index 96% rename from TbsCore/Tasks/LowLevel/BotTaskTemplate.cs rename to TbsCore/Tasks/BotTaskTemplate.cs index 6af871231..2fe9bc382 100644 --- a/TbsCore/Tasks/LowLevel/BotTaskTemplate.cs +++ b/TbsCore/Tasks/BotTaskTemplate.cs @@ -1,14 +1,14 @@ -using System.Threading.Tasks; -using TbsCore.Models.AccModels; - -namespace TbsCore.Tasks.LowLevel -{ - public class BotTaskTemplate : BotTask - { - public override async Task Execute(Account acc) - { - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/dorf1.php"); - return TaskRes.Executed; - } - } +using System.Threading.Tasks; +using TbsCore.Models.AccModels; + +namespace TbsCore.Tasks.LowLevel +{ + public class BotTaskTemplate : BotTask + { + public override async Task Execute(Account acc) + { + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/dorf1.php"); + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/ChangeAccess.cs b/TbsCore/Tasks/Browser/ChangeAccess.cs similarity index 98% rename from TbsCore/Tasks/LowLevel/ChangeAccess.cs rename to TbsCore/Tasks/Browser/ChangeAccess.cs index 6928d8664..ddf6aee3f 100644 --- a/TbsCore/Tasks/LowLevel/ChangeAccess.cs +++ b/TbsCore/Tasks/Browser/ChangeAccess.cs @@ -1,6 +1,6 @@ using System; using System.Threading.Tasks; -using TbsCore.Models.AccModels; +using TbsCore.Models.AccModels; using TbsCore.Helpers; namespace TbsCore.Tasks.LowLevel @@ -9,23 +9,23 @@ namespace TbsCore.Tasks.LowLevel /// This task changes access (and restarts selenium driver) for the account and sets the next access change, if there are multiple access'. /// public class ChangeAccess : ReopenDriver - { - private readonly Random rand = new Random(); - private DateTime sleepEnd; - + { + private readonly Random rand = new Random(); + private DateTime sleepEnd; + public override async Task Execute(Account acc) { // may add setting for these // how "lag" for duals login to your account (in minutes) - var min = 10 * 60; // 10 mins - var max = 30 * 60; // 30 mins - int nextTime = rand.Next(min, max); - sleepEnd = DateTime.Now.AddSeconds(nextTime); - - acc.Logger.Information($"New proxy will be change at {sleepEnd}"); - ChangeAccess = true; - await base.Execute(acc); - + var min = 10 * 60; // 10 mins + var max = 30 * 60; // 30 mins + int nextTime = rand.Next(min, max); + sleepEnd = DateTime.Now.AddSeconds(nextTime); + + acc.Logger.Information($"New proxy will be change at {sleepEnd}"); + ChangeAccess = true; + await base.Execute(acc); + var nextProxyChange = TimeHelper.GetNextProxyChange(acc); if (nextProxyChange != TimeSpan.MaxValue) { @@ -36,18 +36,18 @@ public override async Task Execute(Account acc) return TaskRes.Executed; } - public DateTime GetSleepEnd(Account acc) - { - var min = acc.Settings.Time.MinSleep * 60; - var max = acc.Settings.Time.MaxSleep * 60; - int sleepSec = rand.Next(min, max); - return DateTime.Now.AddSeconds(sleepSec); - } - - public override int GetMinutes(Account acc) - { - var delay = sleepEnd - DateTime.Now; - return (int)delay.TotalMinutes; + public DateTime GetSleepEnd(Account acc) + { + var min = acc.Settings.Time.MinSleep * 60; + var max = acc.Settings.Time.MaxSleep * 60; + int sleepSec = rand.Next(min, max); + return DateTime.Now.AddSeconds(sleepSec); + } + + public override int GetMinutes(Account acc) + { + var delay = sleepEnd - DateTime.Now; + return (int)delay.TotalMinutes; } } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/CheckAttacks.cs b/TbsCore/Tasks/Browser/CheckAttacks.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/CheckAttacks.cs rename to TbsCore/Tasks/Browser/CheckAttacks.cs index e030f7f7f..ca0900a17 100644 --- a/TbsCore/Tasks/LowLevel/CheckAttacks.cs +++ b/TbsCore/Tasks/Browser/CheckAttacks.cs @@ -1,136 +1,136 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Models.SendTroopsModels; -using TbsCore.Helpers; -using TbsCore.Models.VillageModels; -using TbsCore.Parsers; - -namespace TbsCore.Tasks.LowLevel -{ - public class CheckAttacks : BotTask - { - public override async Task Execute(Account acc) - { - //await NavigationHelper.ToRallyPoint(acc, Vill, NavigationHelper.RallyPointTab.Overview) - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?gid=16&tt=1&filter=1&subfilters=1"); - - var attacks = TroopsMovementParser.ParseTroopsOverview(acc, acc.Wb.Html); - - var pageCnt = TroopsMovementParser.GetPageCount(acc.Wb.Html); - - // Parsed all incoming attacks - if (pageCnt == 1) return CheckCompleted(acc, attacks); - - // If there are multiple pages of attacks and attacks per page is less than 50, - // increase number of attacks per page in preferences, then repeat CheckAttacks - if (3 <= pageCnt && attacks.Count < 50) - { - acc.Tasks.Add(new EditPreferences() - { - TroopsPerPage = 99, // Max - ExecuteAt = DateTime.MinValue.AddHours(1), - NextTask = new CheckAttacks() { Vill = this.Vill }, - }); - return TaskRes.Executed; - } - - // Check all pages of the attacks - int page = 1; - do - { - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?gid=16&tt=1&filter=1&subfilters=1&page={++page}"); - var pageAttacks = TroopsMovementParser.ParseTroopsOverview(acc, acc.Wb.Html); - attacks.AddRange(pageAttacks); - await Task.Delay(AccountHelper.Delay(acc)); - } - while (!acc.Wb.Html // While the next page img isn't disabled - .GetElementbyId("build") - .Descendants("div") - .First(x => x.HasClass("paginator")) - .Descendants("img") - .First() - .HasClass("disabled") - ); - - return CheckCompleted(acc, attacks); - } - - /// - /// After getting all attacks, check for differences in attacks, alert user and - /// configure this task for next check - /// - /// Incoming attacks - /// TaskRes.Executed - private TaskRes CheckCompleted(Account acc, List attacks) - { - // There are no attacks on the village - if (attacks.Count == 0 || Vill.Deffing.AlertType == AlertTypeEnum.Disabled) return TaskRes.Executed; - - // In case it was null - if (Vill.TroopMovements.IncomingAttacks == null) Vill.TroopMovements.IncomingAttacks = new List(); - - for (var i = 0; i < Vill.TroopMovements.IncomingAttacks.Count; i++) - { - var oldAttack = Vill.TroopMovements.IncomingAttacks[i]; - // Attack already happen - if (DateTime.Compare(DateTime.Now, oldAttack.Arrival) > 0) - { - Vill.TroopMovements.IncomingAttacks.RemoveAt(i); - continue; - } - - // Remove all attacks that were discovered previously - attacks.RemoveAll(x => x.Equals(oldAttack)); - } - - // Alert user if new attacks were found - string alertStr = ""; - foreach (var newAttack in attacks) - { - // Check if hero is present in the attack - if (Vill.Deffing.OnlyAlertOnHero && newAttack.Troops[10] == 0) continue; - - if (newAttack.MovementType == Classificator.MovementTypeRallyPoint.inRaid) - { - if (Vill.Deffing.AlertType == AlertTypeEnum.AnyAttack) - { - alertStr += $"Raid from {newAttack.SourceCoordinates} at {newAttack.Arrival}\n"; - } - } - else alertStr += $"Normal attack from {newAttack.SourceCoordinates} at {newAttack.Arrival} (server time)\n"; - } - - if (!String.IsNullOrEmpty(alertStr)) - { - //send to discord webhook - if (acc.Settings.DiscordWebhook) - { - new Thread(() => - DiscordHelper.SendMessage(acc, $"Village {Vill.Name} is under {attacks.Count} new attacks!\n{alertStr}") - ).Start(); - } - else - { - // Popup + sound - new Thread(() => - IoHelperCore.AlertUser?.Invoke($"Village {Vill.Name} is under {attacks.Count} new attacks!\n{alertStr}") - ).Start(); - } - } - - Vill.TroopMovements.IncomingAttacks.AddRange(attacks); - // Next check for new attacks should be in: - // - 1x speed = 30 min - // - 3x speed = 10 min - // - 5x speed = 6 min - var nextCheckMin = 30 / acc.AccInfo.ServerSpeed; - this.NextExecute = DateTime.Now.AddMinutes(Math.Max(nextCheckMin, 2)); // For TTWars - - return TaskRes.Executed; - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Models.SendTroopsModels; +using TbsCore.Helpers; +using TbsCore.Models.VillageModels; +using TbsCore.Parsers; + +namespace TbsCore.Tasks.LowLevel +{ + public class CheckAttacks : BotTask + { + public override async Task Execute(Account acc) + { + //await NavigationHelper.ToRallyPoint(acc, Vill, NavigationHelper.RallyPointTab.Overview) + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?gid=16&tt=1&filter=1&subfilters=1"); + + var attacks = TroopsMovementParser.ParseTroopsOverview(acc, acc.Wb.Html); + + var pageCnt = TroopsMovementParser.GetPageCount(acc.Wb.Html); + + // Parsed all incoming attacks + if (pageCnt == 1) return CheckCompleted(acc, attacks); + + // If there are multiple pages of attacks and attacks per page is less than 50, + // increase number of attacks per page in preferences, then repeat CheckAttacks + if (3 <= pageCnt && attacks.Count < 50) + { + acc.Tasks.Add(new EditPreferences() + { + TroopsPerPage = 99, // Max + ExecuteAt = DateTime.MinValue.AddHours(1), + NextTask = new CheckAttacks() { Vill = this.Vill }, + }); + return TaskRes.Executed; + } + + // Check all pages of the attacks + int page = 1; + do + { + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?gid=16&tt=1&filter=1&subfilters=1&page={++page}"); + var pageAttacks = TroopsMovementParser.ParseTroopsOverview(acc, acc.Wb.Html); + attacks.AddRange(pageAttacks); + await Task.Delay(AccountHelper.Delay(acc)); + } + while (!acc.Wb.Html // While the next page img isn't disabled + .GetElementbyId("build") + .Descendants("div") + .First(x => x.HasClass("paginator")) + .Descendants("img") + .First() + .HasClass("disabled") + ); + + return CheckCompleted(acc, attacks); + } + + /// + /// After getting all attacks, check for differences in attacks, alert user and + /// configure this task for next check + /// + /// Incoming attacks + /// TaskRes.Executed + private TaskRes CheckCompleted(Account acc, List attacks) + { + // There are no attacks on the village + if (attacks.Count == 0 || Vill.Deffing.AlertType == AlertTypeEnum.Disabled) return TaskRes.Executed; + + // In case it was null + if (Vill.TroopMovements.IncomingAttacks == null) Vill.TroopMovements.IncomingAttacks = new List(); + + for (var i = 0; i < Vill.TroopMovements.IncomingAttacks.Count; i++) + { + var oldAttack = Vill.TroopMovements.IncomingAttacks[i]; + // Attack already happen + if (DateTime.Compare(DateTime.Now, oldAttack.Arrival) > 0) + { + Vill.TroopMovements.IncomingAttacks.RemoveAt(i); + continue; + } + + // Remove all attacks that were discovered previously + attacks.RemoveAll(x => x.Equals(oldAttack)); + } + + // Alert user if new attacks were found + string alertStr = ""; + foreach (var newAttack in attacks) + { + // Check if hero is present in the attack + if (Vill.Deffing.OnlyAlertOnHero && newAttack.Troops[10] == 0) continue; + + if (newAttack.MovementType == Classificator.MovementTypeRallyPoint.inRaid) + { + if (Vill.Deffing.AlertType == AlertTypeEnum.AnyAttack) + { + alertStr += $"Raid from {newAttack.SourceCoordinates} at {newAttack.Arrival}\n"; + } + } + else alertStr += $"Normal attack from {newAttack.SourceCoordinates} at {newAttack.Arrival} (server time)\n"; + } + + if (!String.IsNullOrEmpty(alertStr)) + { + //send to discord webhook + if (acc.Settings.DiscordWebhook) + { + new Thread(() => + DiscordHelper.SendMessage(acc, $"Village {Vill.Name} is under {attacks.Count} new attacks!\n{alertStr}") + ).Start(); + } + else + { + // Popup + sound + new Thread(() => + IoHelperCore.AlertUser?.Invoke($"Village {Vill.Name} is under {attacks.Count} new attacks!\n{alertStr}") + ).Start(); + } + } + + Vill.TroopMovements.IncomingAttacks.AddRange(attacks); + // Next check for new attacks should be in: + // - 1x speed = 30 min + // - 3x speed = 10 min + // - 5x speed = 6 min + var nextCheckMin = 30 / acc.AccInfo.ServerSpeed; + this.NextExecute = DateTime.Now.AddMinutes(Math.Max(nextCheckMin, 2)); // For TTWars + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/ReopenDriver.cs b/TbsCore/Tasks/Browser/ReopenDriver.cs similarity index 96% rename from TbsCore/Tasks/LowLevel/ReopenDriver.cs rename to TbsCore/Tasks/Browser/ReopenDriver.cs index f7612f8db..e22ebcfa3 100644 --- a/TbsCore/Tasks/LowLevel/ReopenDriver.cs +++ b/TbsCore/Tasks/Browser/ReopenDriver.cs @@ -1,48 +1,48 @@ -using System; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Helpers; -using System.Linq; - -namespace TbsCore.Tasks.LowLevel -{ - /// - /// Task will close and reopen driver then the next Normal/High priority task has to be executed - /// - public abstract class ReopenDriver : BotTask - { - public bool ChangeAccess = false; - - public override async Task Execute(Account acc) - { - StopFlag = false; - acc.Wb.Close(); - string previousLog = ""; - do - { - if (StopFlag) break; - await Task.Delay(1000); - var minutes = GetMinutes(acc); - if (minutes <= 0) break; - string log = $"Chrome will reopen in {minutes} mins"; - - if (log != previousLog) - { - acc.Logger.Information(log); - previousLog = log; - } - } - while (true); - // Use the same access - var result = await acc.Wb.Init(acc, ChangeAccess); - if (!result) - { - acc.TaskTimer.Stop(); - } - - return TaskRes.Executed; - } - - public abstract int GetMinutes(Account acc); - } +using System; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Helpers; +using System.Linq; + +namespace TbsCore.Tasks.LowLevel +{ + /// + /// Task will close and reopen driver then the next Normal/High priority task has to be executed + /// + public abstract class ReopenDriver : BotTask + { + public bool ChangeAccess = false; + + public override async Task Execute(Account acc) + { + StopFlag = false; + acc.Wb.Close(); + string previousLog = ""; + do + { + if (StopFlag) break; + await Task.Delay(1000); + var minutes = GetMinutes(acc); + if (minutes <= 0) break; + string log = $"Chrome will reopen in {minutes} mins"; + + if (log != previousLog) + { + acc.Logger.Information(log); + previousLog = log; + } + } + while (true); + // Use the same access + var result = await acc.Wb.Init(acc, ChangeAccess); + if (!result) + { + acc.TaskTimer.Stop(); + } + + return TaskRes.Executed; + } + + public abstract int GetMinutes(Account acc); + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/RestartChrome.cs b/TbsCore/Tasks/Browser/RestartChrome.cs similarity index 100% rename from TbsCore/Tasks/LowLevel/RestartChrome.cs rename to TbsCore/Tasks/Browser/RestartChrome.cs diff --git a/TbsCore/Tasks/LowLevel/TaskSleep.cs b/TbsCore/Tasks/Browser/TaskSleep.cs similarity index 100% rename from TbsCore/Tasks/LowLevel/TaskSleep.cs rename to TbsCore/Tasks/Browser/TaskSleep.cs diff --git a/TbsCore/Tasks/LowLevel/TimeSleep.cs b/TbsCore/Tasks/Browser/TimeSleep.cs similarity index 100% rename from TbsCore/Tasks/LowLevel/TimeSleep.cs rename to TbsCore/Tasks/Browser/TimeSleep.cs diff --git a/TbsCore/Tasks/LowLevel/AddFarm.cs b/TbsCore/Tasks/Farm/AddFarm.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/AddFarm.cs rename to TbsCore/Tasks/Farm/AddFarm.cs index da7f7dbd0..82e6b4403 100644 --- a/TbsCore/Tasks/LowLevel/AddFarm.cs +++ b/TbsCore/Tasks/Farm/AddFarm.cs @@ -1,48 +1,48 @@ -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.VillageModels; - -namespace TbsCore.Tasks.LowLevel -{ - public class AddFarm : BotTask - { - public int FarmListId { get; set; } - public Farm Farm { get; set; } - - public override async Task Execute(Account acc) - { - - await NavigationHelper.ToRallyPoint(acc, Vill, NavigationHelper.RallyPointTab.Farmlist); - - // Show "Add raid" popup - await DriverHelper.ExecuteScript(acc, $"Travian.Game.RaidList.addSlot({this.FarmListId},'','','rallyPoint');"); - - // Input coordinates - await DriverHelper.WriteCoordinates(acc, Farm.Coords); - - // Input troops - for (int i = 0; i < Farm.Troops.Length; i++) - { - if (Farm.Troops[i] == 0) continue; - await DriverHelper.WriteById(acc, $"t{i + 1}", Farm.Troops[i]); - } - - await Task.Delay(AccountHelper.Delay(acc)); - - // Click "save" - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.TTwars: - acc.Wb.ExecuteScript("Travian.Game.RaidList.saveSlot(getSelectedListId(), $('edit_form').toQueryString().parseQueryString(), true);"); - break; - - case Classificator.ServerVersionEnum.T4_5: - await DriverHelper.ClickById(acc, "save"); - break; - } - - return TaskRes.Executed; - } - } +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.VillageModels; + +namespace TbsCore.Tasks.LowLevel +{ + public class AddFarm : BotTask + { + public int FarmListId { get; set; } + public Farm Farm { get; set; } + + public override async Task Execute(Account acc) + { + + await NavigationHelper.ToRallyPoint(acc, Vill, NavigationHelper.RallyPointTab.Farmlist); + + // Show "Add raid" popup + await DriverHelper.ExecuteScript(acc, $"Travian.Game.RaidList.addSlot({this.FarmListId},'','','rallyPoint');"); + + // Input coordinates + await DriverHelper.WriteCoordinates(acc, Farm.Coords); + + // Input troops + for (int i = 0; i < Farm.Troops.Length; i++) + { + if (Farm.Troops[i] == 0) continue; + await DriverHelper.WriteById(acc, $"t{i + 1}", Farm.Troops[i]); + } + + await Task.Delay(AccountHelper.Delay(acc)); + + // Click "save" + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.TTwars: + acc.Wb.ExecuteScript("Travian.Game.RaidList.saveSlot(getSelectedListId(), $('edit_form').toQueryString().parseQueryString(), true);"); + break; + + case Classificator.ServerVersionEnum.T4_5: + await DriverHelper.ClickById(acc, "save"); + break; + } + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/SecondLevel/AttackOasis.cs b/TbsCore/Tasks/Farm/AttackOasis.cs similarity index 100% rename from TbsCore/Tasks/SecondLevel/AttackOasis.cs rename to TbsCore/Tasks/Farm/AttackOasis.cs diff --git a/TbsCore/Tasks/LowLevel/ImproveTroop.cs b/TbsCore/Tasks/Farm/ImproveTroop.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/ImproveTroop.cs rename to TbsCore/Tasks/Farm/ImproveTroop.cs index 78186b786..f9b64abea 100644 --- a/TbsCore/Tasks/LowLevel/ImproveTroop.cs +++ b/TbsCore/Tasks/Farm/ImproveTroop.cs @@ -1,93 +1,93 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.TroopsModels; -using TbsCore.Models.VillageModels; -using TbsCore.Parsers; - -namespace TbsCore.Tasks.LowLevel -{ - public class ImproveTroop : BotTask - { - public override async Task Execute(Account acc) - { - if (Vill == null) Vill = acc.Villages.First(x => x.Active); - - if (!await NavigationHelper.EnterBuilding(acc, Vill, Classificator.BuildingEnum.Smithy)) - return TaskRes.Executed; - - var levels = TroopsParser.GetTroopLevels(acc.Wb.Html); - if (levels == null) - { - acc.Logger.Warning("There was an error at getting Smithy troop levels"); - return TaskRes.Executed; - } - Vill.Troops.Levels = levels; - TroopsHelper.UpdateResearchedTroops(Vill); - - var currentlyImproving = TroopsParser.GetImprovingTroops(acc.Wb.Html); - var troop = TroopToImprove(Vill, currentlyImproving); - if (troop == Classificator.TroopsEnum.None) - { - return TaskRes.Executed; - } - - //If we have plus account we can improve 2 troops at the same time - int maxImproving = acc.AccInfo.PlusAccount ? 2 : 1; - if (maxImproving <= currentlyImproving.Count()) - { - this.NextExecute = DateTime.Now.Add(currentlyImproving.Last().Time); - return TaskRes.Executed; - } - //call NextImprove() after enough res OR when this improvement finishes. - - var cost = Vill.Troops.Levels.FirstOrDefault(x => x.Troop == troop); - - // Check if we have enough resources to improve the troop - if (!ResourcesHelper.IsEnoughRes(Vill, cost.UpgradeCost.ToArray())) - { - ResourcesHelper.NotEnoughRes(acc, Vill, cost.UpgradeCost, this); - return TaskRes.Executed; - } - - //Click on the button - var troopNode = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("u" + (int)troop)); - while (!troopNode.HasClass("research")) troopNode = troopNode.ParentNode; - - var button = troopNode.Descendants("button").FirstOrDefault(x => x.HasClass("green")); - if (button == null) - { - acc.Logger.Warning($"Could not find Upgrade button to improve {troop}"); - this.NextExecute = DateTime.Now.AddMinutes(1); - return TaskRes.Retry; - } - - await DriverHelper.ClickById(acc, button.Id); - - // If we have plus account and there is currently no other troop to improve, go ahead and improve the unit again - this.NextExecute = (currentlyImproving.Count() == 0 && maxImproving == 2) ? - DateTime.MinValue : - DateTime.Now.Add(cost.TimeCost).AddMilliseconds(5 * AccountHelper.Delay(acc)); - return TaskRes.Executed; - } - - private Classificator.TroopsEnum TroopToImprove(Village vill, List improving) - { - var troop = vill.Troops.ToImprove.FirstOrDefault(); - if (troop == Classificator.TroopsEnum.None) return troop; - //how many times is this troop improving (0/1/2) - int alreadyImprovingTime = improving.Count(x => x.Troop == troop); - - if (!vill.Troops.Levels.Exists(x => x.Troop == troop) || - vill.Troops.Levels.First(x => x.Troop == troop).Level + alreadyImprovingTime >= 20) - { - vill.Troops.ToImprove.Remove(troop); - return TroopToImprove(vill, improving); - } - return troop; - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.TroopsModels; +using TbsCore.Models.VillageModels; +using TbsCore.Parsers; + +namespace TbsCore.Tasks.LowLevel +{ + public class ImproveTroop : BotTask + { + public override async Task Execute(Account acc) + { + if (Vill == null) Vill = acc.Villages.First(x => x.Active); + + if (!await NavigationHelper.EnterBuilding(acc, Vill, Classificator.BuildingEnum.Smithy)) + return TaskRes.Executed; + + var levels = TroopsParser.GetTroopLevels(acc.Wb.Html); + if (levels == null) + { + acc.Logger.Warning("There was an error at getting Smithy troop levels"); + return TaskRes.Executed; + } + Vill.Troops.Levels = levels; + TroopsHelper.UpdateResearchedTroops(Vill); + + var currentlyImproving = TroopsParser.GetImprovingTroops(acc.Wb.Html); + var troop = TroopToImprove(Vill, currentlyImproving); + if (troop == Classificator.TroopsEnum.None) + { + return TaskRes.Executed; + } + + //If we have plus account we can improve 2 troops at the same time + int maxImproving = acc.AccInfo.PlusAccount ? 2 : 1; + if (maxImproving <= currentlyImproving.Count()) + { + this.NextExecute = DateTime.Now.Add(currentlyImproving.Last().Time); + return TaskRes.Executed; + } + //call NextImprove() after enough res OR when this improvement finishes. + + var cost = Vill.Troops.Levels.FirstOrDefault(x => x.Troop == troop); + + // Check if we have enough resources to improve the troop + if (!ResourcesHelper.IsEnoughRes(Vill, cost.UpgradeCost.ToArray())) + { + ResourcesHelper.NotEnoughRes(acc, Vill, cost.UpgradeCost, this); + return TaskRes.Executed; + } + + //Click on the button + var troopNode = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("u" + (int)troop)); + while (!troopNode.HasClass("research")) troopNode = troopNode.ParentNode; + + var button = troopNode.Descendants("button").FirstOrDefault(x => x.HasClass("green")); + if (button == null) + { + acc.Logger.Warning($"Could not find Upgrade button to improve {troop}"); + this.NextExecute = DateTime.Now.AddMinutes(1); + return TaskRes.Retry; + } + + await DriverHelper.ClickById(acc, button.Id); + + // If we have plus account and there is currently no other troop to improve, go ahead and improve the unit again + this.NextExecute = (currentlyImproving.Count() == 0 && maxImproving == 2) ? + DateTime.MinValue : + DateTime.Now.Add(cost.TimeCost).AddMilliseconds(5 * AccountHelper.Delay(acc)); + return TaskRes.Executed; + } + + private Classificator.TroopsEnum TroopToImprove(Village vill, List improving) + { + var troop = vill.Troops.ToImprove.FirstOrDefault(); + if (troop == Classificator.TroopsEnum.None) return troop; + //how many times is this troop improving (0/1/2) + int alreadyImprovingTime = improving.Count(x => x.Troop == troop); + + if (!vill.Troops.Levels.Exists(x => x.Troop == troop) || + vill.Troops.Levels.First(x => x.Troop == troop).Level + alreadyImprovingTime >= 20) + { + vill.Troops.ToImprove.Remove(troop); + return TroopToImprove(vill, improving); + } + return troop; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/ReadFarmScoutReport.cs b/TbsCore/Tasks/Farm/ReadFarmScoutReport.cs similarity index 100% rename from TbsCore/Tasks/LowLevel/ReadFarmScoutReport.cs rename to TbsCore/Tasks/Farm/ReadFarmScoutReport.cs diff --git a/TbsCore/Tasks/LowLevel/ResearchTroop.cs b/TbsCore/Tasks/Farm/ResearchTroop.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/ResearchTroop.cs rename to TbsCore/Tasks/Farm/ResearchTroop.cs index 7bae0267b..225257ce8 100644 --- a/TbsCore/Tasks/LowLevel/ResearchTroop.cs +++ b/TbsCore/Tasks/Farm/ResearchTroop.cs @@ -1,68 +1,68 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.ResourceModels; -using TbsCore.Models.VillageModels; -using TbsCore.Parsers; - -using static TbsCore.Helpers.Classificator; - -namespace TbsCore.Tasks.LowLevel -{ - public class ResearchTroop : BotTask - { - //If Troop == null, just update the troop levels - public override async Task Execute(Account acc) - { - if (!await NavigationHelper.EnterBuilding(acc, Vill, BuildingEnum.Academy)) - return TaskRes.Executed; - - var troop = Vill.Troops.ToResearch.FirstOrDefault(); - if (troop == TroopsEnum.None) return TaskRes.Executed; //We have researched all troops that were on the list - - var troopNode = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("u" + (int)troop)); - if (troopNode == null) - { - acc.Logger.Warning($"Researching {troop} was not possible! Bot assumes you already have it researched"); - Vill.Troops.Researched.Add(troop); - return TaskRes.Retry; - } - while (!troopNode.HasClass("research")) troopNode = troopNode.ParentNode; - - var button = troopNode.Descendants("button").FirstOrDefault(x => x.HasClass("green")); - if (button == null) - { - RepeatTask(Vill, troop, DateTime.Now); - } - (TimeSpan dur, Resources cost) = TroopsParser.AcademyResearchCost(acc.Wb.Html, troop); - - // Check if we have enough resources to research the troop - if (!ResourcesHelper.IsEnoughRes(Vill, cost.ToArray())) - { - ResourcesHelper.NotEnoughRes(acc, Vill, cost, this); - return TaskRes.Executed; - } - - await DriverHelper.ClickById(acc, button.Id); - - var executeNext = DateTime.Now.Add(dur).AddMilliseconds(10 * AccountHelper.Delay(acc)); - if (Vill.Settings.AutoImprove) - { - acc.Tasks.Add(new ImproveTroop() { Vill = this.Vill, ExecuteAt = DateTime.Now.Add(dur) }); - } - - RepeatTask(Vill, troop, executeNext); - - return TaskRes.Executed; - } - - private void RepeatTask(Village vill, Classificator.TroopsEnum troop, DateTime nextExecute) - { - vill.Troops.ToResearch.Remove(troop); - //Next research when this one finishes - if (0 < vill.Troops.ToResearch.Count) this.NextExecute = nextExecute; - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.ResourceModels; +using TbsCore.Models.VillageModels; +using TbsCore.Parsers; + +using static TbsCore.Helpers.Classificator; + +namespace TbsCore.Tasks.LowLevel +{ + public class ResearchTroop : BotTask + { + //If Troop == null, just update the troop levels + public override async Task Execute(Account acc) + { + if (!await NavigationHelper.EnterBuilding(acc, Vill, BuildingEnum.Academy)) + return TaskRes.Executed; + + var troop = Vill.Troops.ToResearch.FirstOrDefault(); + if (troop == TroopsEnum.None) return TaskRes.Executed; //We have researched all troops that were on the list + + var troopNode = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("u" + (int)troop)); + if (troopNode == null) + { + acc.Logger.Warning($"Researching {troop} was not possible! Bot assumes you already have it researched"); + Vill.Troops.Researched.Add(troop); + return TaskRes.Retry; + } + while (!troopNode.HasClass("research")) troopNode = troopNode.ParentNode; + + var button = troopNode.Descendants("button").FirstOrDefault(x => x.HasClass("green")); + if (button == null) + { + RepeatTask(Vill, troop, DateTime.Now); + } + (TimeSpan dur, Resources cost) = TroopsParser.AcademyResearchCost(acc.Wb.Html, troop); + + // Check if we have enough resources to research the troop + if (!ResourcesHelper.IsEnoughRes(Vill, cost.ToArray())) + { + ResourcesHelper.NotEnoughRes(acc, Vill, cost, this); + return TaskRes.Executed; + } + + await DriverHelper.ClickById(acc, button.Id); + + var executeNext = DateTime.Now.Add(dur).AddMilliseconds(10 * AccountHelper.Delay(acc)); + if (Vill.Settings.AutoImprove) + { + acc.Tasks.Add(new ImproveTroop() { Vill = this.Vill, ExecuteAt = DateTime.Now.Add(dur) }); + } + + RepeatTask(Vill, troop, executeNext); + + return TaskRes.Executed; + } + + private void RepeatTask(Village vill, Classificator.TroopsEnum troop, DateTime nextExecute) + { + vill.Troops.ToResearch.Remove(troop); + //Next research when this one finishes + if (0 < vill.Troops.ToResearch.Count) this.NextExecute = nextExecute; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/SecondLevel/ScoutPlayer.cs b/TbsCore/Tasks/Farm/ScoutPlayer.cs similarity index 100% rename from TbsCore/Tasks/SecondLevel/ScoutPlayer.cs rename to TbsCore/Tasks/Farm/ScoutPlayer.cs diff --git a/TbsCore/Tasks/SecondLevel/SendDeff.cs b/TbsCore/Tasks/Farm/SendDeff.cs similarity index 97% rename from TbsCore/Tasks/SecondLevel/SendDeff.cs rename to TbsCore/Tasks/Farm/SendDeff.cs index fc8d41060..a5c26598d 100644 --- a/TbsCore/Tasks/SecondLevel/SendDeff.cs +++ b/TbsCore/Tasks/Farm/SendDeff.cs @@ -1,84 +1,84 @@ -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.MapModels; -using TbsCore.Models.SendTroopsModels; -using TbsCore.Models.TroopsModels; -using TbsCore.TravianData; - -namespace TbsCore.Tasks.LowLevel -{ - public class SendDeff : SendTroops - { - public SendDeffAmount DeffAmount { get; set; } - public Coordinates TargetVillage { get; set; } - - public override async Task Execute(Account acc) - { - // Can't send deff to home village or to 0/0 - if (TargetVillage == null || - TargetVillage.Equals(Vill.Coordinates) || - TargetVillage.Equals(new Coordinates(0, 0) { x = 0, y = 0 })) - { - return TaskRes.Executed; - } - - base.TroopsMovement = new TroopsSendModel() - { - TargetCoordinates = TargetVillage, - MovementType = Classificator.MovementType.Reinforcement, - // Bot will configure amount of troops to be sent when it parses - // the amount of troops available at home - Troops = new int[10], - }; - - base.TroopsCallback = TroopsCountRecieved; - - await base.Execute(acc); - - return TaskRes.Executed; - } - - public bool TroopsCountRecieved(Account acc, TroopsBase troops) - { - int upkeepSent = 0; - - for (int i = 0; i < 10; i++) - { - var troop = TroopsHelper.TroopFromInt(acc, i); - if (!TroopsData.IsTroopDefensive(troop) || troops.Troops[i] == 0) continue; - - var upkeep = TroopsData.GetTroopUpkeep(troop); - int sendAmount = troops.Troops[i]; - - int toSend = this.DeffAmount.Amount / upkeep; - bool finished = false; - if (toSend - upkeepSent < sendAmount) - { - // If we have enough troops, no other tasks need to be executed - this.NextTask = null; - finished = true; - sendAmount = toSend; - } - - base.TroopsMovement.Troops[i] = sendAmount; - - upkeepSent += sendAmount * upkeep; - - if (finished) break; - } - - this.DeffAmount.Amount -= upkeepSent; - if (this.DeffAmount.Amount > 0) - { - acc.Logger.Warning($"Bot will send {upkeepSent} deff (in upkeep) from {this.Vill.Name} to {this.TargetVillage}. Still needed {this.DeffAmount.Amount} deff"); - } - else - { - acc.Logger.Information($"Bot will send {upkeepSent} deff (in upkeep) from {this.Vill.Name} to {this.TargetVillage}."); - } - - return true; - } - } +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.MapModels; +using TbsCore.Models.SendTroopsModels; +using TbsCore.Models.TroopsModels; +using TbsCore.TravianData; + +namespace TbsCore.Tasks.LowLevel +{ + public class SendDeff : SendTroops + { + public SendDeffAmount DeffAmount { get; set; } + public Coordinates TargetVillage { get; set; } + + public override async Task Execute(Account acc) + { + // Can't send deff to home village or to 0/0 + if (TargetVillage == null || + TargetVillage.Equals(Vill.Coordinates) || + TargetVillage.Equals(new Coordinates(0, 0) { x = 0, y = 0 })) + { + return TaskRes.Executed; + } + + base.TroopsMovement = new TroopsSendModel() + { + TargetCoordinates = TargetVillage, + MovementType = Classificator.MovementType.Reinforcement, + // Bot will configure amount of troops to be sent when it parses + // the amount of troops available at home + Troops = new int[10], + }; + + base.TroopsCallback = TroopsCountRecieved; + + await base.Execute(acc); + + return TaskRes.Executed; + } + + public bool TroopsCountRecieved(Account acc, TroopsBase troops) + { + int upkeepSent = 0; + + for (int i = 0; i < 10; i++) + { + var troop = TroopsHelper.TroopFromInt(acc, i); + if (!TroopsData.IsTroopDefensive(troop) || troops.Troops[i] == 0) continue; + + var upkeep = TroopsData.GetTroopUpkeep(troop); + int sendAmount = troops.Troops[i]; + + int toSend = this.DeffAmount.Amount / upkeep; + bool finished = false; + if (toSend - upkeepSent < sendAmount) + { + // If we have enough troops, no other tasks need to be executed + this.NextTask = null; + finished = true; + sendAmount = toSend; + } + + base.TroopsMovement.Troops[i] = sendAmount; + + upkeepSent += sendAmount * upkeep; + + if (finished) break; + } + + this.DeffAmount.Amount -= upkeepSent; + if (this.DeffAmount.Amount > 0) + { + acc.Logger.Warning($"Bot will send {upkeepSent} deff (in upkeep) from {this.Vill.Name} to {this.TargetVillage}. Still needed {this.DeffAmount.Amount} deff"); + } + else + { + acc.Logger.Information($"Bot will send {upkeepSent} deff (in upkeep) from {this.Vill.Name} to {this.TargetVillage}."); + } + + return true; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/SecondLevel/SendFLs.cs b/TbsCore/Tasks/Farm/SendFLs.cs similarity index 97% rename from TbsCore/Tasks/SecondLevel/SendFLs.cs rename to TbsCore/Tasks/Farm/SendFLs.cs index 676cba6eb..1bccdfaf4 100644 --- a/TbsCore/Tasks/SecondLevel/SendFLs.cs +++ b/TbsCore/Tasks/Farm/SendFLs.cs @@ -1,60 +1,60 @@ -using System; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Helpers; -using TbsCore.Tasks.LowLevel; - -namespace TbsCore.Tasks.SecondLevel -{ - public class SendFLs : BotTask - { - public override async Task Execute(Account acc) - { - Random rnd = new Random(); - int totalSec = 0; - await Task.Delay(AccountHelper.Delay(acc) / 3); - - foreach (var fl in acc.Farming.FL) - { - // Check interval of the farmlist - if (fl.Interval > 1) - { - fl.IntervalCounter++; - if (fl.IntervalCounter < fl.Interval) continue; - fl.IntervalCounter = 0; - } - - if (fl.Enabled) - { - acc.Tasks.Add(new SendFarmlist() { ExecuteAt = DateTime.Now.AddSeconds(totalSec), FL = fl, Priority = TaskPriority.High }); - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.TTwars: - // For TTWars, you need 30sec delay between each FL send - totalSec += rnd.Next(acc.Farming.MinInterval, acc.Farming.MaxInterval); - break; - - case Classificator.ServerVersionEnum.T4_5: - totalSec += rnd.Next(5, 13); - break; - } - } - } - - int nextExecuteSec = 100; - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.TTwars: - nextExecuteSec = totalSec; - break; - - case Classificator.ServerVersionEnum.T4_5: - nextExecuteSec = rnd.Next(acc.Farming.MinInterval, acc.Farming.MaxInterval); - break; - } - acc.Tasks.Add(new SendFLs() { ExecuteAt = DateTime.Now.AddSeconds(nextExecuteSec), Priority = TaskPriority.High }); - - return TaskRes.Executed; - } - } +using System; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Helpers; +using TbsCore.Tasks.LowLevel; + +namespace TbsCore.Tasks.SecondLevel +{ + public class SendFLs : BotTask + { + public override async Task Execute(Account acc) + { + Random rnd = new Random(); + int totalSec = 0; + await Task.Delay(AccountHelper.Delay(acc) / 3); + + foreach (var fl in acc.Farming.FL) + { + // Check interval of the farmlist + if (fl.Interval > 1) + { + fl.IntervalCounter++; + if (fl.IntervalCounter < fl.Interval) continue; + fl.IntervalCounter = 0; + } + + if (fl.Enabled) + { + acc.Tasks.Add(new SendFarmlist() { ExecuteAt = DateTime.Now.AddSeconds(totalSec), FL = fl, Priority = TaskPriority.High }); + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.TTwars: + // For TTWars, you need 30sec delay between each FL send + totalSec += rnd.Next(acc.Farming.MinInterval, acc.Farming.MaxInterval); + break; + + case Classificator.ServerVersionEnum.T4_5: + totalSec += rnd.Next(5, 13); + break; + } + } + } + + int nextExecuteSec = 100; + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.TTwars: + nextExecuteSec = totalSec; + break; + + case Classificator.ServerVersionEnum.T4_5: + nextExecuteSec = rnd.Next(acc.Farming.MinInterval, acc.Farming.MaxInterval); + break; + } + acc.Tasks.Add(new SendFLs() { ExecuteAt = DateTime.Now.AddSeconds(nextExecuteSec), Priority = TaskPriority.High }); + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/SendFarmlist.cs b/TbsCore/Tasks/Farm/SendFarmlist.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/SendFarmlist.cs rename to TbsCore/Tasks/Farm/SendFarmlist.cs index e0c188466..a59222103 100644 --- a/TbsCore/Tasks/LowLevel/SendFarmlist.cs +++ b/TbsCore/Tasks/Farm/SendFarmlist.cs @@ -1,111 +1,111 @@ -using HtmlAgilityPack; -using OpenQA.Selenium; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.TroopsModels; -using TbsCore.Parsers; -using static TbsCore.Helpers.Classificator; - -namespace TbsCore.Tasks.LowLevel -{ - public class SendFarmlist : BotTask - { - public FarmList FL { get; set; } - - public override async Task Execute(Account acc) - { - await NavigationHelper.ToRallyPoint(acc, Vill, NavigationHelper.RallyPointTab.Farmlist); - - var flNode = GetFlNode(acc.Wb.Html, acc.AccInfo.ServerVersion); - - // If there is no rally point, switch to different village - if (flNode == null) - { - var mainVill = AccountHelper.GetMainVillage(acc); - if (mainVill == this.Vill) return TaskRes.Executed; // No gold account? - await VillageHelper.SwitchVillage(acc, mainVill.Id); - flNode = GetFlNode(acc.Wb.Html, acc.AccInfo.ServerVersion); - if (flNode == null) return TaskRes.Retry; - } - - if (acc.Farming.TrainTroopsAfterFL) // For TTWars servers - { - acc.Tasks.Add(new TrainTroops() - { - ExecuteAt = DateTime.Now.AddSeconds(2), - Troop = Vill.Troops.TroopToTrain ?? Classificator.TroopsEnum.Hero, - Vill = this.Vill, - HighSpeedServer = true - }); - } - - // If FL is collapsed, expand it - if (acc.AccInfo.ServerVersion == ServerVersionEnum.TTwars || - flNode.Descendants("div").Any(x => x.HasClass("expandCollapse") && x.HasClass("collapsed"))) - { - await DriverHelper.ExecuteScript(acc, $"Travian.Game.RaidList.toggleList({this.FL.Id});"); - await Task.Delay(500); - acc.Wb.UpdateHtml(); - // Update flNode! - flNode = GetFlNode(acc.Wb.Html, acc.AccInfo.ServerVersion); - } - - var farms = new List(); - foreach (var farm in flNode.Descendants("tr").Where(x => x.HasClass("slotRow"))) - { - //iReport2 = yellow swords, iReport3 = red swords, iReport1 = successful raid - var img = farm.ChildNodes.FirstOrDefault(x => x.HasClass("lastRaid"))?.Descendants("img"); - - var coords = MapParser.GetPositionDetails(farm); - farms.Add(new GoldClubFarm(coords)); - - //there has to be an image (we already have a report) and wrong raid style to not check this farmlist: - if (img.Count() != 0 && ( //no image -> no recent attack - (img.FirstOrDefault(x => x.HasClass("iReport3")) != null && this.FL.RaidStyle != RaidStyle.RaidLost) //raid was lost and we don't have RaidLost raidstyle - || (img.FirstOrDefault(x => x.HasClass("iReport2")) != null && (this.FL.RaidStyle == RaidStyle.RaidSuccessful)) //some casualities, but we only attack on successful - )) - { - continue; - } - - var checkbox = farm.Descendants("input").FirstOrDefault(x => x.HasClass("markSlot")); - await DriverHelper.CheckById(acc, checkbox.Id, true, update: false); - } - this.FL.Farms = farms; - - await Task.Delay(AccountHelper.Delay(acc) * 2); - - switch (acc.AccInfo.ServerVersion) - { - case ServerVersionEnum.TTwars: - var sendFlScript = $"document.getElementById('{flNode.Id}').childNodes[1].submit()"; - acc.Wb.ExecuteScript(sendFlScript); - break; - - case ServerVersionEnum.T4_5: - var startRaid = flNode.Descendants("button").FirstOrDefault(x => x.HasClass("startButton")); - acc.Wb.Driver.FindElement(By.Id(startRaid.Id)).Click(); - break; - } - - acc.Logger.Information($"FarmList '{this.FL.Name}' was sent"); - await Task.Delay(1000); - return TaskRes.Executed; - } - - private HtmlNode GetFlNode(HtmlDocument htmlDoc, ServerVersionEnum version) - { - switch (version) - { - case ServerVersionEnum.TTwars: return htmlDoc.GetElementbyId("list" + this.FL.Id); - - case ServerVersionEnum.T4_5: return htmlDoc.GetElementbyId("raidList" + this.FL.Id); - default: return null; - } - } - } +using HtmlAgilityPack; +using OpenQA.Selenium; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.TroopsModels; +using TbsCore.Parsers; +using static TbsCore.Helpers.Classificator; + +namespace TbsCore.Tasks.LowLevel +{ + public class SendFarmlist : BotTask + { + public FarmList FL { get; set; } + + public override async Task Execute(Account acc) + { + await NavigationHelper.ToRallyPoint(acc, Vill, NavigationHelper.RallyPointTab.Farmlist); + + var flNode = GetFlNode(acc.Wb.Html, acc.AccInfo.ServerVersion); + + // If there is no rally point, switch to different village + if (flNode == null) + { + var mainVill = AccountHelper.GetMainVillage(acc); + if (mainVill == this.Vill) return TaskRes.Executed; // No gold account? + await VillageHelper.SwitchVillage(acc, mainVill.Id); + flNode = GetFlNode(acc.Wb.Html, acc.AccInfo.ServerVersion); + if (flNode == null) return TaskRes.Retry; + } + + if (acc.Farming.TrainTroopsAfterFL) // For TTWars servers + { + acc.Tasks.Add(new TrainTroops() + { + ExecuteAt = DateTime.Now.AddSeconds(2), + Troop = Vill.Troops.TroopToTrain ?? Classificator.TroopsEnum.Hero, + Vill = this.Vill, + HighSpeedServer = true + }); + } + + // If FL is collapsed, expand it + if (acc.AccInfo.ServerVersion == ServerVersionEnum.TTwars || + flNode.Descendants("div").Any(x => x.HasClass("expandCollapse") && x.HasClass("collapsed"))) + { + await DriverHelper.ExecuteScript(acc, $"Travian.Game.RaidList.toggleList({this.FL.Id});"); + await Task.Delay(500); + acc.Wb.UpdateHtml(); + // Update flNode! + flNode = GetFlNode(acc.Wb.Html, acc.AccInfo.ServerVersion); + } + + var farms = new List(); + foreach (var farm in flNode.Descendants("tr").Where(x => x.HasClass("slotRow"))) + { + //iReport2 = yellow swords, iReport3 = red swords, iReport1 = successful raid + var img = farm.ChildNodes.FirstOrDefault(x => x.HasClass("lastRaid"))?.Descendants("img"); + + var coords = MapParser.GetPositionDetails(farm); + farms.Add(new GoldClubFarm(coords)); + + //there has to be an image (we already have a report) and wrong raid style to not check this farmlist: + if (img.Count() != 0 && ( //no image -> no recent attack + (img.FirstOrDefault(x => x.HasClass("iReport3")) != null && this.FL.RaidStyle != RaidStyle.RaidLost) //raid was lost and we don't have RaidLost raidstyle + || (img.FirstOrDefault(x => x.HasClass("iReport2")) != null && (this.FL.RaidStyle == RaidStyle.RaidSuccessful)) //some casualities, but we only attack on successful + )) + { + continue; + } + + var checkbox = farm.Descendants("input").FirstOrDefault(x => x.HasClass("markSlot")); + await DriverHelper.CheckById(acc, checkbox.Id, true, update: false); + } + this.FL.Farms = farms; + + await Task.Delay(AccountHelper.Delay(acc) * 2); + + switch (acc.AccInfo.ServerVersion) + { + case ServerVersionEnum.TTwars: + var sendFlScript = $"document.getElementById('{flNode.Id}').childNodes[1].submit()"; + acc.Wb.ExecuteScript(sendFlScript); + break; + + case ServerVersionEnum.T4_5: + var startRaid = flNode.Descendants("button").FirstOrDefault(x => x.HasClass("startButton")); + acc.Wb.Driver.FindElement(By.Id(startRaid.Id)).Click(); + break; + } + + acc.Logger.Information($"FarmList '{this.FL.Name}' was sent"); + await Task.Delay(1000); + return TaskRes.Executed; + } + + private HtmlNode GetFlNode(HtmlDocument htmlDoc, ServerVersionEnum version) + { + switch (version) + { + case ServerVersionEnum.TTwars: return htmlDoc.GetElementbyId("list" + this.FL.Id); + + case ServerVersionEnum.T4_5: return htmlDoc.GetElementbyId("raidList" + this.FL.Id); + default: return null; + } + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/SecondLevel/SendRaid.cs b/TbsCore/Tasks/Farm/SendRaid.cs similarity index 100% rename from TbsCore/Tasks/SecondLevel/SendRaid.cs rename to TbsCore/Tasks/Farm/SendRaid.cs diff --git a/TbsCore/Tasks/SecondLevel/SendReinforcementScouts.cs b/TbsCore/Tasks/Farm/SendReinforcementScouts.cs similarity index 100% rename from TbsCore/Tasks/SecondLevel/SendReinforcementScouts.cs rename to TbsCore/Tasks/Farm/SendReinforcementScouts.cs diff --git a/TbsCore/Tasks/LowLevel/SendTroops.cs b/TbsCore/Tasks/Farm/SendTroops.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/SendTroops.cs rename to TbsCore/Tasks/Farm/SendTroops.cs index fbaf5fb5b..323f7ddcd 100644 --- a/TbsCore/Tasks/LowLevel/SendTroops.cs +++ b/TbsCore/Tasks/Farm/SendTroops.cs @@ -1,118 +1,118 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.SendTroopsModels; -using TbsCore.Models.TroopsModels; -using TbsCore.Parsers; - -namespace TbsCore.Tasks.LowLevel -{ - public class SendTroops : BotTask - { - public TroopsSendModel TroopsMovement { get; set; } - - /// - /// Other tasks (like SendDeff) can extend this task and configure amount of troops to - /// send when getting amount of troops at home. If false is returned, bot won't proceed the attack - /// - public Func TroopsCallback { get; set; } - - /// - /// When the troops will arrive to the destination, is set after the bot sends the troops. - /// Used by other BotTasks that extend this task (like OasisFarming) - /// - public TimeSpan Arrival { get; private set; } - - /// - /// In case we don't have specified troops at home, send partial attack (as many troops as we have at home) - /// If false, bot will skip this task. - /// - public bool SendPartialAttack { get; set; } = false; - /// - /// Whether we want to embed coordinates into the url. This saves ~1 sec and it used when searching from the map / send troops clicked - /// - //public bool SetCoordsInUrl { get; set; } = false; // Currently it will navigate to coordinates only on TTwars - - public override async Task Execute(Account acc) - { - //if (acc.AccInfo.ServerVersion == Classificator.ServerVersionEnum.TTwars) SetCoordsInUrl = true; - - await NavigationHelper.ToRallyPoint(acc, Vill, - NavigationHelper.RallyPointTab.SendTroops, TroopsMovement.TargetCoordinates - //SetCoordsInUrl ? TroopsMovement.TargetCoordinates : null - ); - - var troopsArr = TroopsMovementParser.GetTroopsInRallyPoint(acc.Wb.Html); - var proceed = TroopsCallback?.Invoke(acc, new TroopsBase(troopsArr, acc.AccInfo.Tribe)); - if (!(proceed ?? true)) return TaskRes.Retry; - - // No troops selected to be sent from this village - if (this.TroopsMovement.Troops.Sum() == 0) return TaskRes.Executed; - - // Add number of troops to the input boxes - for (int i = 0; i < TroopsMovement.Troops.Length; i++) - { - if (TroopsMovement.Troops[i] == 0) continue; - if (troopsArr[i] < TroopsMovement.Troops[i]) - { - if (SendPartialAttack) - { - TroopsMovement.Troops[i] = troopsArr[i]; - } - else - { - acc.Logger.Warning($"Vill {this.Vill} didn't have enough troops to send! Skipping task"); - return TaskRes.Executed; - } - } - - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.TTwars: - await DriverHelper.WriteByName(acc, $"t{i + 1}", TroopsMovement.Troops[i]); - break; - - case Classificator.ServerVersionEnum.T4_5: - await DriverHelper.WriteByName(acc, $"troops[0][t{i + 1}]", TroopsMovement.Troops[i]); - break; - } - } - - // Select coordinates, if we haven't set them in the url already - await DriverHelper.WriteCoordinates(acc, TroopsMovement.TargetCoordinates); - - //Select type of troop sending - string script = $"Array.from(document.getElementsByName('c')).find(x=>x.value=={(int)TroopsMovement.MovementType}).checked=true;"; - await DriverHelper.ExecuteScript(acc, script); - - //Click on "Send" button - await DriverHelper.ClickById(acc, "btn_ok"); - - await Task.Delay(AccountHelper.Delay(acc)); - - // Select catapult targets - if (this.TroopsMovement.Target1 != Classificator.BuildingEnum.Site) - await DriverHelper.SelectIndexByName(acc, "ctar1", (int)this.TroopsMovement.Target1); - if (this.TroopsMovement.Target2 != Classificator.BuildingEnum.Site) - await DriverHelper.SelectIndexByName(acc, "ctar2", (int)this.TroopsMovement.Target2); - - // Scout type - if (this.TroopsMovement.ScoutType != ScoutEnum.None) - { - string scout = $"Array.from(document.getElementsByName('spy')).find(x=>x.value=={(int)TroopsMovement.ScoutType}).checked=true;"; - await DriverHelper.ExecuteScript(acc, scout); - } - - // Parse movement duration of the troops - this.Arrival = TroopsMovementParser.GetMovementDuration(acc.Wb.Html); - - //Click on "Send" button - await DriverHelper.ClickById(acc, "btn_ok"); - acc.Logger.Information($"Bot sent troops from village {Vill.Name} to {this.TroopsMovement.TargetCoordinates}"); - - return TaskRes.Executed; - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.SendTroopsModels; +using TbsCore.Models.TroopsModels; +using TbsCore.Parsers; + +namespace TbsCore.Tasks.LowLevel +{ + public class SendTroops : BotTask + { + public TroopsSendModel TroopsMovement { get; set; } + + /// + /// Other tasks (like SendDeff) can extend this task and configure amount of troops to + /// send when getting amount of troops at home. If false is returned, bot won't proceed the attack + /// + public Func TroopsCallback { get; set; } + + /// + /// When the troops will arrive to the destination, is set after the bot sends the troops. + /// Used by other BotTasks that extend this task (like OasisFarming) + /// + public TimeSpan Arrival { get; private set; } + + /// + /// In case we don't have specified troops at home, send partial attack (as many troops as we have at home) + /// If false, bot will skip this task. + /// + public bool SendPartialAttack { get; set; } = false; + /// + /// Whether we want to embed coordinates into the url. This saves ~1 sec and it used when searching from the map / send troops clicked + /// + //public bool SetCoordsInUrl { get; set; } = false; // Currently it will navigate to coordinates only on TTwars + + public override async Task Execute(Account acc) + { + //if (acc.AccInfo.ServerVersion == Classificator.ServerVersionEnum.TTwars) SetCoordsInUrl = true; + + await NavigationHelper.ToRallyPoint(acc, Vill, + NavigationHelper.RallyPointTab.SendTroops, TroopsMovement.TargetCoordinates + //SetCoordsInUrl ? TroopsMovement.TargetCoordinates : null + ); + + var troopsArr = TroopsMovementParser.GetTroopsInRallyPoint(acc.Wb.Html); + var proceed = TroopsCallback?.Invoke(acc, new TroopsBase(troopsArr, acc.AccInfo.Tribe)); + if (!(proceed ?? true)) return TaskRes.Retry; + + // No troops selected to be sent from this village + if (this.TroopsMovement.Troops.Sum() == 0) return TaskRes.Executed; + + // Add number of troops to the input boxes + for (int i = 0; i < TroopsMovement.Troops.Length; i++) + { + if (TroopsMovement.Troops[i] == 0) continue; + if (troopsArr[i] < TroopsMovement.Troops[i]) + { + if (SendPartialAttack) + { + TroopsMovement.Troops[i] = troopsArr[i]; + } + else + { + acc.Logger.Warning($"Vill {this.Vill} didn't have enough troops to send! Skipping task"); + return TaskRes.Executed; + } + } + + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.TTwars: + await DriverHelper.WriteByName(acc, $"t{i + 1}", TroopsMovement.Troops[i]); + break; + + case Classificator.ServerVersionEnum.T4_5: + await DriverHelper.WriteByName(acc, $"troops[0][t{i + 1}]", TroopsMovement.Troops[i]); + break; + } + } + + // Select coordinates, if we haven't set them in the url already + await DriverHelper.WriteCoordinates(acc, TroopsMovement.TargetCoordinates); + + //Select type of troop sending + string script = $"Array.from(document.getElementsByName('c')).find(x=>x.value=={(int)TroopsMovement.MovementType}).checked=true;"; + await DriverHelper.ExecuteScript(acc, script); + + //Click on "Send" button + await DriverHelper.ClickById(acc, "btn_ok"); + + await Task.Delay(AccountHelper.Delay(acc)); + + // Select catapult targets + if (this.TroopsMovement.Target1 != Classificator.BuildingEnum.Site) + await DriverHelper.SelectIndexByName(acc, "ctar1", (int)this.TroopsMovement.Target1); + if (this.TroopsMovement.Target2 != Classificator.BuildingEnum.Site) + await DriverHelper.SelectIndexByName(acc, "ctar2", (int)this.TroopsMovement.Target2); + + // Scout type + if (this.TroopsMovement.ScoutType != ScoutEnum.None) + { + string scout = $"Array.from(document.getElementsByName('spy')).find(x=>x.value=={(int)TroopsMovement.ScoutType}).checked=true;"; + await DriverHelper.ExecuteScript(acc, scout); + } + + // Parse movement duration of the troops + this.Arrival = TroopsMovementParser.GetMovementDuration(acc.Wb.Html); + + //Click on "Send" button + await DriverHelper.ClickById(acc, "btn_ok"); + acc.Logger.Information($"Bot sent troops from village {Vill.Name} to {this.TroopsMovement.TargetCoordinates}"); + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/SendWaves.cs b/TbsCore/Tasks/Farm/SendWaves.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/SendWaves.cs rename to TbsCore/Tasks/Farm/SendWaves.cs index 8d6065787..f60ecd429 100644 --- a/TbsCore/Tasks/LowLevel/SendWaves.cs +++ b/TbsCore/Tasks/Farm/SendWaves.cs @@ -1,244 +1,244 @@ -using RestSharp; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.NetworkInformation; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Models.SendTroopsModels; -using TbsCore.TravianData; -using TbsCore.Helpers; -using TbsCore.Parsers; - -namespace TbsCore.Tasks.LowLevel -{ - public class SendWaves : BotTask - { - public List SendWaveModels { get; set; } - - // Time difference between server and computer time - private TimeSpan timeDifference; - - private DateTime lastArriveAt; - private string[] hiddenFields = new string[] { "timestamp", "timestamp_checksum", "b", "currentDid", "mpvt_token" }; - - public override async Task Execute(Account acc) - { - await NavigationHelper.ToRallyPoint(acc, Vill, NavigationHelper.RallyPointTab.SendTroops); - - var wavesReady = new List(); - - // Get request time for getting more accurate attacks - Ping ping = new Ping(); - PingReply reply = ping.Send(IoHelperCore.UrlRemoveHttp(acc.AccInfo.ServerUrl)); - var reqTripMs = (int)(reply.RoundtripTime / 2); - - Random rnd = new Random(); - - // Prepare the waves - for (int i = 0; i < SendWaveModels.Count; i++) - { - await Task.Delay(rnd.Next(800, 1000)); - acc.Logger.Information($"Preparing {i + 1}. wave..."); - - // TODO: eliminate the need of this first request, will send a second on each wave - var htmlDoc1 = await HttpHelper.SendGetReqAsync(acc, "/build.php?tt=2&id=39"); - - var build = htmlDoc1.GetElementbyId("build"); - - var req = new RestRequest - { - Resource = "/build.php?tt=2&id=39", - Method = Method.Post, - }; - - req.AddParameter("dname", ""); - req.AddParameter("x", SendWaveModels[i].TargetCoordinates.x.ToString()); - req.AddParameter("y", SendWaveModels[i].TargetCoordinates.y.ToString()); - req.AddParameter("c", ((int)SendWaveModels[i].MovementType).ToString()); - req.AddParameter("s1", "ok"); - - foreach (var hidden in hiddenFields) - { - var value = build.Descendants("input").FirstOrDefault(x => x.GetAttributeValue("name", "") == hidden); - if (value == null) continue; - req.AddParameter(hidden, value.GetAttributeValue("value", "")); - } - - // Get available troops - int[] troopsAtHome = TroopsMovementParser.GetTroopsInRallyPoint(htmlDoc1); - - // Send fake attack dirty hack - if (SendWaveModels[i].FakeAttack) - { - for (int j = 0; j < 10; j++) - { - if (troopsAtHome[j] > 19) - { - SendWaveModels[i].Troops[j] = 19; - troopsAtHome[j] -= 19; - break; - } - } - } - - for (int j = 0; j < SendWaveModels[i].Troops.Length; j++) - { - // If negative value, send all available units - if (SendWaveModels[i].Troops[j] < 0) - { - SendWaveModels[i].Troops[j] = troopsAtHome[j]; - troopsAtHome[j] = 0; - } - - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.TTwars: - req.AddParameter($"t{j + 1}", TroopCount(SendWaveModels[i].Troops[j])); - break; - - case Classificator.ServerVersionEnum.T4_5: - req.AddParameter($"troops[0][t{j + 1}]", TroopCount(SendWaveModels[i].Troops[j])); - break; - } - } - await Task.Delay(rnd.Next(800, 1000)); - - var ret = await HttpHelper.SendPostReqAsync(acc, req); - - var htmlDoc2 = new HtmlAgilityPack.HtmlDocument(); - htmlDoc2.LoadHtml(ret); - - // Get time it takes for troops to the target, for later usage - var timespan = TroopsMovementParser.GetMovementDuration(htmlDoc2); - lastArriveAt = TroopsMovementParser.GetArrivalTime(htmlDoc2); - - if (timeDifference == TimeSpan.Zero) - { - var serverTime = TimeParser.GetServerTime(htmlDoc2); - timeDifference = DateTime.Now - serverTime; - // Negate seconds and milliseconds in time difference. - var negateMillis = timeDifference.Milliseconds; - negateMillis += timeDifference.Seconds * 1000; - timeDifference = timeDifference.Subtract(new TimeSpan(0, 0, 0, 0, negateMillis)); - - var executeTime = CorrectExecuteTime(timespan); - if (DateTime.Now.AddMinutes(1) < executeTime) - { - // Restart this task at the correct time - acc.Logger.Information($"Bot will send waves in {TimeHelper.InSeconds(executeTime)} seconds"); - this.NextExecute = executeTime; - return TaskRes.Executed; - } - } - - //var ajaxToken = await HttpHelper.GetAjaxToken(wb); - var req2 = new RestRequest - { - Resource = "/build.php?tt=2&id=39", - Method = Method.Post, - }; - - req2.AddParameter("s1", "ok"); - - // Copy all hidden names and values - var build2 = htmlDoc2.GetElementbyId("build"); - var hiddens2 = build2.Descendants("input").Where(x => x.GetAttributeValue("type", "") == "hidden"); - foreach (var hidden2 in hiddens2) - { - var val = hidden2.GetAttributeValue("value", ""); - var name = hidden2.GetAttributeValue("name", ""); - req2.AddParameter(name, val); - } - - // Add catapult targets - string cataCount = "0"; - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.TTwars: - cataCount = req2.Parameters.FirstOrDefault(x => x.Name == "t8").Value.ToString(); - break; - - case Classificator.ServerVersionEnum.T4_5: - cataCount = req2.Parameters.FirstOrDefault(x => x.Name == "troops[0][t8]").Value.ToString(); - // If T4.5, we need to get value "a" as well - From Confirm button - var button = htmlDoc2.GetElementbyId("btn_ok"); - string a = button.GetAttributeValue("value", ""); - req2.AddParameter("a", a); - break; - } - - if (int.Parse(cataCount) > 0) - { - req2.AddParameter("ctar1", "99"); // 99 = Random, 1 = woodcuter, 2 = claypit.. - req2.AddParameter("ctar2", "99"); // 99 = Random - } - - wavesReady.Add(new WaveReadyModel - { - Request = req2, - MovementTime = timespan - }); - } - - var waitMs = 1000 - DateTime.Now.Millisecond - reqTripMs; - if (waitMs < 0) waitMs += 1000; - var wait = new TimeSpan(0, 0, 0, 0, waitMs); - - // Calculate how much you need to wait so waves arrive at the correct time! - var targetArrival = SendWaveModels.FirstOrDefault(x => x.Arrival != DateTime.MinValue).Arrival; - TimeSpan waitForTarget = (targetArrival - lastArriveAt); - if (waitForTarget > TimeSpan.Zero) - { - var waitForTargetSec = (int)waitForTarget.TotalSeconds - 1; // -1 to compensate - var waitForTargetTimeSpan = new TimeSpan(0, 0, waitForTargetSec); - wait = wait.Add(waitForTargetTimeSpan); - } - await Task.Delay(wait); - - // Send the waves - DateTime lastSent = default; - for (int i = 0; i < wavesReady.Count; i++) - { - lastSent = DateTime.Now; - acc.Logger.Information($"{DateTime.Now.Second}.{DateTime.Now.Millisecond}] Sending wave {i + 1}"); - _ = HttpHelper.SendPostReqAsync(acc, wavesReady[i].Request); - - // Wait +- 10% selected delay - var delay = SendWaveModels[i].DelayMs; - - // Negate the time it took to send the request - delay -= (int)(DateTime.Now - lastSent).TotalMilliseconds; - Console.WriteLine("New Delay " + delay); - - //var delay10Percent = (int)delay / 100; - //await Task.Delay(rnd.Next(delay - delay10Percent, delay + delay10Percent)); - if (0 < delay) await Task.Delay(delay); - } - acc.Logger.Information($"Successfully sent {wavesReady.Count} waves!"); - - await Task.Delay(AccountHelper.Delay(acc) * 2); - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?gid=16&tt=1&filter=2&subfilters=4"); - //Todo: check waves? - return TaskRes.Executed; - } - - private string TroopCount(int v) - { - if (v == 0) return ""; - return v.ToString(); - } - - private DateTime CorrectExecuteTime(TimeSpan troopTime) - { - var sec = 10; // Base value - sec += 2 * this.SendWaveModels.Count(); // + 4 sec for each wave - var targetArrival = SendWaveModels.FirstOrDefault(x => x.Arrival != DateTime.MinValue).Arrival; - - DateTime executeAt = targetArrival.Add(timeDifference); - executeAt = executeAt.Subtract(troopTime); - executeAt = executeAt.AddSeconds(-sec); - return executeAt; - } - } +using RestSharp; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net.NetworkInformation; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Models.SendTroopsModels; +using TbsCore.TravianData; +using TbsCore.Helpers; +using TbsCore.Parsers; + +namespace TbsCore.Tasks.LowLevel +{ + public class SendWaves : BotTask + { + public List SendWaveModels { get; set; } + + // Time difference between server and computer time + private TimeSpan timeDifference; + + private DateTime lastArriveAt; + private string[] hiddenFields = new string[] { "timestamp", "timestamp_checksum", "b", "currentDid", "mpvt_token" }; + + public override async Task Execute(Account acc) + { + await NavigationHelper.ToRallyPoint(acc, Vill, NavigationHelper.RallyPointTab.SendTroops); + + var wavesReady = new List(); + + // Get request time for getting more accurate attacks + Ping ping = new Ping(); + PingReply reply = ping.Send(IoHelperCore.UrlRemoveHttp(acc.AccInfo.ServerUrl)); + var reqTripMs = (int)(reply.RoundtripTime / 2); + + Random rnd = new Random(); + + // Prepare the waves + for (int i = 0; i < SendWaveModels.Count; i++) + { + await Task.Delay(rnd.Next(800, 1000)); + acc.Logger.Information($"Preparing {i + 1}. wave..."); + + // TODO: eliminate the need of this first request, will send a second on each wave + var htmlDoc1 = await HttpHelper.SendGetReqAsync(acc, "/build.php?tt=2&id=39"); + + var build = htmlDoc1.GetElementbyId("build"); + + var req = new RestRequest + { + Resource = "/build.php?tt=2&id=39", + Method = Method.Post, + }; + + req.AddParameter("dname", ""); + req.AddParameter("x", SendWaveModels[i].TargetCoordinates.x.ToString()); + req.AddParameter("y", SendWaveModels[i].TargetCoordinates.y.ToString()); + req.AddParameter("c", ((int)SendWaveModels[i].MovementType).ToString()); + req.AddParameter("s1", "ok"); + + foreach (var hidden in hiddenFields) + { + var value = build.Descendants("input").FirstOrDefault(x => x.GetAttributeValue("name", "") == hidden); + if (value == null) continue; + req.AddParameter(hidden, value.GetAttributeValue("value", "")); + } + + // Get available troops + int[] troopsAtHome = TroopsMovementParser.GetTroopsInRallyPoint(htmlDoc1); + + // Send fake attack dirty hack + if (SendWaveModels[i].FakeAttack) + { + for (int j = 0; j < 10; j++) + { + if (troopsAtHome[j] > 19) + { + SendWaveModels[i].Troops[j] = 19; + troopsAtHome[j] -= 19; + break; + } + } + } + + for (int j = 0; j < SendWaveModels[i].Troops.Length; j++) + { + // If negative value, send all available units + if (SendWaveModels[i].Troops[j] < 0) + { + SendWaveModels[i].Troops[j] = troopsAtHome[j]; + troopsAtHome[j] = 0; + } + + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.TTwars: + req.AddParameter($"t{j + 1}", TroopCount(SendWaveModels[i].Troops[j])); + break; + + case Classificator.ServerVersionEnum.T4_5: + req.AddParameter($"troops[0][t{j + 1}]", TroopCount(SendWaveModels[i].Troops[j])); + break; + } + } + await Task.Delay(rnd.Next(800, 1000)); + + var ret = await HttpHelper.SendPostReqAsync(acc, req); + + var htmlDoc2 = new HtmlAgilityPack.HtmlDocument(); + htmlDoc2.LoadHtml(ret); + + // Get time it takes for troops to the target, for later usage + var timespan = TroopsMovementParser.GetMovementDuration(htmlDoc2); + lastArriveAt = TroopsMovementParser.GetArrivalTime(htmlDoc2); + + if (timeDifference == TimeSpan.Zero) + { + var serverTime = TimeParser.GetServerTime(htmlDoc2); + timeDifference = DateTime.Now - serverTime; + // Negate seconds and milliseconds in time difference. + var negateMillis = timeDifference.Milliseconds; + negateMillis += timeDifference.Seconds * 1000; + timeDifference = timeDifference.Subtract(new TimeSpan(0, 0, 0, 0, negateMillis)); + + var executeTime = CorrectExecuteTime(timespan); + if (DateTime.Now.AddMinutes(1) < executeTime) + { + // Restart this task at the correct time + acc.Logger.Information($"Bot will send waves in {TimeHelper.InSeconds(executeTime)} seconds"); + this.NextExecute = executeTime; + return TaskRes.Executed; + } + } + + //var ajaxToken = await HttpHelper.GetAjaxToken(wb); + var req2 = new RestRequest + { + Resource = "/build.php?tt=2&id=39", + Method = Method.Post, + }; + + req2.AddParameter("s1", "ok"); + + // Copy all hidden names and values + var build2 = htmlDoc2.GetElementbyId("build"); + var hiddens2 = build2.Descendants("input").Where(x => x.GetAttributeValue("type", "") == "hidden"); + foreach (var hidden2 in hiddens2) + { + var val = hidden2.GetAttributeValue("value", ""); + var name = hidden2.GetAttributeValue("name", ""); + req2.AddParameter(name, val); + } + + // Add catapult targets + string cataCount = "0"; + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.TTwars: + cataCount = req2.Parameters.FirstOrDefault(x => x.Name == "t8").Value.ToString(); + break; + + case Classificator.ServerVersionEnum.T4_5: + cataCount = req2.Parameters.FirstOrDefault(x => x.Name == "troops[0][t8]").Value.ToString(); + // If T4.5, we need to get value "a" as well - From Confirm button + var button = htmlDoc2.GetElementbyId("btn_ok"); + string a = button.GetAttributeValue("value", ""); + req2.AddParameter("a", a); + break; + } + + if (int.Parse(cataCount) > 0) + { + req2.AddParameter("ctar1", "99"); // 99 = Random, 1 = woodcuter, 2 = claypit.. + req2.AddParameter("ctar2", "99"); // 99 = Random + } + + wavesReady.Add(new WaveReadyModel + { + Request = req2, + MovementTime = timespan + }); + } + + var waitMs = 1000 - DateTime.Now.Millisecond - reqTripMs; + if (waitMs < 0) waitMs += 1000; + var wait = new TimeSpan(0, 0, 0, 0, waitMs); + + // Calculate how much you need to wait so waves arrive at the correct time! + var targetArrival = SendWaveModels.FirstOrDefault(x => x.Arrival != DateTime.MinValue).Arrival; + TimeSpan waitForTarget = (targetArrival - lastArriveAt); + if (waitForTarget > TimeSpan.Zero) + { + var waitForTargetSec = (int)waitForTarget.TotalSeconds - 1; // -1 to compensate + var waitForTargetTimeSpan = new TimeSpan(0, 0, waitForTargetSec); + wait = wait.Add(waitForTargetTimeSpan); + } + await Task.Delay(wait); + + // Send the waves + DateTime lastSent = default; + for (int i = 0; i < wavesReady.Count; i++) + { + lastSent = DateTime.Now; + acc.Logger.Information($"{DateTime.Now.Second}.{DateTime.Now.Millisecond}] Sending wave {i + 1}"); + _ = HttpHelper.SendPostReqAsync(acc, wavesReady[i].Request); + + // Wait +- 10% selected delay + var delay = SendWaveModels[i].DelayMs; + + // Negate the time it took to send the request + delay -= (int)(DateTime.Now - lastSent).TotalMilliseconds; + Console.WriteLine("New Delay " + delay); + + //var delay10Percent = (int)delay / 100; + //await Task.Delay(rnd.Next(delay - delay10Percent, delay + delay10Percent)); + if (0 < delay) await Task.Delay(delay); + } + acc.Logger.Information($"Successfully sent {wavesReady.Count} waves!"); + + await Task.Delay(AccountHelper.Delay(acc) * 2); + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?gid=16&tt=1&filter=2&subfilters=4"); + //Todo: check waves? + return TaskRes.Executed; + } + + private string TroopCount(int v) + { + if (v == 0) return ""; + return v.ToString(); + } + + private DateTime CorrectExecuteTime(TimeSpan troopTime) + { + var sec = 10; // Base value + sec += 2 * this.SendWaveModels.Count(); // + 4 sec for each wave + var targetArrival = SendWaveModels.FirstOrDefault(x => x.Arrival != DateTime.MinValue).Arrival; + + DateTime executeAt = targetArrival.Add(timeDifference); + executeAt = executeAt.Subtract(troopTime); + executeAt = executeAt.AddSeconds(-sec); + return executeAt; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/SecondLevel/TTWarsAddNatarsToFL.cs b/TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs similarity index 97% rename from TbsCore/Tasks/SecondLevel/TTWarsAddNatarsToFL.cs rename to TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs index a10192174..1d6b6b2fd 100644 --- a/TbsCore/Tasks/SecondLevel/TTWarsAddNatarsToFL.cs +++ b/TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs @@ -1,55 +1,55 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Models.MapModels; -using TbsCore.Models.TroopsModels; -using TbsCore.Helpers; -using TbsCore.Parsers; -using TbsCore.Tasks.LowLevel; - -namespace TbsCore.Tasks.SecondLevel -{ - public class TTWarsAddNatarsToFL : CheckProfile - { - public int MinPop { get; set; } = 1; - public int MaxPop { get; set; } = 9999; - public FarmList FL { get; set; } - - public override async Task Execute(Account acc) - { - base.UserId = 1; - await base.Execute(acc); - - int addedFarms = 0; - base.Profile.Villages = base.Profile.Villages - .OrderBy(x => x.Coordinates.CalculateDistance(acc, this.Vill.Coordinates)) - //.Where(vill => !acc.Farming.FL.Any(x => x.Farms.Any(farm => farm.Coordinates.Equals(vill.Coordinates)))) - .ToList(); - foreach (var vill in base.Profile.Villages) - { - // If this farm already exists on some FL - if (acc.Farming.FL.Any(x => x.Farms.Any(farm => farm.Coordinates.Equals(vill.Coordinates)))) continue; - - if (MinPop < vill.Population && vill.Population < MaxPop) - { - acc.Tasks.Add(new AddFarm() - { - ExecuteAt = DateTime.Now.AddHours(-1), - Farm = new Models.VillageModels.Farm() - { - Troops = new int[] { 100 }, - Coords = vill.Coordinates, - }, - FarmListId = this.FL.Id, - }); - - addedFarms++; - if (FL.NumOfFarms + addedFarms >= 100) break; //no more slots FL slots! - } - } - return TaskRes.Executed; - } - } +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Models.MapModels; +using TbsCore.Models.TroopsModels; +using TbsCore.Helpers; +using TbsCore.Parsers; +using TbsCore.Tasks.LowLevel; + +namespace TbsCore.Tasks.SecondLevel +{ + public class TTWarsAddNatarsToFL : CheckProfile + { + public int MinPop { get; set; } = 1; + public int MaxPop { get; set; } = 9999; + public FarmList FL { get; set; } + + public override async Task Execute(Account acc) + { + base.UserId = 1; + await base.Execute(acc); + + int addedFarms = 0; + base.Profile.Villages = base.Profile.Villages + .OrderBy(x => x.Coordinates.CalculateDistance(acc, this.Vill.Coordinates)) + //.Where(vill => !acc.Farming.FL.Any(x => x.Farms.Any(farm => farm.Coordinates.Equals(vill.Coordinates)))) + .ToList(); + foreach (var vill in base.Profile.Villages) + { + // If this farm already exists on some FL + if (acc.Farming.FL.Any(x => x.Farms.Any(farm => farm.Coordinates.Equals(vill.Coordinates)))) continue; + + if (MinPop < vill.Population && vill.Population < MaxPop) + { + acc.Tasks.Add(new AddFarm() + { + ExecuteAt = DateTime.Now.AddHours(-1), + Farm = new Models.VillageModels.Farm() + { + Troops = new int[] { 100 }, + Coords = vill.Coordinates, + }, + FarmListId = this.FL.Id, + }); + + addedFarms++; + if (FL.NumOfFarms + addedFarms >= 100) break; //no more slots FL slots! + } + } + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/SecondLevel/TTWarsAddNatarsToNonGoldFL.cs b/TbsCore/Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs similarity index 100% rename from TbsCore/Tasks/SecondLevel/TTWarsAddNatarsToNonGoldFL.cs rename to TbsCore/Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs diff --git a/TbsCore/Tasks/LowLevel/TrainExchangeRes.cs b/TbsCore/Tasks/Farm/TrainExchangeRes.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/TrainExchangeRes.cs rename to TbsCore/Tasks/Farm/TrainExchangeRes.cs index aed252a80..3272183fa 100644 --- a/TbsCore/Tasks/LowLevel/TrainExchangeRes.cs +++ b/TbsCore/Tasks/Farm/TrainExchangeRes.cs @@ -1,39 +1,39 @@ -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.TravianData; - -namespace TbsCore.Tasks.LowLevel -{ - public class TrainExchangeRes : BotTask - { - public bool Great { get; set; } - public Classificator.TroopsEnum troop { get; set; } - - public override async Task Execute(Account acc) - { - if (Vill == null) Vill = AccountHelper.GetMainVillage(acc); - - var building = TroopsData.GetTroopBuilding(troop, Great); - if (!await NavigationHelper.EnterBuilding(acc, Vill, building)) - return TaskRes.Executed; - - var troopNode = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("u" + (int)troop)); - while (!troopNode.HasClass("details")) troopNode = troopNode.ParentNode; - - //finding the correct "Exchange resources" button - var exchangeResButton = troopNode.Descendants("button").FirstOrDefault(x => x.HasClass("gold")); - await DriverHelper.ClickById(acc, exchangeResButton.Id); - - var distribute = acc.Wb.Html.DocumentNode.SelectNodes("//*[text()[contains(., 'Distribute remaining resources.')]]")[0]; - while (distribute.Name != "button") distribute = distribute.ParentNode; - await DriverHelper.ClickById(acc, distribute.Id); - - await Task.Delay(AccountHelper.Delay(acc)); - await DriverHelper.ClickById(acc, "npc_market_button"); - - return TaskRes.Executed; - } - } +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.TravianData; + +namespace TbsCore.Tasks.LowLevel +{ + public class TrainExchangeRes : BotTask + { + public bool Great { get; set; } + public Classificator.TroopsEnum troop { get; set; } + + public override async Task Execute(Account acc) + { + if (Vill == null) Vill = AccountHelper.GetMainVillage(acc); + + var building = TroopsData.GetTroopBuilding(troop, Great); + if (!await NavigationHelper.EnterBuilding(acc, Vill, building)) + return TaskRes.Executed; + + var troopNode = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("u" + (int)troop)); + while (!troopNode.HasClass("details")) troopNode = troopNode.ParentNode; + + //finding the correct "Exchange resources" button + var exchangeResButton = troopNode.Descendants("button").FirstOrDefault(x => x.HasClass("gold")); + await DriverHelper.ClickById(acc, exchangeResButton.Id); + + var distribute = acc.Wb.Html.DocumentNode.SelectNodes("//*[text()[contains(., 'Distribute remaining resources.')]]")[0]; + while (distribute.Name != "button") distribute = distribute.ParentNode; + await DriverHelper.ClickById(acc, distribute.Id); + + await Task.Delay(AccountHelper.Delay(acc)); + await DriverHelper.ClickById(acc, "npc_market_button"); + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/TrainTroops.cs b/TbsCore/Tasks/Farm/TrainTroops.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/TrainTroops.cs rename to TbsCore/Tasks/Farm/TrainTroops.cs index 322724efc..d4122bff7 100644 --- a/TbsCore/Tasks/LowLevel/TrainTroops.cs +++ b/TbsCore/Tasks/Farm/TrainTroops.cs @@ -1,205 +1,205 @@ -using HtmlAgilityPack; -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.ResourceModels; -using TbsCore.Parsers; -using TbsCore.TravianData; - -using static TbsCore.Helpers.Classificator; - -namespace TbsCore.Tasks.LowLevel -{ - /// - /// Old train troops task, only here because of high speed TTWars servers. - /// - public class TrainTroops : BotTask - { - /// - /// Great barracks/stable? - /// - public bool Great { get; set; } - - /// - /// Which troop we want to train - /// - public TroopsEnum Troop { get; set; } - - /// - /// If true, will just check CurrentlyTraining and Researched. - /// - public bool UpdateOnly { get; set; } - - /// - /// If we play on UNL/VIP, don't repeat this cycle; this tasks gets called every time after FL/buying res - /// - public bool HighSpeedServer { get; set; } - - private BuildingEnum building; - - public override async Task Execute(Account acc) - { - building = TroopsData.GetTroopBuilding(Troop, Great); - - // Switch hero helmet. If hero will be switched, this TrainTroops task - // will be executed right after the hero helmet switch - if (HeroHelper.SwitchHelmet(acc, this.Vill, building, this)) return TaskRes.Executed; - - if (!await NavigationHelper.EnterBuilding(acc, Vill, building)) - return TaskRes.Executed; - - if (this.UpdateOnly || this.Troop == TroopsEnum.None) - { - return TaskRes.Executed; - } - - (TimeSpan dur, Resources cost) = TroopsParser.GetTrainCost(acc.Wb.Html, this.Troop); - - var troopNode = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("u" + (int)Troop)); - - if (troopNode == null) - { - acc.Logger.Warning($"Bot tried to train {Troop} in {Vill.Name}, but couldn't find it in {building}! Are you sure you have {Troop} researched?"); - return TaskRes.Executed; - } - while (!troopNode.HasClass("details")) troopNode = troopNode.ParentNode; - var inputName = troopNode.Descendants("input").FirstOrDefault().GetAttributeValue("name", ""); - - long maxNum = 0; - switch (acc.AccInfo.ServerVersion) - { - case ServerVersionEnum.TTwars: - maxNum = Parser.RemoveNonNumeric( - troopNode.ChildNodes - .FirstOrDefault(x => x.Name == "a")?.InnerText ?? "0" - ); - break; - - case ServerVersionEnum.T4_5: - maxNum = Parser.RemoveNonNumeric( - troopNode.ChildNodes - .First(x => x.HasClass("cta")) - .ChildNodes - .First(x => x.Name == "a") - .InnerText); - break; - } - - if (!HighSpeedServer) - { - var trainNum = TroopsHelper.TroopsToFill(acc, Vill, this.Troop, this.Great); - - // Don't train too many troops, just fill up the training building - if (maxNum > trainNum) maxNum = trainNum; - } - - if (maxNum < 0) - { - // We have already enough troops in training. - return TaskRes.Executed; - } - - acc.Wb.ExecuteScript($"document.getElementsByName('{inputName}')[0].value='{maxNum}'"); - - await Task.Delay(100); - - await DriverHelper.ExecuteScript(acc, "document.getElementsByName('s1')[0].click()"); - UpdateCurrentlyTraining(acc.Wb.Html, acc); - - if (!HighSpeedServer) RepeatTrainingCycle(acc.Wb.Html, acc); - - return TaskRes.Executed; - } - - public void UpdateCurrentlyTraining(HtmlDocument htmlDoc, Account acc) - { - var ct = TroopsParser.GetTroopsCurrentlyTraining(htmlDoc); - switch (building) - { - case Classificator.BuildingEnum.Barracks: - Vill.Troops.CurrentlyTraining.Barracks = ct; - break; - - case Classificator.BuildingEnum.Stable: - Vill.Troops.CurrentlyTraining.Stable = ct; - break; - - case Classificator.BuildingEnum.GreatBarracks: - Vill.Troops.CurrentlyTraining.GB = ct; - break; - - case Classificator.BuildingEnum.GreatStable: - Vill.Troops.CurrentlyTraining.GS = ct; - break; - - case Classificator.BuildingEnum.Workshop: - Vill.Troops.CurrentlyTraining.Workshop = ct; - break; - } - } - - /// - /// Repeats sending resources and training troops. Needs to fill up training above X hours. - /// - /// html of the page - /// Account - public void RepeatTrainingCycle(HtmlDocument htmlDoc, Account acc) - { - var trainingEnds = TroopsHelper.GetTrainingTimeForBuilding(building, Vill); - - // If sendRes is activated and there are some resources left to send - if (Vill.Settings.SendRes && 0 < MarketHelper.GetResToMainVillage(this.Vill).Sum()) - { - // Check If all troops are filled in this vill before sending resources back to main village - if (TroopsHelper.EverythingFilled(acc, Vill) && AccountHelper.GetMainVillage(acc) != this.Vill) - { - acc.Tasks.Add(new SendResToMain() { Vill = this.Vill, ExecuteAt = DateTime.MinValue.AddHours(1) }); - } - } - - var mainVill = AccountHelper.GetMainVillage(acc); - if (Vill.Settings.GetRes && mainVill != this.Vill) - { - var nextCycle = trainingEnds.AddHours(-acc.Settings.FillInAdvance); - - if (nextCycle < Vill.Market.LastTransit.AddMinutes(5)) - nextCycle = Vill.Market.LastTransit.AddMinutes(5); - - if (nextCycle < DateTime.Now) - { - // Send resources asap. - nextCycle = DateTime.MinValue.AddHours(3); - } - else - { - acc.Tasks.Add(new UpdateDorf1() - { - ExecuteAt = nextCycle, - Vill = this.Vill - }); - } - - acc.Tasks.Add(new SendResFillTroops() - { - ExecuteAt = nextCycle.AddMilliseconds(1), - Vill = mainVill, - TargetVill = this.Vill, - TrainTask = this - }); - this.NextExecute = nextCycle.AddMinutes(30); //will get overwritten in sendResFillTroops - acc.Tasks.ReOrder(); - } - else - { - var subtractMillis = AccountHelper.Delay(acc) * 50; //~30sec - var later = DateTime.Now.AddMinutes(10); - // Don't training again sooner than after 10min - if (later > trainingEnds) trainingEnds = later; - - this.NextExecute = trainingEnds.AddMilliseconds(-subtractMillis); - } - } - } +using HtmlAgilityPack; +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.ResourceModels; +using TbsCore.Parsers; +using TbsCore.TravianData; + +using static TbsCore.Helpers.Classificator; + +namespace TbsCore.Tasks.LowLevel +{ + /// + /// Old train troops task, only here because of high speed TTWars servers. + /// + public class TrainTroops : BotTask + { + /// + /// Great barracks/stable? + /// + public bool Great { get; set; } + + /// + /// Which troop we want to train + /// + public TroopsEnum Troop { get; set; } + + /// + /// If true, will just check CurrentlyTraining and Researched. + /// + public bool UpdateOnly { get; set; } + + /// + /// If we play on UNL/VIP, don't repeat this cycle; this tasks gets called every time after FL/buying res + /// + public bool HighSpeedServer { get; set; } + + private BuildingEnum building; + + public override async Task Execute(Account acc) + { + building = TroopsData.GetTroopBuilding(Troop, Great); + + // Switch hero helmet. If hero will be switched, this TrainTroops task + // will be executed right after the hero helmet switch + if (HeroHelper.SwitchHelmet(acc, this.Vill, building, this)) return TaskRes.Executed; + + if (!await NavigationHelper.EnterBuilding(acc, Vill, building)) + return TaskRes.Executed; + + if (this.UpdateOnly || this.Troop == TroopsEnum.None) + { + return TaskRes.Executed; + } + + (TimeSpan dur, Resources cost) = TroopsParser.GetTrainCost(acc.Wb.Html, this.Troop); + + var troopNode = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("u" + (int)Troop)); + + if (troopNode == null) + { + acc.Logger.Warning($"Bot tried to train {Troop} in {Vill.Name}, but couldn't find it in {building}! Are you sure you have {Troop} researched?"); + return TaskRes.Executed; + } + while (!troopNode.HasClass("details")) troopNode = troopNode.ParentNode; + var inputName = troopNode.Descendants("input").FirstOrDefault().GetAttributeValue("name", ""); + + long maxNum = 0; + switch (acc.AccInfo.ServerVersion) + { + case ServerVersionEnum.TTwars: + maxNum = Parser.RemoveNonNumeric( + troopNode.ChildNodes + .FirstOrDefault(x => x.Name == "a")?.InnerText ?? "0" + ); + break; + + case ServerVersionEnum.T4_5: + maxNum = Parser.RemoveNonNumeric( + troopNode.ChildNodes + .First(x => x.HasClass("cta")) + .ChildNodes + .First(x => x.Name == "a") + .InnerText); + break; + } + + if (!HighSpeedServer) + { + var trainNum = TroopsHelper.TroopsToFill(acc, Vill, this.Troop, this.Great); + + // Don't train too many troops, just fill up the training building + if (maxNum > trainNum) maxNum = trainNum; + } + + if (maxNum < 0) + { + // We have already enough troops in training. + return TaskRes.Executed; + } + + acc.Wb.ExecuteScript($"document.getElementsByName('{inputName}')[0].value='{maxNum}'"); + + await Task.Delay(100); + + await DriverHelper.ExecuteScript(acc, "document.getElementsByName('s1')[0].click()"); + UpdateCurrentlyTraining(acc.Wb.Html, acc); + + if (!HighSpeedServer) RepeatTrainingCycle(acc.Wb.Html, acc); + + return TaskRes.Executed; + } + + public void UpdateCurrentlyTraining(HtmlDocument htmlDoc, Account acc) + { + var ct = TroopsParser.GetTroopsCurrentlyTraining(htmlDoc); + switch (building) + { + case Classificator.BuildingEnum.Barracks: + Vill.Troops.CurrentlyTraining.Barracks = ct; + break; + + case Classificator.BuildingEnum.Stable: + Vill.Troops.CurrentlyTraining.Stable = ct; + break; + + case Classificator.BuildingEnum.GreatBarracks: + Vill.Troops.CurrentlyTraining.GB = ct; + break; + + case Classificator.BuildingEnum.GreatStable: + Vill.Troops.CurrentlyTraining.GS = ct; + break; + + case Classificator.BuildingEnum.Workshop: + Vill.Troops.CurrentlyTraining.Workshop = ct; + break; + } + } + + /// + /// Repeats sending resources and training troops. Needs to fill up training above X hours. + /// + /// html of the page + /// Account + public void RepeatTrainingCycle(HtmlDocument htmlDoc, Account acc) + { + var trainingEnds = TroopsHelper.GetTrainingTimeForBuilding(building, Vill); + + // If sendRes is activated and there are some resources left to send + if (Vill.Settings.SendRes && 0 < MarketHelper.GetResToMainVillage(this.Vill).Sum()) + { + // Check If all troops are filled in this vill before sending resources back to main village + if (TroopsHelper.EverythingFilled(acc, Vill) && AccountHelper.GetMainVillage(acc) != this.Vill) + { + acc.Tasks.Add(new SendResToMain() { Vill = this.Vill, ExecuteAt = DateTime.MinValue.AddHours(1) }); + } + } + + var mainVill = AccountHelper.GetMainVillage(acc); + if (Vill.Settings.GetRes && mainVill != this.Vill) + { + var nextCycle = trainingEnds.AddHours(-acc.Settings.FillInAdvance); + + if (nextCycle < Vill.Market.LastTransit.AddMinutes(5)) + nextCycle = Vill.Market.LastTransit.AddMinutes(5); + + if (nextCycle < DateTime.Now) + { + // Send resources asap. + nextCycle = DateTime.MinValue.AddHours(3); + } + else + { + acc.Tasks.Add(new UpdateDorf1() + { + ExecuteAt = nextCycle, + Vill = this.Vill + }); + } + + acc.Tasks.Add(new SendResFillTroops() + { + ExecuteAt = nextCycle.AddMilliseconds(1), + Vill = mainVill, + TargetVill = this.Vill, + TrainTask = this + }); + this.NextExecute = nextCycle.AddMinutes(30); //will get overwritten in sendResFillTroops + acc.Tasks.ReOrder(); + } + else + { + var subtractMillis = AccountHelper.Delay(acc) * 50; //~30sec + var later = DateTime.Now.AddMinutes(10); + // Don't training again sooner than after 10min + if (later > trainingEnds) trainingEnds = later; + + this.NextExecute = trainingEnds.AddMilliseconds(-subtractMillis); + } + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/SecondLevel/TransitToMainAcc.cs b/TbsCore/Tasks/Farm/TransitToMainAcc.cs similarity index 96% rename from TbsCore/Tasks/SecondLevel/TransitToMainAcc.cs rename to TbsCore/Tasks/Farm/TransitToMainAcc.cs index ae5c855d1..4c762b134 100644 --- a/TbsCore/Tasks/SecondLevel/TransitToMainAcc.cs +++ b/TbsCore/Tasks/Farm/TransitToMainAcc.cs @@ -1,35 +1,35 @@ -using System; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Models.MapModels; -using TbsCore.Helpers; - -namespace TbsCore.Tasks.LowLevel -{ - /// - /// Used on TTWars to constantly send resources to your main account - /// - public class TransitToMainAcc : BotTask - { - public Coordinates coords; - public int delay; - - public override async Task Execute(Account acc) - { - acc.Tasks.Add(new TransitToMainAcc - { - coords = this.coords, - delay = this.delay, - ExecuteAt = DateTime.Now.AddSeconds(delay), - Vill = this.Vill - }, true); - - await Task.Delay(AccountHelper.Delay(acc)); - - //Resources res = new Resources() { Wood = 50000000, Clay = 50000000, Iron = 50000000, Crop = 50000000 }; - acc.Tasks.Add(new SendResources() { ExecuteAt = DateTime.Now, Coordinates = coords, Vill = this.Vill }); - - return TaskRes.Executed; - } - } +using System; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Models.MapModels; +using TbsCore.Helpers; + +namespace TbsCore.Tasks.LowLevel +{ + /// + /// Used on TTWars to constantly send resources to your main account + /// + public class TransitToMainAcc : BotTask + { + public Coordinates coords; + public int delay; + + public override async Task Execute(Account acc) + { + acc.Tasks.Add(new TransitToMainAcc + { + coords = this.coords, + delay = this.delay, + ExecuteAt = DateTime.Now.AddSeconds(delay), + Vill = this.Vill + }, true); + + await Task.Delay(AccountHelper.Delay(acc)); + + //Resources res = new Resources() { Wood = 50000000, Clay = 50000000, Iron = 50000000, Crop = 50000000 }; + acc.Tasks.Add(new SendResources() { ExecuteAt = DateTime.Now, Coordinates = coords, Vill = this.Vill }); + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/UpdateFarmLists.cs b/TbsCore/Tasks/Farm/UpdateFarmLists.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/UpdateFarmLists.cs rename to TbsCore/Tasks/Farm/UpdateFarmLists.cs index c88c61147..339bb0bd7 100644 --- a/TbsCore/Tasks/LowLevel/UpdateFarmLists.cs +++ b/TbsCore/Tasks/Farm/UpdateFarmLists.cs @@ -1,77 +1,77 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Helpers; -using TbsCore.Parsers; -using static TbsCore.Helpers.Classificator; -using HtmlAgilityPack; -using TbsCore.Models.TroopsModels; -using System.Collections.Generic; - -namespace TbsCore.Tasks.LowLevel -{ - public class UpdateFarmLists : BotTask - { - public override async Task Execute(Account acc) - { - await NavigationHelper.ToRallyPoint(acc, this.Vill, NavigationHelper.RallyPointTab.Farmlist); - - var foundFLs = FarmlistParser.ParseFL(acc.Wb.Html, acc.AccInfo.ServerVersion); - if (foundFLs == null) - { - acc.Logger.Warning("No FL, do you have rally point in this village?"); - this.Vill = AccountHelper.GetMainVillage(acc); - this.NextExecute = DateTime.Now.AddSeconds(10); - return TaskRes.Executed; - } - foreach (var oldFl in acc.Farming.FL) - { - var foundFL = foundFLs.FirstOrDefault(x => x.Id == oldFl.Id); - if (foundFL == null) //FL was removed! - { - acc.Farming.FL.Remove(oldFl); - continue; - } - //update the Name of FL (maybe it was changed) - oldFl.Name = foundFL.Name; - oldFl.NumOfFarms = foundFL.NumOfFarms; - foundFLs.Remove(foundFL); - } - //If we added a new FL (and was previously not in acc.Farming.FL, it should still be in foundFLs list. So add them - acc.Farming.FL.AddRange(foundFLs); - - // Read all farms in all farmlists - foreach (var farmlist in acc.Farming.FL) - { - var flNode = GetFlNode(acc.Wb.Html, acc.AccInfo.ServerVersion, farmlist.Id); - if (acc.AccInfo.ServerVersion == ServerVersionEnum.TTwars || - flNode.Descendants("div").Any(x => x.HasClass("expandCollapse") && x.HasClass("collapsed"))) - { - await DriverHelper.ExecuteScript(acc, $"Travian.Game.RaidList.toggleList({farmlist.Id});"); - await Task.Delay(AccountHelper.Delay(acc) * 2); - // Update flNode! - flNode = GetFlNode(acc.Wb.Html, acc.AccInfo.ServerVersion, farmlist.Id); - } - - farmlist.Farms = new List(); - foreach (var farm in flNode.Descendants("tr").Where(x => x.HasClass("slotRow"))) - { - var coords = MapParser.GetPositionDetails(farm); - if (coords != null) farmlist.Farms.Add(new GoldClubFarm(coords)); - } - } - return TaskRes.Executed; - } - - private HtmlNode GetFlNode(HtmlDocument htmlDoc, ServerVersionEnum version, int id) - { - switch (version) - { - case ServerVersionEnum.TTwars: return htmlDoc.GetElementbyId("list" + id); - case ServerVersionEnum.T4_5: return htmlDoc.GetElementbyId("raidList" + id); - default: return null; - } - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Helpers; +using TbsCore.Parsers; +using static TbsCore.Helpers.Classificator; +using HtmlAgilityPack; +using TbsCore.Models.TroopsModels; +using System.Collections.Generic; + +namespace TbsCore.Tasks.LowLevel +{ + public class UpdateFarmLists : BotTask + { + public override async Task Execute(Account acc) + { + await NavigationHelper.ToRallyPoint(acc, this.Vill, NavigationHelper.RallyPointTab.Farmlist); + + var foundFLs = FarmlistParser.ParseFL(acc.Wb.Html, acc.AccInfo.ServerVersion); + if (foundFLs == null) + { + acc.Logger.Warning("No FL, do you have rally point in this village?"); + this.Vill = AccountHelper.GetMainVillage(acc); + this.NextExecute = DateTime.Now.AddSeconds(10); + return TaskRes.Executed; + } + foreach (var oldFl in acc.Farming.FL) + { + var foundFL = foundFLs.FirstOrDefault(x => x.Id == oldFl.Id); + if (foundFL == null) //FL was removed! + { + acc.Farming.FL.Remove(oldFl); + continue; + } + //update the Name of FL (maybe it was changed) + oldFl.Name = foundFL.Name; + oldFl.NumOfFarms = foundFL.NumOfFarms; + foundFLs.Remove(foundFL); + } + //If we added a new FL (and was previously not in acc.Farming.FL, it should still be in foundFLs list. So add them + acc.Farming.FL.AddRange(foundFLs); + + // Read all farms in all farmlists + foreach (var farmlist in acc.Farming.FL) + { + var flNode = GetFlNode(acc.Wb.Html, acc.AccInfo.ServerVersion, farmlist.Id); + if (acc.AccInfo.ServerVersion == ServerVersionEnum.TTwars || + flNode.Descendants("div").Any(x => x.HasClass("expandCollapse") && x.HasClass("collapsed"))) + { + await DriverHelper.ExecuteScript(acc, $"Travian.Game.RaidList.toggleList({farmlist.Id});"); + await Task.Delay(AccountHelper.Delay(acc) * 2); + // Update flNode! + flNode = GetFlNode(acc.Wb.Html, acc.AccInfo.ServerVersion, farmlist.Id); + } + + farmlist.Farms = new List(); + foreach (var farm in flNode.Descendants("tr").Where(x => x.HasClass("slotRow"))) + { + var coords = MapParser.GetPositionDetails(farm); + if (coords != null) farmlist.Farms.Add(new GoldClubFarm(coords)); + } + } + return TaskRes.Executed; + } + + private HtmlNode GetFlNode(HtmlDocument htmlDoc, ServerVersionEnum version, int id) + { + switch (version) + { + case ServerVersionEnum.TTwars: return htmlDoc.GetElementbyId("list" + id); + case ServerVersionEnum.T4_5: return htmlDoc.GetElementbyId("raidList" + id); + default: return null; + } + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/ChangeVillageName.cs b/TbsCore/Tasks/Others/ChangeVillageName.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/ChangeVillageName.cs rename to TbsCore/Tasks/Others/ChangeVillageName.cs index 6c7ff8da1..da54990c2 100644 --- a/TbsCore/Tasks/LowLevel/ChangeVillageName.cs +++ b/TbsCore/Tasks/Others/ChangeVillageName.cs @@ -1,73 +1,73 @@ -using OpenQA.Selenium; -using System.Collections.Generic; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using static TbsCore.Helpers.Classificator; - -namespace TbsCore.Tasks.LowLevel -{ - public class ChangeVillageName : BotTask - { - public List<(int, string)> ChangeList { get; set; } - - public override async Task Execute(Account acc) - { - switch (acc.AccInfo.ServerVersion) - { - case ServerVersionEnum.TTwars: - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/spieler.php?s=2"); - - if (acc.Wb.Html.GetElementbyId("PlayerProfileEditor") == null) - { - // Sitter. Can't change the name of the village. TODO: check if sitter before - // creating the task. - acc.Logger.Warning("Sitter cannot change the name of the village"); - return TaskRes.Executed; - } - - foreach (var change in ChangeList) - { - await DriverHelper.WriteByName(acc, $"dname[{change.Item1}]=", change.Item2); - } - - await Task.Delay(AccountHelper.Delay(acc)); - - acc.Wb.ExecuteScript("document.getElementById('PlayerProfileEditor').submit()"); //click save button - - return TaskRes.Executed; - - //support T4.5 and above, if they change we will and more to here - default: - //i dont know they change this when - //but u need click on "Edit profile" to change your profile - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/profile"); - - if (acc.Wb.Html.DocumentNode.SelectSingleNode("//a[@class='tabItem normal']").GetAttributeValue("disabled", "string") == "disabled") - { - // Sitter. Can't change the name of the village. TODO: check if sitter before - // creating the task. - acc.Logger.Warning("Sitter cannot change the name of the village"); - return TaskRes.Executed; - } - - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/profile/edit"); - foreach (var change in ChangeList) - { - //seem like they want we typing instead of setting value (= =) - //if u only setting value by javascript the button still disable - - // Empty text box - await DriverHelper.WriteByName(acc, $"dname[{change.Item1}]=", ""); - //insert new name into the textbox - acc.Wb.Driver.FindElement(By.XPath($"//input[@name='dname[{change.Item1}]=']")).SendKeys(change.Item2); - } - - await Task.Delay(AccountHelper.Delay(acc)); - acc.Wb.Driver.FindElement(By.Id("btn_ok")).Click(); //click save button - - return TaskRes.Executed; - } - } - } +using OpenQA.Selenium; +using System.Collections.Generic; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using static TbsCore.Helpers.Classificator; + +namespace TbsCore.Tasks.LowLevel +{ + public class ChangeVillageName : BotTask + { + public List<(int, string)> ChangeList { get; set; } + + public override async Task Execute(Account acc) + { + switch (acc.AccInfo.ServerVersion) + { + case ServerVersionEnum.TTwars: + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/spieler.php?s=2"); + + if (acc.Wb.Html.GetElementbyId("PlayerProfileEditor") == null) + { + // Sitter. Can't change the name of the village. TODO: check if sitter before + // creating the task. + acc.Logger.Warning("Sitter cannot change the name of the village"); + return TaskRes.Executed; + } + + foreach (var change in ChangeList) + { + await DriverHelper.WriteByName(acc, $"dname[{change.Item1}]=", change.Item2); + } + + await Task.Delay(AccountHelper.Delay(acc)); + + acc.Wb.ExecuteScript("document.getElementById('PlayerProfileEditor').submit()"); //click save button + + return TaskRes.Executed; + + //support T4.5 and above, if they change we will and more to here + default: + //i dont know they change this when + //but u need click on "Edit profile" to change your profile + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/profile"); + + if (acc.Wb.Html.DocumentNode.SelectSingleNode("//a[@class='tabItem normal']").GetAttributeValue("disabled", "string") == "disabled") + { + // Sitter. Can't change the name of the village. TODO: check if sitter before + // creating the task. + acc.Logger.Warning("Sitter cannot change the name of the village"); + return TaskRes.Executed; + } + + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/profile/edit"); + foreach (var change in ChangeList) + { + //seem like they want we typing instead of setting value (= =) + //if u only setting value by javascript the button still disable + + // Empty text box + await DriverHelper.WriteByName(acc, $"dname[{change.Item1}]=", ""); + //insert new name into the textbox + acc.Wb.Driver.FindElement(By.XPath($"//input[@name='dname[{change.Item1}]=']")).SendKeys(change.Item2); + } + + await Task.Delay(AccountHelper.Delay(acc)); + acc.Wb.Driver.FindElement(By.Id("btn_ok")).Click(); //click save button + + return TaskRes.Executed; + } + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/DonateAllyBonus.cs b/TbsCore/Tasks/Others/DonateAllyBonus.cs similarity index 96% rename from TbsCore/Tasks/LowLevel/DonateAllyBonus.cs rename to TbsCore/Tasks/Others/DonateAllyBonus.cs index f9a1c7d9a..7e2dc88c7 100644 --- a/TbsCore/Tasks/LowLevel/DonateAllyBonus.cs +++ b/TbsCore/Tasks/Others/DonateAllyBonus.cs @@ -1,45 +1,45 @@ -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.ResourceModels; - -namespace TbsCore.Tasks.LowLevel -{ - public class DonateAllyBonus : BotTask - { - public Resources ResToDonate { get; set; } - - private string[] Ids = new string[] - { - "bonusTroopProductionSpeed", - "bonusCPProduction", - "bonusSmithyPower", - "bonusMerchantCapacity" - }; - - public override async Task Execute(Account acc) - { - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/alliance/bonuses"); - - for (int i = 0; i < 4; i++) - { - var radioId = Ids[i]; - var radio = acc.Wb.Html.GetElementbyId(radioId); - - // If the bonus is max / already being upgraded - if (radio.GetAttributeValue("disabled", "") == "disabled") continue; - - await DriverHelper.ClickById(acc, radioId); - } - - var donateArr = ResToDonate.ToArray(); - for (int i = 0; i < 4; i++) - { - await DriverHelper.WriteById(acc, $"donate{(i + 1)}", donateArr[i]); - } - - await DriverHelper.ClickById(acc, "donate_green"); - return TaskRes.Executed; - } - } +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.ResourceModels; + +namespace TbsCore.Tasks.LowLevel +{ + public class DonateAllyBonus : BotTask + { + public Resources ResToDonate { get; set; } + + private string[] Ids = new string[] + { + "bonusTroopProductionSpeed", + "bonusCPProduction", + "bonusSmithyPower", + "bonusMerchantCapacity" + }; + + public override async Task Execute(Account acc) + { + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/alliance/bonuses"); + + for (int i = 0; i < 4; i++) + { + var radioId = Ids[i]; + var radio = acc.Wb.Html.GetElementbyId(radioId); + + // If the bonus is max / already being upgraded + if (radio.GetAttributeValue("disabled", "") == "disabled") continue; + + await DriverHelper.ClickById(acc, radioId); + } + + var donateArr = ResToDonate.ToArray(); + for (int i = 0; i < 4; i++) + { + await DriverHelper.WriteById(acc, $"donate{(i + 1)}", donateArr[i]); + } + + await DriverHelper.ClickById(acc, "donate_green"); + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/EditPreferences.cs b/TbsCore/Tasks/Others/EditPreferences.cs similarity index 96% rename from TbsCore/Tasks/LowLevel/EditPreferences.cs rename to TbsCore/Tasks/Others/EditPreferences.cs index eac2900b7..5f0b190c8 100644 --- a/TbsCore/Tasks/LowLevel/EditPreferences.cs +++ b/TbsCore/Tasks/Others/EditPreferences.cs @@ -1,41 +1,41 @@ -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; - -namespace TbsCore.Tasks.LowLevel -{ - public class EditPreferences : BotTask - { - /// - /// Disable contextual help - /// - public bool? ContextualHelp { get; set; } - - /// - /// Troop movements per page in rally point - /// - public int? TroopsPerPage { get; set; } - - public override async Task Execute(Account acc) - { - await VersionHelper.Navigate(acc, "/options.php", "/options"); - - if (ContextualHelp != null) - await DriverHelper.CheckById(acc, "v13", ContextualHelp ?? true); - - if (TroopsPerPage != null) - await DriverHelper.WriteById(acc, "troopMovementsPerPage", TroopsPerPage ?? 10); - - var acceptButton = acc.Wb.Html.DocumentNode - .Descendants("div") - .First(x => x.HasClass("submitButtonContainer")) - .Descendants("button") - .First(); - - await DriverHelper.ClickById(acc, acceptButton.Id); - - return TaskRes.Executed; - } - } +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; + +namespace TbsCore.Tasks.LowLevel +{ + public class EditPreferences : BotTask + { + /// + /// Disable contextual help + /// + public bool? ContextualHelp { get; set; } + + /// + /// Troop movements per page in rally point + /// + public int? TroopsPerPage { get; set; } + + public override async Task Execute(Account acc) + { + await VersionHelper.Navigate(acc, "/options.php", "/options"); + + if (ContextualHelp != null) + await DriverHelper.CheckById(acc, "v13", ContextualHelp ?? true); + + if (TroopsPerPage != null) + await DriverHelper.WriteById(acc, "troopMovementsPerPage", TroopsPerPage ?? 10); + + var acceptButton = acc.Wb.Html.DocumentNode + .Descendants("div") + .First(x => x.HasClass("submitButtonContainer")) + .Descendants("button") + .First(); + + await DriverHelper.ClickById(acc, acceptButton.Id); + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/HeroEquip.cs b/TbsCore/Tasks/Others/HeroEquip.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/HeroEquip.cs rename to TbsCore/Tasks/Others/HeroEquip.cs index 2ec13501a..89aa92f72 100644 --- a/TbsCore/Tasks/LowLevel/HeroEquip.cs +++ b/TbsCore/Tasks/Others/HeroEquip.cs @@ -1,91 +1,91 @@ -using OpenQA.Selenium; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; - -using static TbsCore.Helpers.Classificator; - -namespace TbsCore.Tasks.LowLevel -{ - public class HeroEquip : BotTask - { - public List<(HeroItemEnum, int)> Items { get; set; } - - public override async Task Execute(Account acc) - { - await NavigationHelper.ToHero(acc, NavigationHelper.HeroTab.Attributes); - - foreach (var use in Items) - { - var (item, amount) = use; - - var (category, _, _) = HeroHelper.ParseHeroItem(item); - if (category != HeroItemCategory.Resource && category != HeroItemCategory.Stackable && category != HeroItemCategory.NonStackable) - { - // Check if hero is at home - if (acc.Hero.Status != Hero.StatusEnum.Home) - { - // Wait for hero to come home - var nextExecute = acc.Hero.NextHeroSend > acc.Hero.HeroArrival ? - acc.Hero.NextHeroSend : - acc.Hero.HeroArrival; - - var in5Min = DateTime.Now.AddMinutes(5); - if (nextExecute < in5Min) nextExecute = in5Min; - this.NextExecute = nextExecute; - return TaskRes.Retry; - } - } - - string script = "var items = document.getElementById('itemsToSale');"; - - switch (acc.AccInfo.ServerVersion) - { - case ServerVersionEnum.T4_5: - script += $"items.querySelector('div[class$=\"_{(int)item}\"]').click();"; - break; - - case ServerVersionEnum.TTwars: - script += $"items.querySelector('div[class$=\"_{(int)item} \"]').click();"; - break; - } - - await DriverHelper.ExecuteScript(acc, script); - - // No amount specified, meaning we have already equipt the item - if (amount == 0) continue; - await Task.Delay(900); - acc.Wb.UpdateHtml(); - var amountNode = acc.Wb.Html.GetElementbyId("amount"); - if (amountNode == null) continue; - var amountElement = acc.Wb.Driver.FindElement(By.XPath(amountNode.XPath)); - amountElement.SendKeys(Keys.Home); - amountElement.SendKeys(Keys.Shift + Keys.End); - amountElement.SendKeys($"{ amount}"); - - var okNode = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("ok")); - if (okNode == null) continue; - var okElement = acc.Wb.Driver.FindElement(By.XPath(okNode.XPath)); - okElement.Click(); - await Task.Delay(900); - HeroHelper.ParseHeroPage(acc); - } - - return Done(acc); - } - - /// - /// Refresh the hero page after equipping an item - /// - /// Account - /// TaskRes - - private TaskRes Done(Account acc) - { - return TaskRes.Executed; - } - } +using OpenQA.Selenium; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; + +using static TbsCore.Helpers.Classificator; + +namespace TbsCore.Tasks.LowLevel +{ + public class HeroEquip : BotTask + { + public List<(HeroItemEnum, int)> Items { get; set; } + + public override async Task Execute(Account acc) + { + await NavigationHelper.ToHero(acc, NavigationHelper.HeroTab.Attributes); + + foreach (var use in Items) + { + var (item, amount) = use; + + var (category, _, _) = HeroHelper.ParseHeroItem(item); + if (category != HeroItemCategory.Resource && category != HeroItemCategory.Stackable && category != HeroItemCategory.NonStackable) + { + // Check if hero is at home + if (acc.Hero.Status != Hero.StatusEnum.Home) + { + // Wait for hero to come home + var nextExecute = acc.Hero.NextHeroSend > acc.Hero.HeroArrival ? + acc.Hero.NextHeroSend : + acc.Hero.HeroArrival; + + var in5Min = DateTime.Now.AddMinutes(5); + if (nextExecute < in5Min) nextExecute = in5Min; + this.NextExecute = nextExecute; + return TaskRes.Retry; + } + } + + string script = "var items = document.getElementById('itemsToSale');"; + + switch (acc.AccInfo.ServerVersion) + { + case ServerVersionEnum.T4_5: + script += $"items.querySelector('div[class$=\"_{(int)item}\"]').click();"; + break; + + case ServerVersionEnum.TTwars: + script += $"items.querySelector('div[class$=\"_{(int)item} \"]').click();"; + break; + } + + await DriverHelper.ExecuteScript(acc, script); + + // No amount specified, meaning we have already equipt the item + if (amount == 0) continue; + await Task.Delay(900); + acc.Wb.UpdateHtml(); + var amountNode = acc.Wb.Html.GetElementbyId("amount"); + if (amountNode == null) continue; + var amountElement = acc.Wb.Driver.FindElement(By.XPath(amountNode.XPath)); + amountElement.SendKeys(Keys.Home); + amountElement.SendKeys(Keys.Shift + Keys.End); + amountElement.SendKeys($"{ amount}"); + + var okNode = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("ok")); + if (okNode == null) continue; + var okElement = acc.Wb.Driver.FindElement(By.XPath(okNode.XPath)); + okElement.Click(); + await Task.Delay(900); + HeroHelper.ParseHeroPage(acc); + } + + return Done(acc); + } + + /// + /// Refresh the hero page after equipping an item + /// + /// Account + /// TaskRes + + private TaskRes Done(Account acc) + { + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/HeroSetPoints.cs b/TbsCore/Tasks/Others/HeroSetPoints.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/HeroSetPoints.cs rename to TbsCore/Tasks/Others/HeroSetPoints.cs index 7317ca43c..8a939e946 100644 --- a/TbsCore/Tasks/LowLevel/HeroSetPoints.cs +++ b/TbsCore/Tasks/Others/HeroSetPoints.cs @@ -1,56 +1,56 @@ -using System; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Helpers; - -namespace TbsCore.Tasks.LowLevel -{ - public class HeroSetPoints : BotTask - { - private readonly string[] domId = new string[] { - "attributepower", - "attributeoffBonus", - "attributedefBonus", - "attributeproductionPoints" - }; - - public override async Task Execute(Account acc) - { - await NavigationHelper.ToHero(acc, NavigationHelper.HeroTab.Attributes); - - HeroHelper.ParseHeroPage(acc); - - float sum = 0; - for (int i = 0; i < 4; i++) sum += acc.Hero.Settings.Upgrades[i]; - if (sum == 0) - { - // Upgrade points were not set. Set points to default - acc.Hero.Settings.Upgrades = new byte[4] { 2, 0, 0, 2 }; - sum = 4; - } - - var points = acc.Hero.HeroInfo.AvaliblePoints; - - for (int i = 0; i < 4; i++) - { - var amount = Math.Ceiling(acc.Hero.Settings.Upgrades[i] * points / sum); - if (amount == 0) continue; - - var script = $"var attribute = document.getElementById('{domId[i]}');"; - script += "var upPoint = attribute.getElementsByClassName('pointsValueSetter')[1];"; - script += "upPoint.getElementsByTagName('a')[0].click();"; - - for (int j = 0; j < (int)amount; j++) - { - // Execute the script (set point) to add 1 point - acc.Wb.ExecuteScript(script); - } - await Task.Delay(AccountHelper.Delay(acc)); - } - - acc.Wb.ExecuteScript("document.getElementById('saveHeroAttributes').click();"); - //await Driver - return TaskRes.Executed; - } - } +using System; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Helpers; + +namespace TbsCore.Tasks.LowLevel +{ + public class HeroSetPoints : BotTask + { + private readonly string[] domId = new string[] { + "attributepower", + "attributeoffBonus", + "attributedefBonus", + "attributeproductionPoints" + }; + + public override async Task Execute(Account acc) + { + await NavigationHelper.ToHero(acc, NavigationHelper.HeroTab.Attributes); + + HeroHelper.ParseHeroPage(acc); + + float sum = 0; + for (int i = 0; i < 4; i++) sum += acc.Hero.Settings.Upgrades[i]; + if (sum == 0) + { + // Upgrade points were not set. Set points to default + acc.Hero.Settings.Upgrades = new byte[4] { 2, 0, 0, 2 }; + sum = 4; + } + + var points = acc.Hero.HeroInfo.AvaliblePoints; + + for (int i = 0; i < 4; i++) + { + var amount = Math.Ceiling(acc.Hero.Settings.Upgrades[i] * points / sum); + if (amount == 0) continue; + + var script = $"var attribute = document.getElementById('{domId[i]}');"; + script += "var upPoint = attribute.getElementsByClassName('pointsValueSetter')[1];"; + script += "upPoint.getElementsByTagName('a')[0].click();"; + + for (int j = 0; j < (int)amount; j++) + { + // Execute the script (set point) to add 1 point + acc.Wb.ExecuteScript(script); + } + await Task.Delay(AccountHelper.Delay(acc)); + } + + acc.Wb.ExecuteScript("document.getElementById('saveHeroAttributes').click();"); + //await Driver + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/LoginTask.cs b/TbsCore/Tasks/Others/LoginTask.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/LoginTask.cs rename to TbsCore/Tasks/Others/LoginTask.cs index edc3adf02..d2fd1ebbb 100644 --- a/TbsCore/Tasks/LowLevel/LoginTask.cs +++ b/TbsCore/Tasks/Others/LoginTask.cs @@ -1,124 +1,124 @@ -using HtmlAgilityPack; -using OpenQA.Selenium; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; - -namespace TbsCore.Tasks.LowLevel -{ - public class LoginTask : BotTask - { - public override async Task Execute(Account acc) - { - var usernameNode = GetUsernameNode(acc); - if (usernameNode == null) - { - acc.Logger.Warning("Cannot find username box"); - acc.TaskTimer.Stop(); - acc.Status = Status.Paused; - return TaskRes.Retry; - } - - var passwordNode = GetPasswordNode(acc); - if (passwordNode == null) - { - acc.Logger.Warning("Cannot find password box"); - acc.TaskTimer.Stop(); - acc.Status = Status.Paused; - return TaskRes.Retry; - } - - var buttonNode = GetLoginButton(acc); - if (buttonNode == null) - { - acc.Logger.Warning("Cannot find login button"); - acc.TaskTimer.Stop(); - acc.Status = Status.Paused; - return TaskRes.Retry; - } - - var access = acc.Access.GetCurrentAccess(); - - var usernameElement = acc.Wb.Driver.FindElement(By.XPath(usernameNode.XPath)); - - usernameElement.SendKeys(Keys.Home); - usernameElement.SendKeys(Keys.Shift + Keys.End); - usernameElement.SendKeys(acc.AccInfo.Nickname); - - var passwordElement = acc.Wb.Driver.FindElement(By.XPath(passwordNode.XPath)); - passwordElement.SendKeys(Keys.Home); - passwordElement.SendKeys(Keys.Shift + Keys.End); - passwordElement.SendKeys(access.Password); - - var buttonElement = acc.Wb.Driver.FindElement(By.XPath(buttonNode.XPath)); - buttonElement.Click(); - - var result = await DriverHelper.WaitPageChange(acc, "dorf"); - - if (!result && TaskExecutor.IsLoginScreen(acc)) - { - // Wrong password/nickname - acc.Logger.Warning("Password is incorrect!"); - acc.TaskTimer.Stop(); - acc.Status = Status.Paused; - return TaskRes.Retry; - } - else - { - // check sitter account - var auction = acc.Wb.Html.DocumentNode.Descendants("a").FirstOrDefault(x => x.HasClass("auction")); - acc.Access.GetCurrentAccess().IsSittering = (auction != null && auction.HasClass("disable")); - return TaskRes.Executed; - } - } - - private HtmlNode GetUsernameNode(Account acc) - { - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.TTwars: - return acc.Wb.Html.DocumentNode.Descendants("input").FirstOrDefault(x => x.GetAttributeValue("name", "").Equals("user")); - - case Classificator.ServerVersionEnum.T4_5: - return acc.Wb.Html.DocumentNode.Descendants("input").FirstOrDefault(x => x.GetAttributeValue("name", "").Equals("name")); - - default: - return null; - }; - } - - private HtmlNode GetPasswordNode(Account acc) - { - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.TTwars: - return acc.Wb.Html.DocumentNode.Descendants("input").FirstOrDefault(x => x.GetAttributeValue("name", "").Equals("pw")); - - case Classificator.ServerVersionEnum.T4_5: - return acc.Wb.Html.DocumentNode.Descendants("input").FirstOrDefault(x => x.GetAttributeValue("name", "").Equals("password")); - - default: - return null; - }; - } - - private HtmlNode GetLoginButton(Account acc) - { - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.TTwars: - return acc.Wb.Html.GetElementbyId("s1"); - - case Classificator.ServerVersionEnum.T4_5: - { - var trNode = acc.Wb.Html.DocumentNode.Descendants("tr").FirstOrDefault(x => x.HasClass("loginButtonRow")); - if (trNode == null) return null; - return trNode.Descendants("button").FirstOrDefault(x => x.HasClass("green")); - } - default: - return null; - }; - } - } +using HtmlAgilityPack; +using OpenQA.Selenium; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; + +namespace TbsCore.Tasks.LowLevel +{ + public class LoginTask : BotTask + { + public override async Task Execute(Account acc) + { + var usernameNode = GetUsernameNode(acc); + if (usernameNode == null) + { + acc.Logger.Warning("Cannot find username box"); + acc.TaskTimer.Stop(); + acc.Status = Status.Paused; + return TaskRes.Retry; + } + + var passwordNode = GetPasswordNode(acc); + if (passwordNode == null) + { + acc.Logger.Warning("Cannot find password box"); + acc.TaskTimer.Stop(); + acc.Status = Status.Paused; + return TaskRes.Retry; + } + + var buttonNode = GetLoginButton(acc); + if (buttonNode == null) + { + acc.Logger.Warning("Cannot find login button"); + acc.TaskTimer.Stop(); + acc.Status = Status.Paused; + return TaskRes.Retry; + } + + var access = acc.Access.GetCurrentAccess(); + + var usernameElement = acc.Wb.Driver.FindElement(By.XPath(usernameNode.XPath)); + + usernameElement.SendKeys(Keys.Home); + usernameElement.SendKeys(Keys.Shift + Keys.End); + usernameElement.SendKeys(acc.AccInfo.Nickname); + + var passwordElement = acc.Wb.Driver.FindElement(By.XPath(passwordNode.XPath)); + passwordElement.SendKeys(Keys.Home); + passwordElement.SendKeys(Keys.Shift + Keys.End); + passwordElement.SendKeys(access.Password); + + var buttonElement = acc.Wb.Driver.FindElement(By.XPath(buttonNode.XPath)); + buttonElement.Click(); + + var result = await DriverHelper.WaitPageChange(acc, "dorf"); + + if (!result && TaskExecutor.IsLoginScreen(acc)) + { + // Wrong password/nickname + acc.Logger.Warning("Password is incorrect!"); + acc.TaskTimer.Stop(); + acc.Status = Status.Paused; + return TaskRes.Retry; + } + else + { + // check sitter account + var auction = acc.Wb.Html.DocumentNode.Descendants("a").FirstOrDefault(x => x.HasClass("auction")); + acc.Access.GetCurrentAccess().IsSittering = (auction != null && auction.HasClass("disable")); + return TaskRes.Executed; + } + } + + private HtmlNode GetUsernameNode(Account acc) + { + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.TTwars: + return acc.Wb.Html.DocumentNode.Descendants("input").FirstOrDefault(x => x.GetAttributeValue("name", "").Equals("user")); + + case Classificator.ServerVersionEnum.T4_5: + return acc.Wb.Html.DocumentNode.Descendants("input").FirstOrDefault(x => x.GetAttributeValue("name", "").Equals("name")); + + default: + return null; + }; + } + + private HtmlNode GetPasswordNode(Account acc) + { + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.TTwars: + return acc.Wb.Html.DocumentNode.Descendants("input").FirstOrDefault(x => x.GetAttributeValue("name", "").Equals("pw")); + + case Classificator.ServerVersionEnum.T4_5: + return acc.Wb.Html.DocumentNode.Descendants("input").FirstOrDefault(x => x.GetAttributeValue("name", "").Equals("password")); + + default: + return null; + }; + } + + private HtmlNode GetLoginButton(Account acc) + { + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.TTwars: + return acc.Wb.Html.GetElementbyId("s1"); + + case Classificator.ServerVersionEnum.T4_5: + { + var trNode = acc.Wb.Html.DocumentNode.Descendants("tr").FirstOrDefault(x => x.HasClass("loginButtonRow")); + if (trNode == null) return null; + return trNode.Descendants("button").FirstOrDefault(x => x.HasClass("green")); + } + default: + return null; + }; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/RandomTask.cs b/TbsCore/Tasks/Others/RandomTask.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/RandomTask.cs rename to TbsCore/Tasks/Others/RandomTask.cs index 64f19f37c..3903a7e6e 100644 --- a/TbsCore/Tasks/LowLevel/RandomTask.cs +++ b/TbsCore/Tasks/Others/RandomTask.cs @@ -1,74 +1,74 @@ -using System; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; - -namespace TbsCore.Tasks.LowLevel -{ - /// - /// Just a random navigation event - to make bot less suspicious to Travian. - /// - public class RandomTask : BotTask - { - public int MinWait { get; set; } = 5000; - public int MaxWait { get; set; } = 20000; - - private readonly string[] UrlT4_4 = new string[] { - "/statistiken.php", // player - "/statistiken.php?id=1", // ally - "/statistiken.php?id=1&idSub=3", // ally TOP10 - "/statistiken.php?id=3", // hero - "/statistiken.php?id=0&idSub=3", // player top10 - "/spieler.php", // profile - "/statistiken.php?id=0&idSub=1", // players top attackers - "/statistiken.php?id=0&idSub=2", // players top deffenders - "/messages.php", // messages - "/hero.php?t=4", // Hero auctions - "/reports.php", - "/reports.php?t=1", - "/reports.php?t=2", - "/reports.php?t=3", - "/reports.php?t=4", - }; - - private readonly string[] UrlT4_5 = new string[] { - "/statistics", // player - "/statistics/alliance", // ally - "/statistics/alliance?idSub=3", // ally TOP10 - "/statistics/hero", // hero - "/statistics/player?idSub=3", // player top10 - "/profile", // profile - "/statistics/player?idSub=1", // players top attackers - "/statistics/player?idSub=2", // players top deffenders - "/messages.php", // messages - "/hero/auction", // Hero auctions - "/report", - "/report/offensive", - "/report/defensive", - "/report/scouting", - "/report/other", - }; - - public override async Task Execute(Account acc) - { - string[] Urls = new string[0]; - switch (acc.AccInfo.ServerVersion) - { - case Helpers.Classificator.ServerVersionEnum.TTwars: - Urls = UrlT4_4; - break; - - case Helpers.Classificator.ServerVersionEnum.T4_5: - Urls = UrlT4_5; - break; - } - - var ran = new Random(); - var id = ran.Next(0, Urls.Length - 1); - - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}{Urls[id]}"); - await Task.Delay(ran.Next(MinWait, MaxWait)); - - return TaskRes.Executed; - } - } +using System; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; + +namespace TbsCore.Tasks.LowLevel +{ + /// + /// Just a random navigation event - to make bot less suspicious to Travian. + /// + public class RandomTask : BotTask + { + public int MinWait { get; set; } = 5000; + public int MaxWait { get; set; } = 20000; + + private readonly string[] UrlT4_4 = new string[] { + "/statistiken.php", // player + "/statistiken.php?id=1", // ally + "/statistiken.php?id=1&idSub=3", // ally TOP10 + "/statistiken.php?id=3", // hero + "/statistiken.php?id=0&idSub=3", // player top10 + "/spieler.php", // profile + "/statistiken.php?id=0&idSub=1", // players top attackers + "/statistiken.php?id=0&idSub=2", // players top deffenders + "/messages.php", // messages + "/hero.php?t=4", // Hero auctions + "/reports.php", + "/reports.php?t=1", + "/reports.php?t=2", + "/reports.php?t=3", + "/reports.php?t=4", + }; + + private readonly string[] UrlT4_5 = new string[] { + "/statistics", // player + "/statistics/alliance", // ally + "/statistics/alliance?idSub=3", // ally TOP10 + "/statistics/hero", // hero + "/statistics/player?idSub=3", // player top10 + "/profile", // profile + "/statistics/player?idSub=1", // players top attackers + "/statistics/player?idSub=2", // players top deffenders + "/messages.php", // messages + "/hero/auction", // Hero auctions + "/report", + "/report/offensive", + "/report/defensive", + "/report/scouting", + "/report/other", + }; + + public override async Task Execute(Account acc) + { + string[] Urls = new string[0]; + switch (acc.AccInfo.ServerVersion) + { + case Helpers.Classificator.ServerVersionEnum.TTwars: + Urls = UrlT4_4; + break; + + case Helpers.Classificator.ServerVersionEnum.T4_5: + Urls = UrlT4_5; + break; + } + + var ran = new Random(); + var id = ran.Next(0, Urls.Length - 1); + + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}{Urls[id]}"); + await Task.Delay(ran.Next(MinWait, MaxWait)); + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/ReviveHero.cs b/TbsCore/Tasks/Others/ReviveHero.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/ReviveHero.cs rename to TbsCore/Tasks/Others/ReviveHero.cs index dfea6f316..8d1aacd0c 100644 --- a/TbsCore/Tasks/LowLevel/ReviveHero.cs +++ b/TbsCore/Tasks/Others/ReviveHero.cs @@ -1,49 +1,49 @@ -using System; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Helpers; -using OpenQA.Selenium; - -namespace TbsCore.Tasks.LowLevel -{ - public class ReviveHero : BotTask - { - public override async Task Execute(Account acc) - { - StopFlag = false; - acc.Logger.Information("Navigate to revive page", this); - await NavigationHelper.ToHero(acc, NavigationHelper.HeroTab.Attributes); - if (StopFlag) return TaskRes.Executed; - - acc.Logger.Information("Find revive button to click", this); - //heroRegeneration - var reviveButton = acc.Wb.Html.GetElementbyId("heroRegeneration"); - if (reviveButton == null) - { - acc.Logger.Information("No revive button found!"); - return TaskRes.Executed; - } - - if (reviveButton.HasClass("green")) - { - var element = acc.Wb.Driver.FindElement(By.XPath(reviveButton.XPath)); - - if (element == null) - { - acc.Logger.Information("Cannot click revive button!"); - return TaskRes.Executed; - } - - element.Click(); - return TaskRes.Executed; - } - else - { - //no resources? - acc.Logger.Information("Don't have enough resource. Retry after 10 minutes!"); - NextExecute = DateTime.Now.AddMinutes(10); - return TaskRes.Executed; - } - } - } +using System; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Helpers; +using OpenQA.Selenium; + +namespace TbsCore.Tasks.LowLevel +{ + public class ReviveHero : BotTask + { + public override async Task Execute(Account acc) + { + StopFlag = false; + acc.Logger.Information("Navigate to revive page", this); + await NavigationHelper.ToHero(acc, NavigationHelper.HeroTab.Attributes); + if (StopFlag) return TaskRes.Executed; + + acc.Logger.Information("Find revive button to click", this); + //heroRegeneration + var reviveButton = acc.Wb.Html.GetElementbyId("heroRegeneration"); + if (reviveButton == null) + { + acc.Logger.Information("No revive button found!"); + return TaskRes.Executed; + } + + if (reviveButton.HasClass("green")) + { + var element = acc.Wb.Driver.FindElement(By.XPath(reviveButton.XPath)); + + if (element == null) + { + acc.Logger.Information("Cannot click revive button!"); + return TaskRes.Executed; + } + + element.Click(); + return TaskRes.Executed; + } + else + { + //no resources? + acc.Logger.Information("Don't have enough resource. Retry after 10 minutes!"); + NextExecute = DateTime.Now.AddMinutes(10); + return TaskRes.Executed; + } + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/SellOnAuctions.cs b/TbsCore/Tasks/Others/SellOnAuctions.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/SellOnAuctions.cs rename to TbsCore/Tasks/Others/SellOnAuctions.cs index 0ef4c0b5e..a3ded93e7 100644 --- a/TbsCore/Tasks/LowLevel/SellOnAuctions.cs +++ b/TbsCore/Tasks/Others/SellOnAuctions.cs @@ -1,120 +1,120 @@ -using OpenQA.Selenium; -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Parsers; -using static TbsCore.Helpers.Classificator; - -namespace TbsCore.Tasks.LowLevel -{ - public class SellOnAuctions : BotTask - { - private readonly Random rand = new Random(); - - public override async Task Execute(Account acc) - - { - if (acc.AccInfo.ServerVersion == ServerVersionEnum.TTwars) return TaskRes.Executed; - if (!acc.Wb.CurrentUrl.Contains("auction?action=sell")) - { - string xPathSellTab = null; - - switch (acc.AccInfo.ServerVersion) - { - case ServerVersionEnum.TTwars: - xPathSellTab = "//*[@id='content']/div[4]/div[2]/div[3]/a"; - break; - - case ServerVersionEnum.T4_5: - xPathSellTab = "//*[@id='heroAuction']/div[2]/div[2]/div[3]/a"; - break; - } - // enter right tab - - do - { - await NavigationHelper.ToHero(acc, NavigationHelper.HeroTab.Auctions); - - var node = acc.Wb.Html.DocumentNode.SelectSingleNode(xPathSellTab); - if (node == null) continue; - var element = acc.Wb.Driver.FindElement(By.XPath(node.XPath)); - if (element == null) continue; - element.Click(); - - try - { - await DriverHelper.WaitPageChange(acc, "auction?action=sell"); - } - catch - { - continue; - } - break; - } - while (true); - } - - acc.Wb.UpdateHtml(); - var nodeAllItem = acc.Wb.Html.GetElementbyId("itemsToSale"); - if (nodeAllItem == null) return TaskRes.Executed; - - var nodeItems = nodeAllItem.Descendants("div").Where(x => !x.HasClass("disabled") && x.HasClass("item")); - if (nodeItems.Count() == 0) return TaskRes.Executed; - - foreach (var nodeItem in nodeItems) - { - (var heroItemEnum, int amount) = HeroParser.ParseItemNode(nodeItem); - if (heroItemEnum == null) continue; - - var category = HeroHelper.GetHeroItemCategory(heroItemEnum ?? HeroItemEnum.Others_None_0); - switch (category) - { - case HeroItemCategory.Others: - continue; - case HeroItemCategory.Resource: - continue; - - case HeroItemCategory.Stackable: - if (amount < 5) continue; - break; - - case HeroItemCategory.Horse: - continue; - } - - var nodeParentItem = nodeItem.ParentNode; - var nodeItemXPath = acc.Wb.Html.DocumentNode.SelectSingleNode($"//*[@id='{nodeParentItem.Id}']/div"); - if (nodeItem.Id != nodeItemXPath.Id) continue; - var element = acc.Wb.Driver.FindElement(By.XPath(nodeItemXPath.XPath)); - if (element == null) continue; - element.Click(); - await Task.Delay(rand.Next(1500, 2500)); - - int counter = 3; - do - { - counter--; - acc.Wb.UpdateHtml(); - var nodeDialog = acc.Wb.Html.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass("dialogVisible")); - if (nodeDialog == null) continue; - - var button = acc.Wb.Html.DocumentNode.SelectSingleNode("//*[@id='mainLayout']/body/div[1]/div/div/div/div/form/div[6]/button"); - if (button == null) continue; - try - { - var elementButton = acc.Wb.Driver.FindElement(By.XPath(button.XPath)); - if (elementButton == null) continue; - elementButton.Click(); - } - catch { } - break; - } - while (counter > 0); - } - - return TaskRes.Executed; - } - } +using OpenQA.Selenium; +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Parsers; +using static TbsCore.Helpers.Classificator; + +namespace TbsCore.Tasks.LowLevel +{ + public class SellOnAuctions : BotTask + { + private readonly Random rand = new Random(); + + public override async Task Execute(Account acc) + + { + if (acc.AccInfo.ServerVersion == ServerVersionEnum.TTwars) return TaskRes.Executed; + if (!acc.Wb.CurrentUrl.Contains("auction?action=sell")) + { + string xPathSellTab = null; + + switch (acc.AccInfo.ServerVersion) + { + case ServerVersionEnum.TTwars: + xPathSellTab = "//*[@id='content']/div[4]/div[2]/div[3]/a"; + break; + + case ServerVersionEnum.T4_5: + xPathSellTab = "//*[@id='heroAuction']/div[2]/div[2]/div[3]/a"; + break; + } + // enter right tab + + do + { + await NavigationHelper.ToHero(acc, NavigationHelper.HeroTab.Auctions); + + var node = acc.Wb.Html.DocumentNode.SelectSingleNode(xPathSellTab); + if (node == null) continue; + var element = acc.Wb.Driver.FindElement(By.XPath(node.XPath)); + if (element == null) continue; + element.Click(); + + try + { + await DriverHelper.WaitPageChange(acc, "auction?action=sell"); + } + catch + { + continue; + } + break; + } + while (true); + } + + acc.Wb.UpdateHtml(); + var nodeAllItem = acc.Wb.Html.GetElementbyId("itemsToSale"); + if (nodeAllItem == null) return TaskRes.Executed; + + var nodeItems = nodeAllItem.Descendants("div").Where(x => !x.HasClass("disabled") && x.HasClass("item")); + if (nodeItems.Count() == 0) return TaskRes.Executed; + + foreach (var nodeItem in nodeItems) + { + (var heroItemEnum, int amount) = HeroParser.ParseItemNode(nodeItem); + if (heroItemEnum == null) continue; + + var category = HeroHelper.GetHeroItemCategory(heroItemEnum ?? HeroItemEnum.Others_None_0); + switch (category) + { + case HeroItemCategory.Others: + continue; + case HeroItemCategory.Resource: + continue; + + case HeroItemCategory.Stackable: + if (amount < 5) continue; + break; + + case HeroItemCategory.Horse: + continue; + } + + var nodeParentItem = nodeItem.ParentNode; + var nodeItemXPath = acc.Wb.Html.DocumentNode.SelectSingleNode($"//*[@id='{nodeParentItem.Id}']/div"); + if (nodeItem.Id != nodeItemXPath.Id) continue; + var element = acc.Wb.Driver.FindElement(By.XPath(nodeItemXPath.XPath)); + if (element == null) continue; + element.Click(); + await Task.Delay(rand.Next(1500, 2500)); + + int counter = 3; + do + { + counter--; + acc.Wb.UpdateHtml(); + var nodeDialog = acc.Wb.Html.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass("dialogVisible")); + if (nodeDialog == null) continue; + + var button = acc.Wb.Html.DocumentNode.SelectSingleNode("//*[@id='mainLayout']/body/div[1]/div/div/div/div/form/div[6]/button"); + if (button == null) continue; + try + { + var elementButton = acc.Wb.Driver.FindElement(By.XPath(button.XPath)); + if (elementButton == null) continue; + elementButton.Click(); + } + catch { } + break; + } + while (counter > 0); + } + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/SendResFillTroops.cs b/TbsCore/Tasks/Others/SendResFillTroops.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/SendResFillTroops.cs rename to TbsCore/Tasks/Others/SendResFillTroops.cs index aaf59d6db..ad063d6c6 100644 --- a/TbsCore/Tasks/LowLevel/SendResFillTroops.cs +++ b/TbsCore/Tasks/Others/SendResFillTroops.cs @@ -1,72 +1,72 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Models.VillageModels; -using TbsCore.Helpers; -using TbsCore.TravianData; - -namespace TbsCore.Tasks.LowLevel -{ - /// - /// Sends resources from main village to target village so it can fill up the troops to above X hours - /// Will try to fill troops to to 50% above selected hours in advance - /// So if we want to keep barracks filled for 4h in advance, on this task we will send enough res to fill for up to - /// 6 hours in advance. - /// - public class SendResFillTroops : BotTask - { - /// - /// Village to send resources to - /// - public Village TargetVill { get; set; } - - public TrainTroops TrainTask { get; set; } - - public override async Task Execute(Account acc) - { - if (!await NavigationHelper.ToMarketplace(acc, Vill, NavigationHelper.MarketplaceTab.SendResources)) - return TaskRes.Executed; - - //get troop resource/time cost - var troopCost = TroopCost.GetResourceCost(TrainTask.Troop, TrainTask.Great); - - var trainNum = TroopsHelper.TroopsToFill(acc, TargetVill, TrainTask.Troop, TrainTask.Great); - - //how many troops we can train with resources that we have - var mainVillResStored = Vill.Res.Stored.Resources.ToArray(); - var targetVillStoredRes = TargetVill.Res.Stored.Resources.ToArray(); - - // Max troops we can train with resources that we have - var maxTroopsToTrain = ResourcesHelper.MaxTroopsToTrain(mainVillResStored, targetVillStoredRes, troopCost); - - // If we don't have enough rsoruces to train the number of troops that we want, we will train max number of troops that we can - if (maxTroopsToTrain < trainNum) trainNum = maxTroopsToTrain; - - //calculate how many resources we need to train trainNum of troops - long[] neededRes = troopCost.Select(x => x * trainNum).ToArray(); - - //if we have already enough resources in the target village, no need to send anything - if (ResourcesHelper.IsEnoughRes(targetVillStoredRes, neededRes)) - { - this.TrainTask.ExecuteAt = DateTime.Now; - acc.Tasks.ReOrder(); - return TaskRes.Executed; - } - - //amount of resources we want to transit to target village - var sendRes = ResourcesHelper.SendAmount(targetVillStoredRes, neededRes); - - // Check how many merchants we have. If we have 0, wait till some come back. - - var transitTimespan = await MarketHelper.MarketSendResource(acc, sendRes, TargetVill, this); - - //train the troops in the target village after we send the needed - this.TrainTask.ExecuteAt = DateTime.Now.Add(transitTimespan).AddSeconds(5); - acc.Tasks.ReOrder(); - - //TODO: Update marketplace sending - return TaskRes.Executed; - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Models.VillageModels; +using TbsCore.Helpers; +using TbsCore.TravianData; + +namespace TbsCore.Tasks.LowLevel +{ + /// + /// Sends resources from main village to target village so it can fill up the troops to above X hours + /// Will try to fill troops to to 50% above selected hours in advance + /// So if we want to keep barracks filled for 4h in advance, on this task we will send enough res to fill for up to + /// 6 hours in advance. + /// + public class SendResFillTroops : BotTask + { + /// + /// Village to send resources to + /// + public Village TargetVill { get; set; } + + public TrainTroops TrainTask { get; set; } + + public override async Task Execute(Account acc) + { + if (!await NavigationHelper.ToMarketplace(acc, Vill, NavigationHelper.MarketplaceTab.SendResources)) + return TaskRes.Executed; + + //get troop resource/time cost + var troopCost = TroopCost.GetResourceCost(TrainTask.Troop, TrainTask.Great); + + var trainNum = TroopsHelper.TroopsToFill(acc, TargetVill, TrainTask.Troop, TrainTask.Great); + + //how many troops we can train with resources that we have + var mainVillResStored = Vill.Res.Stored.Resources.ToArray(); + var targetVillStoredRes = TargetVill.Res.Stored.Resources.ToArray(); + + // Max troops we can train with resources that we have + var maxTroopsToTrain = ResourcesHelper.MaxTroopsToTrain(mainVillResStored, targetVillStoredRes, troopCost); + + // If we don't have enough rsoruces to train the number of troops that we want, we will train max number of troops that we can + if (maxTroopsToTrain < trainNum) trainNum = maxTroopsToTrain; + + //calculate how many resources we need to train trainNum of troops + long[] neededRes = troopCost.Select(x => x * trainNum).ToArray(); + + //if we have already enough resources in the target village, no need to send anything + if (ResourcesHelper.IsEnoughRes(targetVillStoredRes, neededRes)) + { + this.TrainTask.ExecuteAt = DateTime.Now; + acc.Tasks.ReOrder(); + return TaskRes.Executed; + } + + //amount of resources we want to transit to target village + var sendRes = ResourcesHelper.SendAmount(targetVillStoredRes, neededRes); + + // Check how many merchants we have. If we have 0, wait till some come back. + + var transitTimespan = await MarketHelper.MarketSendResource(acc, sendRes, TargetVill, this); + + //train the troops in the target village after we send the needed + this.TrainTask.ExecuteAt = DateTime.Now.Add(transitTimespan).AddSeconds(5); + acc.Tasks.ReOrder(); + + //TODO: Update marketplace sending + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/SendResToMain.cs b/TbsCore/Tasks/Others/SendResToMain.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/SendResToMain.cs rename to TbsCore/Tasks/Others/SendResToMain.cs index 4aa6c9d68..21beab772 100644 --- a/TbsCore/Tasks/LowLevel/SendResToMain.cs +++ b/TbsCore/Tasks/Others/SendResToMain.cs @@ -1,38 +1,38 @@ -using System; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Models.Settings; -using TbsCore.Helpers; - -namespace TbsCore.Tasks.LowLevel -{ - /// - /// Send all resources above X% to main village. - /// TODO: If we have auto celebration selected, leave res for that (calculate based on production) - /// - public class SendResToMain : BotTask - { - public override async Task Execute(Account acc) - { - // If this is the main village, don't try to send resources - if (AccountHelper.GetMainVillage(acc) == this.Vill) return TaskRes.Executed; - - var res = MarketHelper.GetResToMainVillage(Vill); - if (res.Sum() <= 0) return TaskRes.Executed; - - if (!await NavigationHelper.ToMarketplace(acc, Vill, NavigationHelper.MarketplaceTab.SendResources)) - return TaskRes.Executed; - - if (this.Vill.Settings.Type == VillType.Support && this.Vill.Settings.SendRes) - { - // Repeat this task - var ran = new Random(); - this.NextExecute = DateTime.Now.AddMinutes(ran.Next(30, 60)); - } - - var mainVill = AccountHelper.GetMainVillage(acc); - var ret = await MarketHelper.MarketSendResource(acc, res, mainVill, this); - return TaskRes.Executed; - } - } +using System; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Models.Settings; +using TbsCore.Helpers; + +namespace TbsCore.Tasks.LowLevel +{ + /// + /// Send all resources above X% to main village. + /// TODO: If we have auto celebration selected, leave res for that (calculate based on production) + /// + public class SendResToMain : BotTask + { + public override async Task Execute(Account acc) + { + // If this is the main village, don't try to send resources + if (AccountHelper.GetMainVillage(acc) == this.Vill) return TaskRes.Executed; + + var res = MarketHelper.GetResToMainVillage(Vill); + if (res.Sum() <= 0) return TaskRes.Executed; + + if (!await NavigationHelper.ToMarketplace(acc, Vill, NavigationHelper.MarketplaceTab.SendResources)) + return TaskRes.Executed; + + if (this.Vill.Settings.Type == VillType.Support && this.Vill.Settings.SendRes) + { + // Repeat this task + var ran = new Random(); + this.NextExecute = DateTime.Now.AddMinutes(ran.Next(30, 60)); + } + + var mainVill = AccountHelper.GetMainVillage(acc); + var ret = await MarketHelper.MarketSendResource(acc, res, mainVill, this); + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/SendResources.cs b/TbsCore/Tasks/Others/SendResources.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/SendResources.cs rename to TbsCore/Tasks/Others/SendResources.cs index 93515059e..0aec0c751 100644 --- a/TbsCore/Tasks/LowLevel/SendResources.cs +++ b/TbsCore/Tasks/Others/SendResources.cs @@ -1,45 +1,45 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Models.MapModels; -using TbsCore.Models.ResourceModels; -using TbsCore.Helpers; - -namespace TbsCore.Tasks.LowLevel -{ - public class SendResources : BotTask - { - public SendResourcesConfiguration Configuration { get; set; } - public Resources Resources { get; set; } - public Coordinates Coordinates { get; set; } - public int RunTimes { get; set; } //once / twice / 3 times - - public override async Task Execute(Account acc) - { - if (!await NavigationHelper.ToMarketplace(acc, Vill, NavigationHelper.MarketplaceTab.SendResources)) - return TaskRes.Executed; - - if (this.Resources == null) - { - this.Resources = Vill.Res.Stored.Resources; - } - // Check if we have enough resources in main village - var resToSend = MarketHelper.SendResCapToStorage(acc, this.Resources); - - var targetVillage = acc.Villages.FirstOrDefault(x => x.Coordinates == this.Coordinates); - - var duration = await MarketHelper.MarketSendResource(acc, resToSend, targetVillage, this); - - var targetVill = acc.Villages.FirstOrDefault(x => x.Coordinates == Coordinates); - targetVill.Market.Settings.Configuration.TransitArrival = DateTime.Now.Add(duration); - - if (this.Configuration != null && duration != null) - { - this.Configuration.TransitArrival = DateTime.Now.Add(duration); - } - // When you send resources there actually isn't a page load - return TaskRes.Executed; - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Models.MapModels; +using TbsCore.Models.ResourceModels; +using TbsCore.Helpers; + +namespace TbsCore.Tasks.LowLevel +{ + public class SendResources : BotTask + { + public SendResourcesConfiguration Configuration { get; set; } + public Resources Resources { get; set; } + public Coordinates Coordinates { get; set; } + public int RunTimes { get; set; } //once / twice / 3 times + + public override async Task Execute(Account acc) + { + if (!await NavigationHelper.ToMarketplace(acc, Vill, NavigationHelper.MarketplaceTab.SendResources)) + return TaskRes.Executed; + + if (this.Resources == null) + { + this.Resources = Vill.Res.Stored.Resources; + } + // Check if we have enough resources in main village + var resToSend = MarketHelper.SendResCapToStorage(acc, this.Resources); + + var targetVillage = acc.Villages.FirstOrDefault(x => x.Coordinates == this.Coordinates); + + var duration = await MarketHelper.MarketSendResource(acc, resToSend, targetVillage, this); + + var targetVill = acc.Villages.FirstOrDefault(x => x.Coordinates == Coordinates); + targetVill.Market.Settings.Configuration.TransitArrival = DateTime.Now.Add(duration); + + if (this.Configuration != null && duration != null) + { + this.Configuration.TransitArrival = DateTime.Now.Add(duration); + } + // When you send resources there actually isn't a page load + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/SetCapital.cs b/TbsCore/Tasks/Others/SetCapital.cs similarity index 100% rename from TbsCore/Tasks/LowLevel/SetCapital.cs rename to TbsCore/Tasks/Others/SetCapital.cs diff --git a/TbsCore/Tasks/LowLevel/StartAdventure.cs b/TbsCore/Tasks/Others/StartAdventure.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/StartAdventure.cs rename to TbsCore/Tasks/Others/StartAdventure.cs index 41f039c28..85dea16a6 100644 --- a/TbsCore/Tasks/LowLevel/StartAdventure.cs +++ b/TbsCore/Tasks/Others/StartAdventure.cs @@ -1,70 +1,70 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Parsers; - -namespace TbsCore.Tasks.LowLevel -{ - public class StartAdventure : BotTask - { - /// - /// In case we want to only update adventures - /// - public bool UpdateOnly { get; set; } - - public override async Task Execute(Account acc) - { - await NavigationHelper.ToHero(acc, NavigationHelper.HeroTab.Adventures); - - acc.Hero.Adventures = AdventureParser.GetAdventures(acc.Wb.Html, acc.AccInfo.ServerVersion); - - HeroHelper.UpdateHeroVillage(acc); - - if (acc.Hero.Adventures == null || acc.Hero.Adventures.Count == 0 || UpdateOnly) return TaskRes.Executed; - - var adventures = acc.Hero.Adventures - .Where(x => - x.Coordinates.CalculateDistance(acc, HeroHelper.GetHeroHomeVillage(acc).Coordinates) <= acc.Hero.Settings.MaxDistance - ) - .ToList(); - - if (adventures.Count == 0) return TaskRes.Executed; - - var adventure = adventures.FirstOrDefault(x => x.Difficulty == Classificator.DifficultyEnum.Normal); - if (adventure == null) adventure = adventures.FirstOrDefault(); - - acc.Hero.NextHeroSend = DateTime.Now.AddSeconds(adventure.DurationSeconds * 2); - - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.TTwars: - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/{adventure.Ref}"); - - var startButton = acc.Wb.Html.GetElementbyId("start"); - if (startButton == null) - { - //Hero is probably out of the village. - this.NextExecute = DateTime.Now.AddMinutes(10); - return TaskRes.Executed; - } - await DriverHelper.ClickById(acc, "start"); - break; - - case Classificator.ServerVersionEnum.T4_5: - string script = $"var div = document.getElementById('{adventure.AdventureId}');"; - script += $"div.children[0].submit();"; - await DriverHelper.ExecuteScript(acc, script); - - // Check hero outgoing time - var outTime = HeroParser.GetHeroArrival(acc.Wb.Html); - // At least 1.5x longer (if hero has Large map) - acc.Hero.NextHeroSend = DateTime.Now + TimeSpan.FromTicks((long)(outTime.Ticks * 1.5)); - break; - } - - return TaskRes.Executed; - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Parsers; + +namespace TbsCore.Tasks.LowLevel +{ + public class StartAdventure : BotTask + { + /// + /// In case we want to only update adventures + /// + public bool UpdateOnly { get; set; } + + public override async Task Execute(Account acc) + { + await NavigationHelper.ToHero(acc, NavigationHelper.HeroTab.Adventures); + + acc.Hero.Adventures = AdventureParser.GetAdventures(acc.Wb.Html, acc.AccInfo.ServerVersion); + + HeroHelper.UpdateHeroVillage(acc); + + if (acc.Hero.Adventures == null || acc.Hero.Adventures.Count == 0 || UpdateOnly) return TaskRes.Executed; + + var adventures = acc.Hero.Adventures + .Where(x => + x.Coordinates.CalculateDistance(acc, HeroHelper.GetHeroHomeVillage(acc).Coordinates) <= acc.Hero.Settings.MaxDistance + ) + .ToList(); + + if (adventures.Count == 0) return TaskRes.Executed; + + var adventure = adventures.FirstOrDefault(x => x.Difficulty == Classificator.DifficultyEnum.Normal); + if (adventure == null) adventure = adventures.FirstOrDefault(); + + acc.Hero.NextHeroSend = DateTime.Now.AddSeconds(adventure.DurationSeconds * 2); + + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.TTwars: + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/{adventure.Ref}"); + + var startButton = acc.Wb.Html.GetElementbyId("start"); + if (startButton == null) + { + //Hero is probably out of the village. + this.NextExecute = DateTime.Now.AddMinutes(10); + return TaskRes.Executed; + } + await DriverHelper.ClickById(acc, "start"); + break; + + case Classificator.ServerVersionEnum.T4_5: + string script = $"var div = document.getElementById('{adventure.AdventureId}');"; + script += $"div.children[0].submit();"; + await DriverHelper.ExecuteScript(acc, script); + + // Check hero outgoing time + var outTime = HeroParser.GetHeroArrival(acc.Wb.Html); + // At least 1.5x longer (if hero has Large map) + acc.Hero.NextHeroSend = DateTime.Now + TimeSpan.FromTicks((long)(outTime.Ticks * 1.5)); + break; + } + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/TTWars/TTWarsBuyAdventure.cs b/TbsCore/Tasks/Others/TTWarsBuyAdventure.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/TTWars/TTWarsBuyAdventure.cs rename to TbsCore/Tasks/Others/TTWarsBuyAdventure.cs index f2c02a3e5..f1640da24 100644 --- a/TbsCore/Tasks/LowLevel/TTWars/TTWarsBuyAdventure.cs +++ b/TbsCore/Tasks/Others/TTWarsBuyAdventure.cs @@ -1,23 +1,23 @@ -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; - -namespace TbsCore.Tasks.LowLevel -{ - public class TTWarsBuyAdventure : BotTask - { - public override async Task Execute(Account acc) - { - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/hero.php?t=3"); - - var button = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("buyAdventure")); - if (button == null) - { - acc.Logger.Warning("No button 'Buy' button found, perhaps you are not on vip ttwars server?"); - return TaskRes.Executed; - } - acc.Wb.ExecuteScript($"document.getElementById('{button.Id}').click()"); //Excgabge resources button - return TaskRes.Executed; - } - } +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; + +namespace TbsCore.Tasks.LowLevel +{ + public class TTWarsBuyAdventure : BotTask + { + public override async Task Execute(Account acc) + { + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/hero.php?t=3"); + + var button = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("buyAdventure")); + if (button == null) + { + acc.Logger.Warning("No button 'Buy' button found, perhaps you are not on vip ttwars server?"); + return TaskRes.Executed; + } + acc.Wb.ExecuteScript($"document.getElementById('{button.Id}').click()"); //Excgabge resources button + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/TTWars/TTWarsExpandStorage.cs b/TbsCore/Tasks/Others/TTWarsExpandStorage.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/TTWars/TTWarsExpandStorage.cs rename to TbsCore/Tasks/Others/TTWarsExpandStorage.cs index 781c84a51..a4b692f47 100644 --- a/TbsCore/Tasks/LowLevel/TTWars/TTWarsExpandStorage.cs +++ b/TbsCore/Tasks/Others/TTWarsExpandStorage.cs @@ -1,42 +1,42 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Helpers; - -namespace TbsCore.Tasks.LowLevel -{ - public class TTWarsExpandStorage : BotTask - { - public int Seconds { get; set; } - public int Times { get; set; } - - public override async Task Execute(Account acc) - { - var building = Vill.Build.Buildings.FirstOrDefault(x => x.Level > 0 && (x.Type == Classificator.BuildingEnum.Warehouse || x.Type == Classificator.BuildingEnum.Granary)); - if (building != null) await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?id={building.Id}"); - - //expand the storage - //TODO change this with GOLD options -> expand storage button (like buy res/animals) - var button = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("increaseStorage")); - if (button == null) - { - acc.Logger.Warning("No such button, are you sure you are on TTWars vip/unl?"); - return TaskRes.Executed; - } - acc.Wb.ExecuteScript($"document.getElementById('{button.Id}').click()"); //exapand the storage button - - if (this.Times > 1) - { - //repeat the task - this.NextExecute = DateTime.Now.AddSeconds(2); - this.Times--; - } - else if (this.Seconds > 0) - { - this.NextExecute = DateTime.Now.AddSeconds(this.Seconds); - } - return TaskRes.Executed; - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Helpers; + +namespace TbsCore.Tasks.LowLevel +{ + public class TTWarsExpandStorage : BotTask + { + public int Seconds { get; set; } + public int Times { get; set; } + + public override async Task Execute(Account acc) + { + var building = Vill.Build.Buildings.FirstOrDefault(x => x.Level > 0 && (x.Type == Classificator.BuildingEnum.Warehouse || x.Type == Classificator.BuildingEnum.Granary)); + if (building != null) await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?id={building.Id}"); + + //expand the storage + //TODO change this with GOLD options -> expand storage button (like buy res/animals) + var button = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("increaseStorage")); + if (button == null) + { + acc.Logger.Warning("No such button, are you sure you are on TTWars vip/unl?"); + return TaskRes.Executed; + } + acc.Wb.ExecuteScript($"document.getElementById('{button.Id}').click()"); //exapand the storage button + + if (this.Times > 1) + { + //repeat the task + this.NextExecute = DateTime.Now.AddSeconds(2); + this.Times--; + } + else if (this.Seconds > 0) + { + this.NextExecute = DateTime.Now.AddSeconds(this.Seconds); + } + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/TTWars/TTWarsGetAnimals.cs b/TbsCore/Tasks/Others/TTWarsGetAnimals.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/TTWars/TTWarsGetAnimals.cs rename to TbsCore/Tasks/Others/TTWarsGetAnimals.cs index d9769aa45..766028db2 100644 --- a/TbsCore/Tasks/LowLevel/TTWars/TTWarsGetAnimals.cs +++ b/TbsCore/Tasks/Others/TTWarsGetAnimals.cs @@ -1,37 +1,37 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; - -namespace TbsCore.Tasks.LowLevel -{ - public class TTWarsGetAnimals : BotTask - { - public override async Task Execute(Account acc) - { - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/dorf1.php"); - - Random rnd = new Random(); - int sec = rnd.Next(725, 740); - acc.Tasks.Add(new TTWarsGetAnimals() { ExecuteAt = DateTime.Now.AddSeconds(sec), Vill = AccountHelper.GetMainVillage(acc) }); - - //Open payment wizard on tab Plus features (where you can buy stuff with gold) - var script = "window.fireEvent('startPaymentWizard', {data:{activeTab: 'paymentFeatures'}});"; - await DriverHelper.ExecuteScript(acc, script); - - script = "$$('.paymentWizardMenu').addClass('hide');$$('.buyGoldInfoStep').removeClass('active');$$('.buyGoldInfoStep#3').addClass('active');$$('.paymentWizardMenu#buyAnimal').removeClass('hide');"; - await DriverHelper.ExecuteScript(acc, script); - - var buy = acc.Wb.Html.DocumentNode.Descendants().First(x => x.HasClass("buyAnimal5")); - //wb.FindElementById(buy.Id).Click(); - //var buy = acc.Wb.Html.DocumentNode.SelectNodes("//*[text()[contains(., '3000')]]")[0]; - //while (buy.Name != "button") buy = buy.ParentNode; - //var buyId = buy.GetAttributeValue("id", ""); - acc.Wb.ExecuteScript($"document.getElementById('{buy.Id}').click()"); - - //Clicking on buy button DOES NOT trigger a page reloag. We have to do it manually. - return TaskRes.Executed; - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; + +namespace TbsCore.Tasks.LowLevel +{ + public class TTWarsGetAnimals : BotTask + { + public override async Task Execute(Account acc) + { + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/dorf1.php"); + + Random rnd = new Random(); + int sec = rnd.Next(725, 740); + acc.Tasks.Add(new TTWarsGetAnimals() { ExecuteAt = DateTime.Now.AddSeconds(sec), Vill = AccountHelper.GetMainVillage(acc) }); + + //Open payment wizard on tab Plus features (where you can buy stuff with gold) + var script = "window.fireEvent('startPaymentWizard', {data:{activeTab: 'paymentFeatures'}});"; + await DriverHelper.ExecuteScript(acc, script); + + script = "$$('.paymentWizardMenu').addClass('hide');$$('.buyGoldInfoStep').removeClass('active');$$('.buyGoldInfoStep#3').addClass('active');$$('.paymentWizardMenu#buyAnimal').removeClass('hide');"; + await DriverHelper.ExecuteScript(acc, script); + + var buy = acc.Wb.Html.DocumentNode.Descendants().First(x => x.HasClass("buyAnimal5")); + //wb.FindElementById(buy.Id).Click(); + //var buy = acc.Wb.Html.DocumentNode.SelectNodes("//*[text()[contains(., '3000')]]")[0]; + //while (buy.Name != "button") buy = buy.ParentNode; + //var buyId = buy.GetAttributeValue("id", ""); + acc.Wb.ExecuteScript($"document.getElementById('{buy.Id}').click()"); + + //Clicking on buy button DOES NOT trigger a page reloag. We have to do it manually. + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/TTWars/TTWarsGetRes.cs b/TbsCore/Tasks/Others/TTWarsGetRes.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/TTWars/TTWarsGetRes.cs rename to TbsCore/Tasks/Others/TTWarsGetRes.cs index 711af6668..51f4a2332 100644 --- a/TbsCore/Tasks/LowLevel/TTWars/TTWarsGetRes.cs +++ b/TbsCore/Tasks/Others/TTWarsGetRes.cs @@ -1,46 +1,46 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; - -namespace TbsCore.Tasks.LowLevel -{ - public class TTWarsGetRes : BotTask - { - public override async Task Execute(Account acc) - { - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/dorf2.php"); - - Random rnd = new Random(); - int sec = rnd.Next(370, 380); - acc.Tasks.Add(new TTWarsGetRes() { ExecuteAt = DateTime.Now.AddSeconds(sec), Vill = AccountHelper.GetMainVillage(acc) }); - acc.Tasks.Add(new TrainExchangeRes() { ExecuteAt = DateTime.Now.AddSeconds(sec + 5), troop = acc.Villages[0].Troops.TroopToTrain ?? Classificator.TroopsEnum.Hero, Vill = Vill }); - acc.Tasks.Add(new TrainTroops() - { - ExecuteAt = DateTime.Now.AddSeconds(sec + 9), - Troop = acc.Villages[0].Troops.TroopToTrain ?? Classificator.TroopsEnum.Hero, - Vill = Vill, - HighSpeedServer = true - }); - - var script = "window.fireEvent('startPaymentWizard', {data:{activeTab: 'paymentFeatures'}});"; - await DriverHelper.ExecuteScript(acc, script); - - script = "$$('.paymentWizardMenu').addClass('hide');$$('.buyGoldInfoStep').removeClass('active');$$('.buyGoldInfoStep#2').addClass('active');$$('.paymentWizardMenu#buyResources').removeClass('hide');"; - await DriverHelper.ExecuteScript(acc, script); - - //gold prosButton buyResources6 - //gold prosButton buyAnimal5 - var buy = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("buyResources6")); - if (buy == null) - { - acc.Logger.Warning("Can't find the button with class buyResources6. Are you sure you are on vip/unl TTWars server?"); - return TaskRes.Executed; - } - var buyId = buy.GetAttributeValue("id", ""); - acc.Wb.ExecuteScript($"document.getElementById('{buyId}').click()"); - return TaskRes.Executed; - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; + +namespace TbsCore.Tasks.LowLevel +{ + public class TTWarsGetRes : BotTask + { + public override async Task Execute(Account acc) + { + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/dorf2.php"); + + Random rnd = new Random(); + int sec = rnd.Next(370, 380); + acc.Tasks.Add(new TTWarsGetRes() { ExecuteAt = DateTime.Now.AddSeconds(sec), Vill = AccountHelper.GetMainVillage(acc) }); + acc.Tasks.Add(new TrainExchangeRes() { ExecuteAt = DateTime.Now.AddSeconds(sec + 5), troop = acc.Villages[0].Troops.TroopToTrain ?? Classificator.TroopsEnum.Hero, Vill = Vill }); + acc.Tasks.Add(new TrainTroops() + { + ExecuteAt = DateTime.Now.AddSeconds(sec + 9), + Troop = acc.Villages[0].Troops.TroopToTrain ?? Classificator.TroopsEnum.Hero, + Vill = Vill, + HighSpeedServer = true + }); + + var script = "window.fireEvent('startPaymentWizard', {data:{activeTab: 'paymentFeatures'}});"; + await DriverHelper.ExecuteScript(acc, script); + + script = "$$('.paymentWizardMenu').addClass('hide');$$('.buyGoldInfoStep').removeClass('active');$$('.buyGoldInfoStep#2').addClass('active');$$('.paymentWizardMenu#buyResources').removeClass('hide');"; + await DriverHelper.ExecuteScript(acc, script); + + //gold prosButton buyResources6 + //gold prosButton buyAnimal5 + var buy = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("buyResources6")); + if (buy == null) + { + acc.Logger.Warning("Can't find the button with class buyResources6. Are you sure you are on vip/unl TTWars server?"); + return TaskRes.Executed; + } + var buyId = buy.GetAttributeValue("id", ""); + acc.Wb.ExecuteScript($"document.getElementById('{buyId}').click()"); + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/TTWars/TTWarsPlusAndBoost.cs b/TbsCore/Tasks/Others/TTWarsPlusAndBoost.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/TTWars/TTWarsPlusAndBoost.cs rename to TbsCore/Tasks/Others/TTWarsPlusAndBoost.cs index 83509dd25..116c54778 100644 --- a/TbsCore/Tasks/LowLevel/TTWars/TTWarsPlusAndBoost.cs +++ b/TbsCore/Tasks/Others/TTWarsPlusAndBoost.cs @@ -1,27 +1,27 @@ -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Helpers; - -namespace TbsCore.Tasks.LowLevel -{ - //since "extend automatically" doesn't work on TTWars, this task will automatically prolong plus account / +25% resource boost - public class TTWarsPlusAndBoost : BotTask - { - public override async Task Execute(Account acc) - { - var leftBar = acc.Wb.Html.GetElementbyId("sidebarBeforeContent"); - var button = leftBar.Descendants("button").FirstOrDefault(x => x.HasClass("gold")); - if (button == null) - { - return TaskRes.Executed; - } - var buttonid = button.GetAttributeValue("id", ""); - await Task.Delay(AccountHelper.Delay(acc) / 3); - - acc.Wb.ExecuteScript($"document.getElementById('{buttonid}').click()"); //boost production - - return TaskRes.Executed; - } - } +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Helpers; + +namespace TbsCore.Tasks.LowLevel +{ + //since "extend automatically" doesn't work on TTWars, this task will automatically prolong plus account / +25% resource boost + public class TTWarsPlusAndBoost : BotTask + { + public override async Task Execute(Account acc) + { + var leftBar = acc.Wb.Html.GetElementbyId("sidebarBeforeContent"); + var button = leftBar.Descendants("button").FirstOrDefault(x => x.HasClass("gold")); + if (button == null) + { + return TaskRes.Executed; + } + var buttonid = button.GetAttributeValue("id", ""); + await Task.Delay(AccountHelper.Delay(acc) / 3); + + acc.Wb.ExecuteScript($"document.getElementById('{buttonid}').click()"); //boost production + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/Celebration.cs b/TbsCore/Tasks/Sim/Celebration.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/Celebration.cs rename to TbsCore/Tasks/Sim/Celebration.cs index 7d506593d..9341b497d 100644 --- a/TbsCore/Tasks/LowLevel/Celebration.cs +++ b/TbsCore/Tasks/Sim/Celebration.cs @@ -1,244 +1,244 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.VillageModels; -using TbsCore.TravianData; -using TbsCore.Parsers; -using static TbsCore.Helpers.Classificator; -using HtmlAgilityPack; -using OpenQA.Selenium; - -namespace TbsCore.Tasks.LowLevel -{ - public class Celebration : BotTask - { - private bool bigCeleb; - private readonly Random rand = new Random(); - - public override async Task Execute(Account acc) - { - StopFlag = false; - - do - { - if (StopFlag) return TaskRes.Executed; - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Moving into TownHall ...", this); - var result = await MoveIntoBuilding(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Check current celebration ..."); - var result = IsFreeSlot(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Check enough resource ...", this); - var result = IsEnoughRes(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Click start celebration ...", this); - var result = await StartCelebration(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Post check ...", this); - var result = PostCheck(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - } while (true); - } - - private async Task MoveIntoBuilding(Account acc) - { - acc.Logger.Information($"Checking current village ..."); - { - var result = await NavigationHelper.SwitchVillage(acc, Vill); - if (!result) - { - Retry(acc, "Cannot switch village"); - return false; - } - } - - await AccountHelper.DelayWait(acc); - - { - var result = await NavigationHelper.EnterBuilding(acc, Vill, BuildingEnum.TownHall); - if (!result) - { - Retry(acc, "Cannot enter TownHall"); - return false; - } - } - return true; - } - - private bool IsFreeSlot(Account acc) - { - HtmlNode underProgressNode; - switch (acc.AccInfo.ServerVersion) - { - case ServerVersionEnum.TTwars: - underProgressNode = acc.Wb.Html.GetElementbyId("under_progress"); - break; - - case ServerVersionEnum.T4_5: - { - var content = acc.Wb.Html.GetElementbyId("content"); - underProgressNode = content.Descendants("table").FirstOrDefault(x => x.HasClass("under_progress")); - } - break; - - default: - underProgressNode = null; - break; - } - - if (underProgressNode == null) return true; // No celebration is under progress - - var celebrationEnd = DateTime.Now + TimeParser.ParseTimer(underProgressNode); - Vill.Expansion.CelebrationEnd = celebrationEnd; - NextExecute = celebrationEnd; - acc.Logger.Information($"There is under progress celebration. [{celebrationEnd}]"); - StopFlag = true; - return false; - } - - private bool IsEnoughRes(Account acc) - { - var townHall = Vill.Build.Buildings.FirstOrDefault(x => x.Type == BuildingEnum.TownHall); - if (townHall == null) - { - Retry(acc, "Townhall disappear from database"); - return false; - } - - bigCeleb = Vill.Expansion.Celebrations == CelebrationEnum.Big && 10 <= townHall.Level; - var arrayCost = MiscCost.CelebrationCost(bigCeleb); - var cost = ResourcesHelper.ArrayToResources(arrayCost); - acc.Logger.Information($"Need {cost}"); - if (ResourcesHelper.IsEnoughRes(Vill, arrayCost)) - { - return true; - } - - if (ResourcesHelper.IsStorageTooLow(acc, Vill, cost)) - { - var building = Vill.Build.CurrentlyBuilding.FirstOrDefault(x => x.Building == BuildingEnum.Warehouse || x.Building == BuildingEnum.Granary); - if (building == null) - { - acc.Logger.Warning($"Storage is too low. Added storage upgrade."); - } - else - { - acc.Logger.Warning($"Storage is too low. Next building will be contructed after {building.Building} - level {building.Level} complete. ({NextExecute})"); - NextExecute = TimeHelper.RanDelay(acc, building.Duration); - } - } - else - { - var stillNeededRes = ResourcesHelper.SubtractResources(cost.ToArray(), Vill.Res.Stored.Resources.ToArray(), true); - acc.Logger.Information($"Not enough resources to build. Still need {stillNeededRes}"); - acc.Logger.Information($"Bot will try finish the task later"); - DateTime enoughRes = TimeHelper.EnoughResToUpgrade(Vill, stillNeededRes); - NextExecute = TimeHelper.RanDelay(acc, enoughRes); - } - - StopFlag = true; - return false; - } - - private async Task StartCelebration(Account acc) - { - var nodes = acc.Wb.Html.DocumentNode.Descendants("div").Where(x => x.HasClass("research")); - - var node = bigCeleb ? nodes.LastOrDefault() : nodes.FirstOrDefault(); - if (node == null) - { - Retry(acc, "Cannot find button box"); - return false; - } - - var button = node.Descendants("button").FirstOrDefault(); - if (node == null) - { - Retry(acc, "Cannot find button"); - return false; - } - - var elementButton = acc.Wb.Driver.FindElement(By.XPath(button.XPath)); - elementButton.Click(); - await Task.Delay(rand.Next(1200, 2000)); - return true; - } - - private bool PostCheck(Account acc) - { - HtmlNode underProgressNode; - switch (acc.AccInfo.ServerVersion) - { - case ServerVersionEnum.TTwars: - underProgressNode = acc.Wb.Html.GetElementbyId("under_progress"); - break; - - case ServerVersionEnum.T4_5: - { - var content = acc.Wb.Html.GetElementbyId("content"); - underProgressNode = content.Descendants("table").FirstOrDefault(x => x.HasClass("under_progress")); - } - break; - - default: - underProgressNode = null; - break; - } - - if (underProgressNode == null) return true; // No celebration is under progress - - var celebrationEnd = DateTime.Now + TimeParser.ParseTimer(underProgressNode); - Vill.Expansion.CelebrationEnd = celebrationEnd; - NextExecute = celebrationEnd; - StopFlag = true; - return false; - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.VillageModels; +using TbsCore.TravianData; +using TbsCore.Parsers; +using static TbsCore.Helpers.Classificator; +using HtmlAgilityPack; +using OpenQA.Selenium; + +namespace TbsCore.Tasks.LowLevel +{ + public class Celebration : BotTask + { + private bool bigCeleb; + private readonly Random rand = new Random(); + + public override async Task Execute(Account acc) + { + StopFlag = false; + + do + { + if (StopFlag) return TaskRes.Executed; + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Moving into TownHall ...", this); + var result = await MoveIntoBuilding(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Check current celebration ..."); + var result = IsFreeSlot(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Check enough resource ...", this); + var result = IsEnoughRes(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Click start celebration ...", this); + var result = await StartCelebration(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Post check ...", this); + var result = PostCheck(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + } while (true); + } + + private async Task MoveIntoBuilding(Account acc) + { + acc.Logger.Information($"Checking current village ..."); + { + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (!result) + { + Retry(acc, "Cannot switch village"); + return false; + } + } + + await AccountHelper.DelayWait(acc); + + { + var result = await NavigationHelper.EnterBuilding(acc, Vill, BuildingEnum.TownHall); + if (!result) + { + Retry(acc, "Cannot enter TownHall"); + return false; + } + } + return true; + } + + private bool IsFreeSlot(Account acc) + { + HtmlNode underProgressNode; + switch (acc.AccInfo.ServerVersion) + { + case ServerVersionEnum.TTwars: + underProgressNode = acc.Wb.Html.GetElementbyId("under_progress"); + break; + + case ServerVersionEnum.T4_5: + { + var content = acc.Wb.Html.GetElementbyId("content"); + underProgressNode = content.Descendants("table").FirstOrDefault(x => x.HasClass("under_progress")); + } + break; + + default: + underProgressNode = null; + break; + } + + if (underProgressNode == null) return true; // No celebration is under progress + + var celebrationEnd = DateTime.Now + TimeParser.ParseTimer(underProgressNode); + Vill.Expansion.CelebrationEnd = celebrationEnd; + NextExecute = celebrationEnd; + acc.Logger.Information($"There is under progress celebration. [{celebrationEnd}]"); + StopFlag = true; + return false; + } + + private bool IsEnoughRes(Account acc) + { + var townHall = Vill.Build.Buildings.FirstOrDefault(x => x.Type == BuildingEnum.TownHall); + if (townHall == null) + { + Retry(acc, "Townhall disappear from database"); + return false; + } + + bigCeleb = Vill.Expansion.Celebrations == CelebrationEnum.Big && 10 <= townHall.Level; + var arrayCost = MiscCost.CelebrationCost(bigCeleb); + var cost = ResourcesHelper.ArrayToResources(arrayCost); + acc.Logger.Information($"Need {cost}"); + if (ResourcesHelper.IsEnoughRes(Vill, arrayCost)) + { + return true; + } + + if (ResourcesHelper.IsStorageTooLow(acc, Vill, cost)) + { + var building = Vill.Build.CurrentlyBuilding.FirstOrDefault(x => x.Building == BuildingEnum.Warehouse || x.Building == BuildingEnum.Granary); + if (building == null) + { + acc.Logger.Warning($"Storage is too low. Added storage upgrade."); + } + else + { + acc.Logger.Warning($"Storage is too low. Next building will be contructed after {building.Building} - level {building.Level} complete. ({NextExecute})"); + NextExecute = TimeHelper.RanDelay(acc, building.Duration); + } + } + else + { + var stillNeededRes = ResourcesHelper.SubtractResources(cost.ToArray(), Vill.Res.Stored.Resources.ToArray(), true); + acc.Logger.Information($"Not enough resources to build. Still need {stillNeededRes}"); + acc.Logger.Information($"Bot will try finish the task later"); + DateTime enoughRes = TimeHelper.EnoughResToUpgrade(Vill, stillNeededRes); + NextExecute = TimeHelper.RanDelay(acc, enoughRes); + } + + StopFlag = true; + return false; + } + + private async Task StartCelebration(Account acc) + { + var nodes = acc.Wb.Html.DocumentNode.Descendants("div").Where(x => x.HasClass("research")); + + var node = bigCeleb ? nodes.LastOrDefault() : nodes.FirstOrDefault(); + if (node == null) + { + Retry(acc, "Cannot find button box"); + return false; + } + + var button = node.Descendants("button").FirstOrDefault(); + if (node == null) + { + Retry(acc, "Cannot find button"); + return false; + } + + var elementButton = acc.Wb.Driver.FindElement(By.XPath(button.XPath)); + elementButton.Click(); + await Task.Delay(rand.Next(1200, 2000)); + return true; + } + + private bool PostCheck(Account acc) + { + HtmlNode underProgressNode; + switch (acc.AccInfo.ServerVersion) + { + case ServerVersionEnum.TTwars: + underProgressNode = acc.Wb.Html.GetElementbyId("under_progress"); + break; + + case ServerVersionEnum.T4_5: + { + var content = acc.Wb.Html.GetElementbyId("content"); + underProgressNode = content.Descendants("table").FirstOrDefault(x => x.HasClass("under_progress")); + } + break; + + default: + underProgressNode = null; + break; + } + + if (underProgressNode == null) return true; // No celebration is under progress + + var celebrationEnd = DateTime.Now + TimeParser.ParseTimer(underProgressNode); + Vill.Expansion.CelebrationEnd = celebrationEnd; + NextExecute = celebrationEnd; + StopFlag = true; + return false; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/ClaimBeginnerTask.cs b/TbsCore/Tasks/Sim/ClaimBeginnerTask.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/ClaimBeginnerTask.cs rename to TbsCore/Tasks/Sim/ClaimBeginnerTask.cs index 4cd365e34..d6aa6dd8a 100644 --- a/TbsCore/Tasks/LowLevel/ClaimBeginnerTask.cs +++ b/TbsCore/Tasks/Sim/ClaimBeginnerTask.cs @@ -1,37 +1,37 @@ -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.SideBarModels; - -namespace TbsCore.Tasks.LowLevel -{ - public class ClaimBeginnerTask : BotTask - { - public Quest QuestToClaim { get; set; } - - public override async Task Execute(Account acc) - { - var script = $"document.getElementById('mentorTaskList').querySelector('[data-questid=\"{this.QuestToClaim.Id}\"]').click();"; - await DriverHelper.ExecuteScript(acc, script); - await Task.Delay(AccountHelper.Delay(acc) * 2); - - string buttonId = ""; - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.T4_5: - buttonId = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.GetAttributeValue("questid", "") == this.QuestToClaim.Id).Id; - break; - - case Classificator.ServerVersionEnum.TTwars: - buttonId = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("questButtonNext"))?.Id; - break; - } - - await DriverHelper.ClickById(acc, buttonId); - await DriverHelper.WaitPageLoaded(acc); // Optional - - return TaskRes.Executed; - } - } +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.SideBarModels; + +namespace TbsCore.Tasks.LowLevel +{ + public class ClaimBeginnerTask : BotTask + { + public Quest QuestToClaim { get; set; } + + public override async Task Execute(Account acc) + { + var script = $"document.getElementById('mentorTaskList').querySelector('[data-questid=\"{this.QuestToClaim.Id}\"]').click();"; + await DriverHelper.ExecuteScript(acc, script); + await Task.Delay(AccountHelper.Delay(acc) * 2); + + string buttonId = ""; + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.T4_5: + buttonId = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.GetAttributeValue("questid", "") == this.QuestToClaim.Id).Id; + break; + + case Classificator.ServerVersionEnum.TTwars: + buttonId = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("questButtonNext"))?.Id; + break; + } + + await DriverHelper.ClickById(acc, buttonId); + await DriverHelper.WaitPageLoaded(acc); // Optional + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/ClaimBeginnerTask2021.cs b/TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/ClaimBeginnerTask2021.cs rename to TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs index bfc819d0b..a161e16b5 100644 --- a/TbsCore/Tasks/LowLevel/ClaimBeginnerTask2021.cs +++ b/TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs @@ -1,46 +1,46 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; - -namespace TbsCore.Tasks.LowLevel -{ - public class ClaimBeginnerTask2021 : BotTask - { - public override async Task Execute(Account acc) - { - // Claim village-wide rewards - await DriverHelper.ClickById(acc, "questmasterButton"); - await ClaimRewards(acc); - - if (acc.Wb.Html - .GetElementbyId("sidebarBoxQuestmaster")? - .Descendants()? - .Any(x => x.HasClass("newQuestSpeechBubble")) ?? false) - { - // Claim account-wide rewards - await DriverHelper.ClickByClassName(acc, "tabItem", 1); - await ClaimRewards(acc); - } - - acc.Tasks.Add(new HeroUpdateInfo() { ExecuteAt = DateTime.Now }); - - return TaskRes.Executed; - } - - private async Task ClaimRewards(Account acc) - { - int count = 0; - do - { - await DriverHelper.ClickByClassName(acc, "collect", log: false); - await Task.Delay(AccountHelper.Delay(acc)); - acc.Wb.UpdateHtml(); - count++; - if (count > 50) break; // infinite loop ( i dont think there is over 50 quest waiting bot ) - } - while (acc.Wb.Html.DocumentNode.Descendants("button").Any(x => x.HasClass("collect"))); - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; + +namespace TbsCore.Tasks.LowLevel +{ + public class ClaimBeginnerTask2021 : BotTask + { + public override async Task Execute(Account acc) + { + // Claim village-wide rewards + await DriverHelper.ClickById(acc, "questmasterButton"); + await ClaimRewards(acc); + + if (acc.Wb.Html + .GetElementbyId("sidebarBoxQuestmaster")? + .Descendants()? + .Any(x => x.HasClass("newQuestSpeechBubble")) ?? false) + { + // Claim account-wide rewards + await DriverHelper.ClickByClassName(acc, "tabItem", 1); + await ClaimRewards(acc); + } + + acc.Tasks.Add(new HeroUpdateInfo() { ExecuteAt = DateTime.Now }); + + return TaskRes.Executed; + } + + private async Task ClaimRewards(Account acc) + { + int count = 0; + do + { + await DriverHelper.ClickByClassName(acc, "collect", log: false); + await Task.Delay(AccountHelper.Delay(acc)); + acc.Wb.UpdateHtml(); + count++; + if (count > 50) break; // infinite loop ( i dont think there is over 50 quest waiting bot ) + } + while (acc.Wb.Html.DocumentNode.Descendants("button").Any(x => x.HasClass("collect"))); + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/ClaimDailyTask.cs b/TbsCore/Tasks/Sim/ClaimDailyTask.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/ClaimDailyTask.cs rename to TbsCore/Tasks/Sim/ClaimDailyTask.cs index af79994c7..efa63b726 100644 --- a/TbsCore/Tasks/LowLevel/ClaimDailyTask.cs +++ b/TbsCore/Tasks/Sim/ClaimDailyTask.cs @@ -1,32 +1,32 @@ -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; - -namespace TbsCore.Tasks.LowLevel -{ - public class ClaimDailyTask : BotTask - { - public override async Task Execute(Account acc) - { - - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.TTwars: - await NavigationHelper.ToDorf2(acc); - await DriverHelper.ExecuteScript(acc, "Travian.Game.Quest.openTodoListDialog('', true);"); - var script = "var dialog = document.getElementById('dialogContent');"; - script += "dialog.getElementsByClassName('active')[0].click();"; - await DriverHelper.ExecuteScript(acc, script); - break; - - case Classificator.ServerVersionEnum.T4_5: - await NavigationHelper.MainNavigate(acc, NavigationHelper.MainNavigationButton.DailyQuests); - await DriverHelper.ClickByClassName(acc, "rewardReady"); - break; - } - await DriverHelper.ClickByClassName(acc, "questButtonGainReward"); - - return TaskRes.Executed; - } - } +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; + +namespace TbsCore.Tasks.LowLevel +{ + public class ClaimDailyTask : BotTask + { + public override async Task Execute(Account acc) + { + + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.TTwars: + await NavigationHelper.ToDorf2(acc); + await DriverHelper.ExecuteScript(acc, "Travian.Game.Quest.openTodoListDialog('', true);"); + var script = "var dialog = document.getElementById('dialogContent');"; + script += "dialog.getElementsByClassName('active')[0].click();"; + await DriverHelper.ExecuteScript(acc, script); + break; + + case Classificator.ServerVersionEnum.T4_5: + await NavigationHelper.MainNavigate(acc, NavigationHelper.MainNavigationButton.DailyQuests); + await DriverHelper.ClickByClassName(acc, "rewardReady"); + break; + } + await DriverHelper.ClickByClassName(acc, "questButtonGainReward"); + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/DemolishBuilding.cs b/TbsCore/Tasks/Sim/DemolishBuilding.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/DemolishBuilding.cs rename to TbsCore/Tasks/Sim/DemolishBuilding.cs index 5e822fb2e..6aed16650 100644 --- a/TbsCore/Tasks/LowLevel/DemolishBuilding.cs +++ b/TbsCore/Tasks/Sim/DemolishBuilding.cs @@ -1,89 +1,89 @@ -using HtmlAgilityPack; -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.VillageModels; -using TbsCore.Parsers; - -namespace TbsCore.Tasks.LowLevel -{ - public class DemolishBuilding : BotTask - { - public override async Task Execute(Account acc) - { - // First navigate to dorf2 and then to the main building, to make sure the currently demolish list is refreshed - if (!await NavigationHelper.EnterBuilding(acc, Vill, Classificator.BuildingEnum.MainBuilding)) - return TaskRes.Executed; - - if (Vill.Build.DemolishTasks.Count == 0) return TaskRes.Executed; //No more demolish tasks - - var id = BuildingToDemolish(Vill, acc.Wb.Html); - - if (id == null) return TaskRes.Executed; //No more demolish tasks - - await DriverHelper.WriteById(acc, "demolish", id); - await DriverHelper.ClickById(acc, "btn_demolish"); - - this.NextExecute = TimeHelper.RanDelay(acc, await NextDemolishTime(acc)); - - return TaskRes.Executed; - } - - private int? BuildingToDemolish(Village vill, HtmlDocument htmlDoc) - { - if (vill.Build.DemolishTasks.Count == 0) return null; - - var task = vill.Build.DemolishTasks.FirstOrDefault(); - - var building = htmlDoc.GetElementbyId("demolish").Descendants("option") - .FirstOrDefault(x => - x.GetAttributeValue("value", "") == task.BuildingId.ToString() - ); - - //If this building doesn't exist or is below/on the correct level, find next building to demolish - if (building == null) - { - vill.Build.DemolishTasks.Remove(task); - return BuildingToDemolish(vill, htmlDoc); - } - - var option = building.InnerText; - var lvl = option.Split(' ').LastOrDefault(); - - //TODO: Check if localized building name match - //var buildingName = Parser.RemoveNumeric(option.Split('.')[1]).Trim(); - //var optionBuilding = Localizations.BuildingFromString(buildingName); - - if (int.Parse(lvl) <= task.Level /*|| optionBuilding != task.Building*/) - { - vill.Build.DemolishTasks.Remove(task); - return BuildingToDemolish(vill, htmlDoc); - } - return task.BuildingId; - } - - /// - /// Checks demolish time. - /// - /// account - public async Task NextDemolishTime(Account acc) - { - // Is this needed? - if (!await NavigationHelper.EnterBuilding(acc, Vill, Classificator.BuildingEnum.MainBuilding)) - return DateTime.Now; - - var table = acc.Wb.Html.GetElementbyId("demolish"); - - if (table == null) //No building is being demolished - { - return DateTime.Now; - } - //Re-execute the demolish building task - - var time = DateTime.Now.Add(TimeParser.ParseTimer(table)); - return time.AddSeconds(2); - } - } +using HtmlAgilityPack; +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.VillageModels; +using TbsCore.Parsers; + +namespace TbsCore.Tasks.LowLevel +{ + public class DemolishBuilding : BotTask + { + public override async Task Execute(Account acc) + { + // First navigate to dorf2 and then to the main building, to make sure the currently demolish list is refreshed + if (!await NavigationHelper.EnterBuilding(acc, Vill, Classificator.BuildingEnum.MainBuilding)) + return TaskRes.Executed; + + if (Vill.Build.DemolishTasks.Count == 0) return TaskRes.Executed; //No more demolish tasks + + var id = BuildingToDemolish(Vill, acc.Wb.Html); + + if (id == null) return TaskRes.Executed; //No more demolish tasks + + await DriverHelper.WriteById(acc, "demolish", id); + await DriverHelper.ClickById(acc, "btn_demolish"); + + this.NextExecute = TimeHelper.RanDelay(acc, await NextDemolishTime(acc)); + + return TaskRes.Executed; + } + + private int? BuildingToDemolish(Village vill, HtmlDocument htmlDoc) + { + if (vill.Build.DemolishTasks.Count == 0) return null; + + var task = vill.Build.DemolishTasks.FirstOrDefault(); + + var building = htmlDoc.GetElementbyId("demolish").Descendants("option") + .FirstOrDefault(x => + x.GetAttributeValue("value", "") == task.BuildingId.ToString() + ); + + //If this building doesn't exist or is below/on the correct level, find next building to demolish + if (building == null) + { + vill.Build.DemolishTasks.Remove(task); + return BuildingToDemolish(vill, htmlDoc); + } + + var option = building.InnerText; + var lvl = option.Split(' ').LastOrDefault(); + + //TODO: Check if localized building name match + //var buildingName = Parser.RemoveNumeric(option.Split('.')[1]).Trim(); + //var optionBuilding = Localizations.BuildingFromString(buildingName); + + if (int.Parse(lvl) <= task.Level /*|| optionBuilding != task.Building*/) + { + vill.Build.DemolishTasks.Remove(task); + return BuildingToDemolish(vill, htmlDoc); + } + return task.BuildingId; + } + + /// + /// Checks demolish time. + /// + /// account + public async Task NextDemolishTime(Account acc) + { + // Is this needed? + if (!await NavigationHelper.EnterBuilding(acc, Vill, Classificator.BuildingEnum.MainBuilding)) + return DateTime.Now; + + var table = acc.Wb.Html.GetElementbyId("demolish"); + + if (table == null) //No building is being demolished + { + return DateTime.Now; + } + //Re-execute the demolish building task + + var time = DateTime.Now.Add(TimeParser.ParseTimer(table)); + return time.AddSeconds(2); + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/ExtendProtection.cs b/TbsCore/Tasks/Sim/ExtendProtection.cs similarity index 96% rename from TbsCore/Tasks/LowLevel/ExtendProtection.cs rename to TbsCore/Tasks/Sim/ExtendProtection.cs index 0450181ac..13e870a67 100644 --- a/TbsCore/Tasks/LowLevel/ExtendProtection.cs +++ b/TbsCore/Tasks/Sim/ExtendProtection.cs @@ -1,17 +1,17 @@ -using System.Threading.Tasks; -using TbsCore.Models.AccModels; - -namespace TbsCore.Tasks.LowLevel -{ - /// - /// Extend beginners protection - /// - public class ExtendProtection : BotTask - { - public override async Task Execute(Account acc) - { - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/options/game?extendBeginnersProtection"); - return TaskRes.Executed; - } - } +using System.Threading.Tasks; +using TbsCore.Models.AccModels; + +namespace TbsCore.Tasks.LowLevel +{ + /// + /// Extend beginners protection + /// + public class ExtendProtection : BotTask + { + public override async Task Execute(Account acc) + { + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/options/game?extendBeginnersProtection"); + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/FindVillageToSettle.cs b/TbsCore/Tasks/Sim/FindVillageToSettle.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/FindVillageToSettle.cs rename to TbsCore/Tasks/Sim/FindVillageToSettle.cs index 0c3c1b81d..54d3b02f7 100644 --- a/TbsCore/Tasks/LowLevel/FindVillageToSettle.cs +++ b/TbsCore/Tasks/Sim/FindVillageToSettle.cs @@ -1,61 +1,61 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.MapModels; -using TbsCore.Models.VillageModels; -using TbsCore.Parsers; - -namespace TbsCore.Tasks.LowLevel -{ - public class FindVillageToSettle : BotTask - { - public override async Task Execute(Account acc) - { - await NavigationHelper.ToMap(acc); - - var mainVill = AccountHelper.GetMainVillage(acc); - - var mapTiles = await MapHelper.GetMapTiles(acc, mainVill.Coordinates); - - Coordinates closesCoords = GetClosestCoordinates(acc, mapTiles); - if (closesCoords == null) return TaskRes.Retry; - - acc.NewVillages.Locations.Add(new NewVillage() - { - Coordinates = closesCoords, - Name = NewVillageHelper.GenerateName(acc), - }); - - return TaskRes.Executed; - } - - private Coordinates GetClosestCoordinates(Account acc, List tiles) - { - var mainVill = AccountHelper.GetMainVillage(acc); - var closesCoords = new Coordinates(); - var closest = 1000.0; - foreach (var tile in tiles) - { - if (tile.Title == null || !tile.Title.StartsWith("{k.vt}")) continue; - - // Check if village type meets criteria - if (acc.NewVillages.Types.Count != 0) - { - var num = (int)Parser.RemoveNonNumeric(tile.Title.Split('f')[1]); - var type = (Classificator.VillTypeEnum)(num); - if (!acc.NewVillages.Types.Any(x => x == type)) continue; - } - - var distance = mainVill.Coordinates.CalculateDistance(acc, tile.Coordinates); - if (distance < closest) - { - closest = distance; - closesCoords = tile.Coordinates; - } - } - return closesCoords; - } - } +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.MapModels; +using TbsCore.Models.VillageModels; +using TbsCore.Parsers; + +namespace TbsCore.Tasks.LowLevel +{ + public class FindVillageToSettle : BotTask + { + public override async Task Execute(Account acc) + { + await NavigationHelper.ToMap(acc); + + var mainVill = AccountHelper.GetMainVillage(acc); + + var mapTiles = await MapHelper.GetMapTiles(acc, mainVill.Coordinates); + + Coordinates closesCoords = GetClosestCoordinates(acc, mapTiles); + if (closesCoords == null) return TaskRes.Retry; + + acc.NewVillages.Locations.Add(new NewVillage() + { + Coordinates = closesCoords, + Name = NewVillageHelper.GenerateName(acc), + }); + + return TaskRes.Executed; + } + + private Coordinates GetClosestCoordinates(Account acc, List tiles) + { + var mainVill = AccountHelper.GetMainVillage(acc); + var closesCoords = new Coordinates(); + var closest = 1000.0; + foreach (var tile in tiles) + { + if (tile.Title == null || !tile.Title.StartsWith("{k.vt}")) continue; + + // Check if village type meets criteria + if (acc.NewVillages.Types.Count != 0) + { + var num = (int)Parser.RemoveNonNumeric(tile.Title.Split('f')[1]); + var type = (Classificator.VillTypeEnum)(num); + if (!acc.NewVillages.Types.Any(x => x == type)) continue; + } + + var distance = mainVill.Coordinates.CalculateDistance(acc, tile.Coordinates); + if (distance < closest) + { + closest = distance; + closesCoords = tile.Coordinates; + } + } + return closesCoords; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/InstaUpgrade.cs b/TbsCore/Tasks/Sim/InstaUpgrade.cs similarity index 96% rename from TbsCore/Tasks/LowLevel/InstaUpgrade.cs rename to TbsCore/Tasks/Sim/InstaUpgrade.cs index 0d1a0743b..06d1071e7 100644 --- a/TbsCore/Tasks/LowLevel/InstaUpgrade.cs +++ b/TbsCore/Tasks/Sim/InstaUpgrade.cs @@ -1,42 +1,42 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; - -namespace TbsCore.Tasks.LowLevel -{ - /// - /// Instantly upgrade currently building - /// - public class InstaUpgrade : BotTask - { - public override async Task Execute(Account acc) - { - await NavigationHelper.ToDorf1(acc); - - var finishClass = acc.Wb.Html.DocumentNode - .Descendants("div") - .FirstOrDefault(x => x.HasClass("finishNow")); - var button = finishClass.Descendants("button").FirstOrDefault(); - await DriverHelper.ClickById(acc, button.Id); - - var dialog = acc.Wb.Html.GetElementbyId("finishNowDialog"); - var useButton = dialog.Descendants("button").FirstOrDefault(); - await DriverHelper.ClickById(acc, useButton.Id); - - // Execute next build task right away - var task = acc.Tasks.FindTask(typeof(UpgradeBuilding), Vill); - - if (task != null) - { - task.ExecuteAt = DateTime.Now; - acc.Tasks.ReOrder(); - } - - await DriverHelper.WaitPageLoaded(acc); - - return TaskRes.Executed; - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; + +namespace TbsCore.Tasks.LowLevel +{ + /// + /// Instantly upgrade currently building + /// + public class InstaUpgrade : BotTask + { + public override async Task Execute(Account acc) + { + await NavigationHelper.ToDorf1(acc); + + var finishClass = acc.Wb.Html.DocumentNode + .Descendants("div") + .FirstOrDefault(x => x.HasClass("finishNow")); + var button = finishClass.Descendants("button").FirstOrDefault(); + await DriverHelper.ClickById(acc, button.Id); + + var dialog = acc.Wb.Html.GetElementbyId("finishNowDialog"); + var useButton = dialog.Descendants("button").FirstOrDefault(); + await DriverHelper.ClickById(acc, useButton.Id); + + // Execute next build task right away + var task = acc.Tasks.FindTask(typeof(UpgradeBuilding), Vill); + + if (task != null) + { + task.ExecuteAt = DateTime.Now; + acc.Tasks.ReOrder(); + } + + await DriverHelper.WaitPageLoaded(acc); + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/NPC.cs b/TbsCore/Tasks/Sim/NPC.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/NPC.cs rename to TbsCore/Tasks/Sim/NPC.cs index eee1c1cbe..4372b89a1 100644 --- a/TbsCore/Tasks/LowLevel/NPC.cs +++ b/TbsCore/Tasks/Sim/NPC.cs @@ -1,76 +1,76 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Parsers; -using HtmlAgilityPack; - -namespace TbsCore.Tasks.LowLevel -{ - public class NPC : BotTask - { - public override async Task Execute(Account acc) - { - if (!await NavigationHelper.ToMarketplace(acc, Vill, NavigationHelper.MarketplaceTab.Managenment)) - return TaskRes.Executed; - - var npcMerchant = acc.Wb.Html.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass("npcMerchant")); - var npcButton = npcMerchant.Descendants("button").FirstOrDefault(x => x.HasClass("gold")); - - // Exchange resources button - await DriverHelper.ClickById(acc, npcButton.Id); - - //wait npc form show - var timeout = DateTime.Now.AddSeconds(10); - - HtmlNode remainRes = null; - do - { - await Task.Delay(1000); - - acc.Wb.UpdateHtml(); - remainRes = acc.Wb.Html.GetElementbyId("remain"); - - if (timeout < DateTime.Now) - { - acc.Logger.Warning($"NPC in village {Vill.Name} is time out. Retry after 3 mins"); - this.NextExecute = DateTime.Now.AddMinutes(3); - return TaskRes.Executed; - } - } - while (remainRes == null); - - var resSum = Parser.RemoveNonNumeric(remainRes.InnerText); - var targetRes = MarketHelper.NpcTargetResources(Vill, resSum); - - if (!Vill.Market.Npc.NpcIfOverflow && MarketHelper.NpcWillOverflow(Vill, targetRes)) - { - acc.Logger.Warning($"NPC in village {Vill.Name} will be overflow. Stop NPC"); - return TaskRes.Executed; - } - for (int i = 0; i < 4; i++) - { - //await acc.Wb.Driver.FindElementById($"m2[{i}]").Write(targetRes[i]); - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.TTwars: - await DriverHelper.ExecuteScript(acc, $"document.getElementById('m2[{i}]').value='{targetRes[i]}'"); - break; - - case Classificator.ServerVersionEnum.T4_5: - await DriverHelper.ExecuteScript(acc, $"document.getElementsByName('desired{i}')[0].value='{targetRes[i]}'"); - break; - } - } - - var submit = acc.Wb.Html.GetElementbyId("submitText"); - var distribute = submit.Descendants("button").FirstOrDefault(); - - await DriverHelper.ClickById(acc, distribute.Id); - await DriverHelper.ClickById(acc, "npc_market_button"); - - return TaskRes.Executed; - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Parsers; +using HtmlAgilityPack; + +namespace TbsCore.Tasks.LowLevel +{ + public class NPC : BotTask + { + public override async Task Execute(Account acc) + { + if (!await NavigationHelper.ToMarketplace(acc, Vill, NavigationHelper.MarketplaceTab.Managenment)) + return TaskRes.Executed; + + var npcMerchant = acc.Wb.Html.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass("npcMerchant")); + var npcButton = npcMerchant.Descendants("button").FirstOrDefault(x => x.HasClass("gold")); + + // Exchange resources button + await DriverHelper.ClickById(acc, npcButton.Id); + + //wait npc form show + var timeout = DateTime.Now.AddSeconds(10); + + HtmlNode remainRes = null; + do + { + await Task.Delay(1000); + + acc.Wb.UpdateHtml(); + remainRes = acc.Wb.Html.GetElementbyId("remain"); + + if (timeout < DateTime.Now) + { + acc.Logger.Warning($"NPC in village {Vill.Name} is time out. Retry after 3 mins"); + this.NextExecute = DateTime.Now.AddMinutes(3); + return TaskRes.Executed; + } + } + while (remainRes == null); + + var resSum = Parser.RemoveNonNumeric(remainRes.InnerText); + var targetRes = MarketHelper.NpcTargetResources(Vill, resSum); + + if (!Vill.Market.Npc.NpcIfOverflow && MarketHelper.NpcWillOverflow(Vill, targetRes)) + { + acc.Logger.Warning($"NPC in village {Vill.Name} will be overflow. Stop NPC"); + return TaskRes.Executed; + } + for (int i = 0; i < 4; i++) + { + //await acc.Wb.Driver.FindElementById($"m2[{i}]").Write(targetRes[i]); + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.TTwars: + await DriverHelper.ExecuteScript(acc, $"document.getElementById('m2[{i}]').value='{targetRes[i]}'"); + break; + + case Classificator.ServerVersionEnum.T4_5: + await DriverHelper.ExecuteScript(acc, $"document.getElementsByName('desired{i}')[0].value='{targetRes[i]}'"); + break; + } + } + + var submit = acc.Wb.Html.GetElementbyId("submitText"); + var distribute = submit.Descendants("button").FirstOrDefault(); + + await DriverHelper.ClickById(acc, distribute.Id); + await DriverHelper.ClickById(acc, "npc_market_button"); + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/SendSettlers.cs b/TbsCore/Tasks/Sim/SendSettlers.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/SendSettlers.cs rename to TbsCore/Tasks/Sim/SendSettlers.cs index 403ed1242..8cd90f669 100644 --- a/TbsCore/Tasks/LowLevel/SendSettlers.cs +++ b/TbsCore/Tasks/Sim/SendSettlers.cs @@ -1,79 +1,79 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Parsers; - -namespace TbsCore.Tasks.LowLevel -{ - public class SendSettlers : BotTask - { - public override async Task Execute(Account acc) - { - // Check if the account has enough culture points - if (acc.AccInfo.CulturePoints.MaxVillages <= acc.AccInfo.CulturePoints.VillageCount) - { - // TODO: this shouldn't be here? - acc.Logger.Warning("Don't have enough culture points"); - this.Vill.Expansion.ExpansionAvailable = true; - return TaskRes.Executed; - } - - if (acc.NewVillages.Locations.Count == 0) - { - if (acc.NewVillages.AutoFindVillages) // Find new village to settle - { - acc.Tasks.Add(new FindVillageToSettle() - { - Vill = AccountHelper.GetMainVillage(acc), - ExecuteAt = DateTime.MinValue.AddHours(10), - Priority = TaskPriority.High - }, true); - this.NextExecute = DateTime.MinValue.AddHours(11); - } - - return TaskRes.Executed; - } - - await NavigationHelper.ToMap(acc); - await Task.Delay(AccountHelper.Delay(acc) * 3); - - var newVillage = acc.NewVillages.Locations.FirstOrDefault(); - - //acc.NewVillage.NewVillages.Remove(coords); //remove it after settling and changing the vill name?? - string kid = newVillage.Coordinates.GetKid(acc).ToString(); - - string url = $"{acc.AccInfo.ServerUrl}/build.php?id=39&tt=2"; - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.TTwars: - // https://low4.ttwars.com/build.php?id=39&tt=2&kid=7274&a=6 - url += $"&kid={kid}&a=6"; - break; - - case Classificator.ServerVersionEnum.T4_5: - // https://tx3.travian.com/build.php?id=39&tt=2&mapid=123&s=1&gid=16 - url += $"&mapid={kid}&s=1&gid=16"; - break; - } - await acc.Wb.Navigate(url); - - // Check if we have enough resource - var costNode = acc.Wb.Html.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass("resourceWrapper")); - var cost = ResourceParser.GetResourceCost(costNode); - if (!ResourcesHelper.IsEnoughRes(Vill, cost.ToArray())) - { - ResourcesHelper.NotEnoughRes(acc, Vill, cost, this); - return TaskRes.Executed; - } - - if (!await DriverHelper.ClickById(acc, "btn_ok")) return TaskRes.Retry; - - newVillage.SettlersSent = true; - this.Vill.Expansion.ExpansionAvailable = false; - - return TaskRes.Executed; - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Parsers; + +namespace TbsCore.Tasks.LowLevel +{ + public class SendSettlers : BotTask + { + public override async Task Execute(Account acc) + { + // Check if the account has enough culture points + if (acc.AccInfo.CulturePoints.MaxVillages <= acc.AccInfo.CulturePoints.VillageCount) + { + // TODO: this shouldn't be here? + acc.Logger.Warning("Don't have enough culture points"); + this.Vill.Expansion.ExpansionAvailable = true; + return TaskRes.Executed; + } + + if (acc.NewVillages.Locations.Count == 0) + { + if (acc.NewVillages.AutoFindVillages) // Find new village to settle + { + acc.Tasks.Add(new FindVillageToSettle() + { + Vill = AccountHelper.GetMainVillage(acc), + ExecuteAt = DateTime.MinValue.AddHours(10), + Priority = TaskPriority.High + }, true); + this.NextExecute = DateTime.MinValue.AddHours(11); + } + + return TaskRes.Executed; + } + + await NavigationHelper.ToMap(acc); + await Task.Delay(AccountHelper.Delay(acc) * 3); + + var newVillage = acc.NewVillages.Locations.FirstOrDefault(); + + //acc.NewVillage.NewVillages.Remove(coords); //remove it after settling and changing the vill name?? + string kid = newVillage.Coordinates.GetKid(acc).ToString(); + + string url = $"{acc.AccInfo.ServerUrl}/build.php?id=39&tt=2"; + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.TTwars: + // https://low4.ttwars.com/build.php?id=39&tt=2&kid=7274&a=6 + url += $"&kid={kid}&a=6"; + break; + + case Classificator.ServerVersionEnum.T4_5: + // https://tx3.travian.com/build.php?id=39&tt=2&mapid=123&s=1&gid=16 + url += $"&mapid={kid}&s=1&gid=16"; + break; + } + await acc.Wb.Navigate(url); + + // Check if we have enough resource + var costNode = acc.Wb.Html.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass("resourceWrapper")); + var cost = ResourceParser.GetResourceCost(costNode); + if (!ResourcesHelper.IsEnoughRes(Vill, cost.ToArray())) + { + ResourcesHelper.NotEnoughRes(acc, Vill, cost, this); + return TaskRes.Executed; + } + + if (!await DriverHelper.ClickById(acc, "btn_ok")) return TaskRes.Retry; + + newVillage.SettlersSent = true; + this.Vill.Expansion.ExpansionAvailable = false; + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/TrainSettlers.cs b/TbsCore/Tasks/Sim/TrainSettlers.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/TrainSettlers.cs rename to TbsCore/Tasks/Sim/TrainSettlers.cs index 8d8d7e053..a420ee00f 100644 --- a/TbsCore/Tasks/LowLevel/TrainSettlers.cs +++ b/TbsCore/Tasks/Sim/TrainSettlers.cs @@ -1,301 +1,301 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.TravianData; -using TbsCore.Helpers; -using TbsCore.Parsers; -using static TbsCore.Helpers.Classificator; - -namespace TbsCore.Tasks.LowLevel -{ - public class TrainSettlers : BotTask - { - private TroopsEnum settlerId; - - public override async Task Execute(Account acc) - { - settlerId = TroopsData.TribeSettler(acc.AccInfo.Tribe); - StopFlag = false; - do - { - if (StopFlag) return TaskRes.Executed; - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Checking building ...", this); - var result = await BuildingRequired(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Enter building ...", this); - var result = await EnterBuilding(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Checking settlers condition ...", this); - var result = EnoughSettlers(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Checking settler current number ...", this); - var result = UpdateSettlersAmount(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Checking resource ...", this); - var result = await IsEnoughRes(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Enter amount ... ", this); - await DriverHelper.WriteByName(acc, "t10", 1); - acc.Logger.Information("Click train button ... ", this); - await Task.Delay(900); - await DriverHelper.ClickById(acc, "s1"); - } - } - while (true); - } - - private void SendSettlersTask(Account acc) - { - acc.Wb.UpdateHtml(); - var training = TroopsHelper.TrainingDuration(acc.Wb.Html); - if (training < DateTime.Now) training = DateTime.Now; - training = training.AddSeconds(5); - - acc.Logger.Information($"Bot will (try to) send settlers in {TimeHelper.InSeconds(training)} sec"); - - acc.Tasks.Add(new SendSettlers() - { - ExecuteAt = training, - Vill = this.Vill, - // For high speed servers, you want to train settlers asap - Priority = 1000 < acc.AccInfo.ServerSpeed ? TaskPriority.High : TaskPriority.Medium, - }, true); - } - - private async Task BuildingRequired(Account acc) - { - var building = Vill.Build.Buildings.FirstOrDefault(x => - x.Type == BuildingEnum.Residence || - x.Type == BuildingEnum.Palace || - x.Type == BuildingEnum.CommandCenter - ); - if (building == null) - { - acc.Logger.Information($"Cannot found residence/palace or command center in {Vill.Name}"); - acc.Logger.Information($"Update dorf2 to confirm"); - { - var resultSwitch = await NavigationHelper.SwitchVillage(acc, Vill); - if (!resultSwitch) - { - Retry(acc, "Cannot switch village"); - return false; - } - } - { - var resultSwitch = await NavigationHelper.ToDorf2(acc); - if (!resultSwitch) - { - Retry(acc, "Cannot enter dorf2"); - return false; - } - } - - building = Vill.Build.Buildings.FirstOrDefault(x => - x.Type == BuildingEnum.Residence || - x.Type == BuildingEnum.Palace || - x.Type == BuildingEnum.CommandCenter - ); - - if (building == null) - { - acc.Logger.Information($"Confirm there isn't residence/palace or command center in {Vill.Name}"); - StopFlag = true; - return false; - } - } - return true; - } - - private async Task EnterBuilding(Account acc) - { - return await NavigationHelper.ToGovernmentBuilding(acc, Vill, NavigationHelper.ResidenceTab.Train); - } - - private bool EnoughSettlers(Account acc) - { - var troopNode = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass($"u{(int)settlerId}")); - - if (troopNode == null) - { - acc.Logger.Information("No new settler can be trained, probably because 3 settlers are already (being) trained"); - SendSettlersTask(acc); - StopFlag = true; - return false; - } - return true; - } - - private bool UpdateSettlersAmount(Account acc) - { - HtmlAgilityPack.HtmlNode nodeSettler = null; - switch (acc.AccInfo.ServerVersion) - { - case ServerVersionEnum.TTwars: - { - var troopNode = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("u" + (int)settlerId)); - while (!troopNode.HasClass("details")) troopNode = troopNode.ParentNode; - nodeSettler = troopNode; - } - break; - - case ServerVersionEnum.T4_5: - { - var troopBox = acc.Wb.Html.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass($"troop{(int)settlerId}") && x.HasClass("innerTroopWrapper")); - if (troopBox == null) - { - Retry(acc, "Cannot find settler box"); - return false; - } - nodeSettler = troopBox; - } - break; - - default: - break; - } - var divTit = nodeSettler.Descendants("div").FirstOrDefault(x => x.HasClass("tit")); - if (divTit == null) - { - Retry(acc, "Cannot find Settler title"); - return false; - } - var spanPresent = divTit.Descendants("span").FirstOrDefault(); - if (spanPresent == null) - { - Retry(acc, "Cannot find Settler present number"); - return false; - } - - Vill.Troops.Settlers = (int)Parser.RemoveNonNumeric(spanPresent.InnerText); - acc.Logger.Information($"Update Settler present number: {Vill.Troops.Settlers}"); - - acc.Wb.UpdateHtml(); - var training = TroopsParser.GetTroopsCurrentlyTraining(acc.Wb.Html); - var countTraning = 0; - foreach (var item in training) - { - if (item.Troop == settlerId) countTraning += item.TrainNumber; - } - acc.Logger.Information($"Update Settler training number: {countTraning}"); - - if (Vill.Troops.Settlers + countTraning >= 3) - { - acc.Logger.Information($"Have enough settler."); - StopFlag = true; - if (acc.NewVillages.AutoSettleNewVillages) - { - SendSettlersTask(acc); - } - return false; - } - return true; - } - - private async Task IsEnoughRes(Account acc) - { - var troopBox = acc.Wb.Html.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass($"troop{(int)settlerId}") && x.HasClass("innerTroopWrapper")); - if (troopBox == null) - { - Retry(acc, "Cannot find settler box"); - return false; - } - var resWrapper = troopBox.Descendants("div").FirstOrDefault(x => x.HasClass("resourceWrapper")); - if (resWrapper == null) - { - Retry(acc, "Cannot find resource list"); - return false; - } - var cost = ResourceParser.GetResourceCost(resWrapper); - - acc.Logger.Information($"Need {cost}"); - - if (!ResourcesHelper.IsEnoughRes(Vill, cost.ToArray())) - { - if (ResourcesHelper.IsStorageTooLow(acc, Vill, cost)) - { - acc.Logger.Warning($"Storage is too low. Added storage upgrade."); - StopFlag = true; - return false; - } - - var stillNeededRes = ResourcesHelper.SubtractResources(cost.ToArray(), Vill.Res.Stored.Resources.ToArray(), true); - acc.Logger.Information("Not enough resources to train."); - if (Vill.Settings.UseHeroRes && acc.AccInfo.ServerVersion == ServerVersionEnum.T4_5) // Only T4.5 has resources in hero inv - { - var heroRes = HeroHelper.GetHeroResources(acc); - - if (ResourcesHelper.IsEnoughRes(heroRes, stillNeededRes)) - { - // If we have enough hero res for our task, execute the task - // right after hero equip finishes - acc.Logger.Information("Bot will use resource from hero inventory"); - - var heroEquipTask = ResourcesHelper.UseHeroResources(acc, Vill, ref stillNeededRes, heroRes); - await heroEquipTask.Execute(acc); - return false; - } - } - - acc.Logger.Information($"Bot will try finish the task later"); - DateTime enoughRes = TimeHelper.EnoughResToUpgrade(Vill, stillNeededRes); - NextExecute = TimeHelper.RanDelay(acc, enoughRes); - StopFlag = true; - return false; - } - return true; - } - } +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.TravianData; +using TbsCore.Helpers; +using TbsCore.Parsers; +using static TbsCore.Helpers.Classificator; + +namespace TbsCore.Tasks.LowLevel +{ + public class TrainSettlers : BotTask + { + private TroopsEnum settlerId; + + public override async Task Execute(Account acc) + { + settlerId = TroopsData.TribeSettler(acc.AccInfo.Tribe); + StopFlag = false; + do + { + if (StopFlag) return TaskRes.Executed; + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Checking building ...", this); + var result = await BuildingRequired(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Enter building ...", this); + var result = await EnterBuilding(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Checking settlers condition ...", this); + var result = EnoughSettlers(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Checking settler current number ...", this); + var result = UpdateSettlersAmount(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Checking resource ...", this); + var result = await IsEnoughRes(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Enter amount ... ", this); + await DriverHelper.WriteByName(acc, "t10", 1); + acc.Logger.Information("Click train button ... ", this); + await Task.Delay(900); + await DriverHelper.ClickById(acc, "s1"); + } + } + while (true); + } + + private void SendSettlersTask(Account acc) + { + acc.Wb.UpdateHtml(); + var training = TroopsHelper.TrainingDuration(acc.Wb.Html); + if (training < DateTime.Now) training = DateTime.Now; + training = training.AddSeconds(5); + + acc.Logger.Information($"Bot will (try to) send settlers in {TimeHelper.InSeconds(training)} sec"); + + acc.Tasks.Add(new SendSettlers() + { + ExecuteAt = training, + Vill = this.Vill, + // For high speed servers, you want to train settlers asap + Priority = 1000 < acc.AccInfo.ServerSpeed ? TaskPriority.High : TaskPriority.Medium, + }, true); + } + + private async Task BuildingRequired(Account acc) + { + var building = Vill.Build.Buildings.FirstOrDefault(x => + x.Type == BuildingEnum.Residence || + x.Type == BuildingEnum.Palace || + x.Type == BuildingEnum.CommandCenter + ); + if (building == null) + { + acc.Logger.Information($"Cannot found residence/palace or command center in {Vill.Name}"); + acc.Logger.Information($"Update dorf2 to confirm"); + { + var resultSwitch = await NavigationHelper.SwitchVillage(acc, Vill); + if (!resultSwitch) + { + Retry(acc, "Cannot switch village"); + return false; + } + } + { + var resultSwitch = await NavigationHelper.ToDorf2(acc); + if (!resultSwitch) + { + Retry(acc, "Cannot enter dorf2"); + return false; + } + } + + building = Vill.Build.Buildings.FirstOrDefault(x => + x.Type == BuildingEnum.Residence || + x.Type == BuildingEnum.Palace || + x.Type == BuildingEnum.CommandCenter + ); + + if (building == null) + { + acc.Logger.Information($"Confirm there isn't residence/palace or command center in {Vill.Name}"); + StopFlag = true; + return false; + } + } + return true; + } + + private async Task EnterBuilding(Account acc) + { + return await NavigationHelper.ToGovernmentBuilding(acc, Vill, NavigationHelper.ResidenceTab.Train); + } + + private bool EnoughSettlers(Account acc) + { + var troopNode = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass($"u{(int)settlerId}")); + + if (troopNode == null) + { + acc.Logger.Information("No new settler can be trained, probably because 3 settlers are already (being) trained"); + SendSettlersTask(acc); + StopFlag = true; + return false; + } + return true; + } + + private bool UpdateSettlersAmount(Account acc) + { + HtmlAgilityPack.HtmlNode nodeSettler = null; + switch (acc.AccInfo.ServerVersion) + { + case ServerVersionEnum.TTwars: + { + var troopNode = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("u" + (int)settlerId)); + while (!troopNode.HasClass("details")) troopNode = troopNode.ParentNode; + nodeSettler = troopNode; + } + break; + + case ServerVersionEnum.T4_5: + { + var troopBox = acc.Wb.Html.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass($"troop{(int)settlerId}") && x.HasClass("innerTroopWrapper")); + if (troopBox == null) + { + Retry(acc, "Cannot find settler box"); + return false; + } + nodeSettler = troopBox; + } + break; + + default: + break; + } + var divTit = nodeSettler.Descendants("div").FirstOrDefault(x => x.HasClass("tit")); + if (divTit == null) + { + Retry(acc, "Cannot find Settler title"); + return false; + } + var spanPresent = divTit.Descendants("span").FirstOrDefault(); + if (spanPresent == null) + { + Retry(acc, "Cannot find Settler present number"); + return false; + } + + Vill.Troops.Settlers = (int)Parser.RemoveNonNumeric(spanPresent.InnerText); + acc.Logger.Information($"Update Settler present number: {Vill.Troops.Settlers}"); + + acc.Wb.UpdateHtml(); + var training = TroopsParser.GetTroopsCurrentlyTraining(acc.Wb.Html); + var countTraning = 0; + foreach (var item in training) + { + if (item.Troop == settlerId) countTraning += item.TrainNumber; + } + acc.Logger.Information($"Update Settler training number: {countTraning}"); + + if (Vill.Troops.Settlers + countTraning >= 3) + { + acc.Logger.Information($"Have enough settler."); + StopFlag = true; + if (acc.NewVillages.AutoSettleNewVillages) + { + SendSettlersTask(acc); + } + return false; + } + return true; + } + + private async Task IsEnoughRes(Account acc) + { + var troopBox = acc.Wb.Html.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass($"troop{(int)settlerId}") && x.HasClass("innerTroopWrapper")); + if (troopBox == null) + { + Retry(acc, "Cannot find settler box"); + return false; + } + var resWrapper = troopBox.Descendants("div").FirstOrDefault(x => x.HasClass("resourceWrapper")); + if (resWrapper == null) + { + Retry(acc, "Cannot find resource list"); + return false; + } + var cost = ResourceParser.GetResourceCost(resWrapper); + + acc.Logger.Information($"Need {cost}"); + + if (!ResourcesHelper.IsEnoughRes(Vill, cost.ToArray())) + { + if (ResourcesHelper.IsStorageTooLow(acc, Vill, cost)) + { + acc.Logger.Warning($"Storage is too low. Added storage upgrade."); + StopFlag = true; + return false; + } + + var stillNeededRes = ResourcesHelper.SubtractResources(cost.ToArray(), Vill.Res.Stored.Resources.ToArray(), true); + acc.Logger.Information("Not enough resources to train."); + if (Vill.Settings.UseHeroRes && acc.AccInfo.ServerVersion == ServerVersionEnum.T4_5) // Only T4.5 has resources in hero inv + { + var heroRes = HeroHelper.GetHeroResources(acc); + + if (ResourcesHelper.IsEnoughRes(heroRes, stillNeededRes)) + { + // If we have enough hero res for our task, execute the task + // right after hero equip finishes + acc.Logger.Information("Bot will use resource from hero inventory"); + + var heroEquipTask = ResourcesHelper.UseHeroResources(acc, Vill, ref stillNeededRes, heroRes); + await heroEquipTask.Execute(acc); + return false; + } + } + + acc.Logger.Information($"Bot will try finish the task later"); + DateTime enoughRes = TimeHelper.EnoughResToUpgrade(Vill, stillNeededRes); + NextExecute = TimeHelper.RanDelay(acc, enoughRes); + StopFlag = true; + return false; + } + return true; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/UpgradeBuilding.cs b/TbsCore/Tasks/Sim/UpgradeBuilding.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/UpgradeBuilding.cs rename to TbsCore/Tasks/Sim/UpgradeBuilding.cs index 999a01d16..cf2d88000 100644 --- a/TbsCore/Tasks/LowLevel/UpgradeBuilding.cs +++ b/TbsCore/Tasks/Sim/UpgradeBuilding.cs @@ -1,645 +1,645 @@ -using HtmlAgilityPack; -using OpenQA.Selenium; -using OpenQA.Selenium.Interactions; -using System; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.BuildingModels; -using TbsCore.Models.VillageModels; -using TbsCore.Parsers; -using TbsCore.TravianData; - -using static TbsCore.Helpers.Classificator; - -namespace TbsCore.Tasks.LowLevel -{ - public class UpgradeBuilding : BotTask - { - private BuildingTask _buildingTask; - private readonly Random rand = new Random(); - private bool construct = false; - private bool result = true; - - public override async Task Execute(Account acc) - { - StopFlag = false; - do - { - if (StopFlag) return TaskRes.Executed; - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Choose building to build...", this); - _buildingTask = await ChooseTask(acc); - if (StopFlag) return TaskRes.Executed; - if (_buildingTask == null) continue; - if (_buildingTask.TaskType == BuildingType.AutoUpgradeResFields) - { - acc.Logger.Information($"{_buildingTask.ResourceType} - Level {_buildingTask.Level} is chosen", this); - } - else - { - acc.Logger.Information($"{_buildingTask.Building} - Level {_buildingTask.Level} is chosen", this); - } - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Check condition ...", this); - var result = TaskTypeCondition(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Check Free crop ...", this); - result = await FreeCropCondition(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - - // Fast building for TTWars - if (acc.AccInfo.ServerVersion == ServerVersionEnum.TTwars && !_buildingTask.ConstructNew) - { - acc.Logger.Information("Try using TTWars fast build method", this); - await Task.Delay(AccountHelper.Delay(acc)); - var fastUpgrade = await TTWarsTryFastUpgrade(acc, $"{acc.AccInfo.ServerUrl}/build.php?id={_buildingTask.BuildingId}"); - if (fastUpgrade) continue; - acc.Logger.Information("Using TTWars fast build method failed. Continue normal method", this); - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Moving to building ...", this); - await MoveIntoBuilding(acc); - if (StopFlag) return TaskRes.Executed; - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - - { - acc.Logger.Information("Check correct page ...", this); - var result = IsContructPage(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - { - acc.Logger.Information("Check enough resource ...", this); - var result = await IsEnoughRes(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - - { - var result = await Update(acc); - if (!result) return TaskRes.Executed; - } - { - bool result; - if (construct) - { - acc.Logger.Information("Starting construct ...", this); - result = await Construct(acc); - } - else - { - acc.Logger.Information("Starting upgrade ...", this); - result = await Upgrade(acc); - } - if (StopFlag) return TaskRes.Executed; - if (!result) continue; - } - await DriverHelper.WaitPageChange(acc, "dorf"); - } - while (true); - } - - /// - /// Building isn't constructed yet - construct it - /// - /// Account - /// TaskResult - private async Task Construct(Account acc) - { - acc.Wb.UpdateHtml(); - var node = acc.Wb.Html.GetElementbyId($"contract_building{(int)_buildingTask.Building}"); - var button = node.Descendants("button").FirstOrDefault(x => x.HasClass("new")); - - // Check for prerequisites - if (button == null) - { - Retry(acc, "Button disappear."); - return false; - } - - await AccountHelper.DelayWait(acc); - var element = acc.Wb.Driver.FindElement(By.XPath(button.XPath)); - if (element == null) - { - Retry(acc, "Button disappear."); - return false; - } - element.Click(); - _buildingTask.ConstructNew = false; - - if (_buildingTask.Level == 1) - { - RemoveCurrentTask(); - } - - return true; - } - - /// - /// Building is already constructed, upgrade it - /// - /// Account - /// TaskResult - private async Task Upgrade(Account acc) - { - acc.Wb.UpdateHtml(); - HtmlNode node = acc.Wb.Html.GetElementbyId("build"); - (var buildingEnum, var lvl) = InfrastructureParser.UpgradeBuildingGetInfo(node); - - if (buildingEnum == BuildingEnum.Site || lvl == -1) - { - acc.Logger.Warning($"Can't upgrade building {_buildingTask.Building} in village {Vill.Name}. Will be removed from the queue."); - RemoveCurrentTask(); - return false; - } - - // Basic task already on/above desired level, don't upgrade further - var building = Vill.Build.Buildings.FirstOrDefault(x => x.Id == this._buildingTask.BuildingId); - lvl = building.Level; - // Check if building is under construction - if (building.UnderConstruction) - { - // Check currently building - var cb = Vill.Build.CurrentlyBuilding.OrderByDescending(x => x.Level).FirstOrDefault(x => x.Location == building.Id); - if (cb != null && lvl < cb.Level) lvl = cb.Level; - } - - if (lvl >= _buildingTask.Level) - { - acc.Logger.Information($"{_buildingTask.Building} is already level {lvl} in village {Vill.Name}. Will be removed from the queue."); - RemoveCurrentTask(); - return false; - } - - var container = acc.Wb.Html.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass("upgradeButtonsContainer")); - var buttons = container?.Descendants("button"); - if (buttons == null) - { - acc.Logger.Information($"We wanted to upgrade {_buildingTask.Building}, but no 'upgrade' button was found! Url={acc.Wb.CurrentUrl}", this); - return false; - } - - var errorMessage = acc.Wb.Html.GetElementbyId("build") - .Descendants("div") - .FirstOrDefault(x => x.HasClass("upgradeBuilding"))? - .Descendants("div")? - .FirstOrDefault(x => x.HasClass("errorMessage")); - HtmlNode upgradeButton = buttons.FirstOrDefault(x => x.HasClass("build")); - - if (upgradeButton == null) - { - Retry(acc, $"We wanted to upgrade {_buildingTask.Building}, but no 'upgrade' button was found!"); - return false; - } - - // Not enough resources? - if (acc.AccInfo.ServerVersion == ServerVersionEnum.T4_5 && errorMessage != null) - { - Retry(acc, $"We wanted to upgrade {_buildingTask.Building}, but there was an error message:\n{errorMessage.InnerText}"); - return false; - } - - var buildDuration = InfrastructureParser.GetBuildDuration(container, acc.AccInfo.ServerVersion); - - acc.Logger.Information("Complete checking"); - acc.Logger.Information($"Upgrading {_buildingTask.Building} to level {lvl + 1} in {Vill.Name}"); - - var watchAd = false; - if (acc.AccInfo.ServerVersion == ServerVersionEnum.T4_5 && buildDuration.TotalMinutes > acc.Settings.WatchAdAbove) - { - acc.Logger.Information("Try using watch ads upgrade button"); - watchAd = await TryFastUpgrade(acc); - } - - if (!watchAd) - { - await AccountHelper.DelayWait(acc); - acc.Logger.Information("Using normal upgrade button"); - - upgradeButton = buttons.FirstOrDefault(x => x.HasClass("build")); - - var element = acc.Wb.Driver.FindElement(By.XPath(upgradeButton.XPath)); - if (element == null) - { - Retry(acc, "Button disappear."); - return false; - } - element.Click(); - } - - acc.Logger.Information($"Upgraded {_buildingTask.Building} to level {lvl + 1} in {Vill.Name}"); - if (_buildingTask.Level == lvl + 1) - { - RemoveCurrentTask(); - } - return true; - } - - private void RemoveCurrentTask() => Vill.Build.Tasks.Remove(this._buildingTask); - - private void PostTaskCheckDorf(Account acc) - { - // Check if residence is getting upgraded to level 10 => train settlers - var cbResidence = Vill.Build - .CurrentlyBuilding - .FirstOrDefault(x => (x.Building == BuildingEnum.Residence || - x.Building == BuildingEnum.Palace || - x.Building == BuildingEnum.CommandCenter) && - x.Level == 10); - if (cbResidence != null && - acc.NewVillages.AutoSettleNewVillages && - Vill.Troops.Settlers == 0) - { - acc.Tasks.Add( - new TrainSettlers() - { - ExecuteAt = cbResidence.Duration.AddSeconds(5), - Vill = Vill, - // For high speed servers, you want to train settlers asap - Priority = 1000 < acc.AccInfo.ServerSpeed ? TaskPriority.High : TaskPriority.Medium, - }, true, Vill); - } - - // Check if the task is completed - var taskCb = Vill.Build - .CurrentlyBuilding - .OrderByDescending(x => x.Level) - .FirstOrDefault(x => x.Location == this._buildingTask.BuildingId); - if (taskCb != null && this._buildingTask.TaskType == BuildingType.General && this._buildingTask.Level <= taskCb.Level) RemoveCurrentTask(); - } - - /// - /// Tries to watch an Ad for +25% faster upgrade - /// - /// Account - /// Whether bot watched the ad - private async Task TryFastUpgrade(Account acc) - { - var nodeFastUpgrade = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("videoFeatureButton") && x.HasClass("green")); - if (nodeFastUpgrade == null) return false; - var href = nodeFastUpgrade.GetAttributeValue("onclick", ""); - var script = href.Replace("&", "&"); - acc.Wb.Driver.ExecuteScript(script); - await Task.Delay(rand.Next(2400, 5300)); // just random number =)) - // Confirm - - { - var result = await Update(acc); - if (!result) return false; - } - - var nodeNotShowAgainConfirm = acc.Wb.Html.DocumentNode.SelectSingleNode("//input[@name='adSalesVideoInfoScreen']"); - if (nodeNotShowAgainConfirm != null) - { - acc.Logger.Information("Detected Watch AD diaglog. Choose Don't show again. ..."); - var element = acc.Wb.Driver.FindElement(By.XPath(nodeNotShowAgainConfirm.XPath)); - Actions act = new Actions(acc.Wb.Driver); - act.MoveToElement(element).Click().Build().Perform(); - acc.Wb.Driver.ExecuteScript("jQuery(window).trigger('showVideoWindowAfterInfoScreen')"); - } - - // click to play video - acc.Logger.Information("Waiting ads video play button show"); - - { - var result = await Update(acc); - if (!result) return false; - } - { - // close all tab except current - var current = acc.Wb.Driver.CurrentWindowHandle; - while (acc.Wb.Driver.WindowHandles.Count > 1) - { - if (StopFlag) return false; - var other = acc.Wb.Driver.WindowHandles.FirstOrDefault(x => !x.Equals(current)); - acc.Wb.Driver.SwitchTo().Window(other); - acc.Wb.Driver.Close(); - acc.Wb.Driver.SwitchTo().Window(current); - } - } - { - var result = await Update(acc); - if (!result) return false; - } - { - await Task.Delay(rand.Next(20000, 25000)); // another random number - - acc.Wb.UpdateHtml(); - var nodeIframe = acc.Wb.Html.GetElementbyId("videoFeature"); - if (nodeIframe == null) - { - acc.Logger.Warning("Cannot find play ads button"); - return false; - } - - var elementIframe = acc.Wb.Driver.FindElement(By.XPath(nodeIframe.XPath)); - Actions act = new Actions(acc.Wb.Driver); - var action = act.MoveToElement(elementIframe).Click().Build(); - action.Perform(); - acc.Wb.Driver.SwitchTo().DefaultContent(); - - await Task.Delay(rand.Next(1300, 2000)); // another random number - do - { - var handles = acc.Wb.Driver.WindowHandles; - if (handles.Count == 1) break; - - acc.Logger.Information("Detect auto play ads, bot maybe pause ads. Great work Travian Devs"); - var current = acc.Wb.Driver.CurrentWindowHandle; - var other = acc.Wb.Driver.WindowHandles.FirstOrDefault(x => !x.Equals(current)); - acc.Wb.Driver.SwitchTo().Window(other); - acc.Wb.Driver.Close(); - acc.Wb.Driver.SwitchTo().Window(current); - action.Perform(); - acc.Wb.Driver.SwitchTo().DefaultContent(); - } - while (true); - } - - acc.Logger.Information("Clicked play button, if ads doesn't play please click to help bot"); - acc.Logger.Information("Cooldown 3 mins. If building cannot upgrade will use normal button"); - - { - var result = await DriverHelper.WaitPageChange(acc, "dorf", 3); - if (!result) - { - acc.Wb.UpdateHtml(); - if (acc.Wb.Html.GetElementbyId("dontShowThisAgain") != null) - { - await DriverHelper.ClickById(acc, "dontShowThisAgain"); - await Task.Delay(800); - await DriverHelper.ClickByClassName(acc, "dialogButtonOk ok"); - return true; - } - else - { - await acc.Wb.Refresh(); - return false; - } - } - } - - return true; - } - - private async Task TTWarsTryFastUpgrade(Account acc, string url) - { - var building = Vill.Build.Buildings.FirstOrDefault(x => x.Id == _buildingTask.BuildingId); - var lvl = building.Level; - if (building.UnderConstruction) lvl++; - - var neededRes = BuildingsData.GetBuildingCost(building.Type, lvl + 1); - - if (ResourcesHelper.IsEnoughRes(Vill, neededRes) && - lvl != 0 && - lvl < _buildingTask.Level) - { - await acc.Wb.Navigate(url + "&fastUP=1"); - acc.Logger.Information($"Started (fast) upgrading {building.Type} to level {lvl} in {this.Vill?.Name}"); - - var build = acc.Wb.Html.GetElementbyId("build"); - if (build != null) RemoveCurrentTask(); // Already on max lvl - else PostTaskCheckDorf(acc); - return true; - } - - return false; - } - - private async Task GoRandomDorf(Account acc) - { - var chanceDorf2 = rand.Next(1, 100); - if (chanceDorf2 >= 50) - { - await NavigationHelper.ToDorf2(acc); - } - else - { - await NavigationHelper.ToDorf1(acc); - } - } - - private async Task ChooseTask(Account acc) - { - var nextTask = UpgradeBuildingHelper.NextBuildingTask(acc, Vill); - - if (nextTask == null) - { - if (Vill.Build.Tasks.Count == 0) - { - StopFlag = true; - return nextTask; - } - - acc.Logger.Information("Cannot choose next building task."); - acc.Logger.Information("Checking current village ..."); - await NavigationHelper.SwitchVillage(acc, Vill); - acc.Logger.Information("Update currently building ... "); - await GoRandomDorf(acc); - - var firstComplete = Vill.Build.CurrentlyBuilding.FirstOrDefault(); - if (firstComplete == null) - { - Retry(acc, "Currently building list is empty"); - return nextTask; - } - - NextExecute = TimeHelper.RanDelay(acc, firstComplete.Duration); - acc.Logger.Information($"Next building will be contructed after {firstComplete.Building} - level {firstComplete.Level} complete. ({NextExecute})"); - StopFlag = true; - return nextTask; - } - - return nextTask; - } - - private bool TaskTypeCondition(Account acc) - { - switch (_buildingTask.TaskType) - { - case BuildingType.General: - if (!UpgradeBuildingHelper.CheckGeneralTaskBuildPlace(Vill, _buildingTask)) - { - acc.Logger.Warning($"Cannot find place to construct {_buildingTask.Building}. Skip this and move on next one"); - RemoveCurrentTask(); - _buildingTask = null; - return false; - } - return true; - - case BuildingType.AutoUpgradeResFields: - { - acc.Logger.Information("This is task auto upgrade res field. Choose what res fields will upgrade"); - UpgradeBuildingHelper.AddResFields(acc, Vill, _buildingTask); - var task = Vill.Build.Tasks.FirstOrDefault(); - acc.Logger.Information($"Added {task.Building} - Level {task.Level} to queue"); - return false; - } - } - - return true; - } - - private async Task FreeCropCondition(Account acc) - { - acc.Logger.Information($"Checking current village ..."); - await NavigationHelper.SwitchVillage(acc, Vill); - acc.Logger.Information($"Update free crop ..."); - - if (Vill.Res.FreeCrop <= 5 && _buildingTask.Building != BuildingEnum.Cropland) - { - acc.Logger.Warning($"Don't have enough Free Crop for {_buildingTask.Building} - level {_buildingTask.Level}. Will upgrade Cropland instead."); - - UpgradeBuildingHelper.UpgradeBuildingForOneLvl(acc, Vill, BuildingEnum.Cropland, false); - return false; - } - return true; - } - - private async Task MoveIntoBuilding(Account acc) - { - await AccountHelper.DelayWait(acc); - await NavigationHelper.EnterBuilding(acc, Vill, (int)_buildingTask.BuildingId, 0); - var build = Vill.Build.Buildings.FirstOrDefault(x => x.Id == _buildingTask.BuildingId); - if (build.Type == BuildingEnum.Site) - { - await AccountHelper.DelayWait(acc); - acc.Logger.Information($"This is contruct task, choose correct tab for building {_buildingTask.Building}"); - await NavigationHelper.ToConstructionTab(acc, _buildingTask.Building); - } - } - - private bool IsContructPage(Account acc) - { - acc.Logger.Information($"Finding button to build ..."); - - acc.Wb.UpdateHtml(); - var contractNode = acc.Wb.Html.GetElementbyId($"contract_building{(int)_buildingTask.Building}"); - if (contractNode != null) - { - construct = true; - } - else - { - contractNode = acc.Wb.Html.GetElementbyId("build"); - if (contractNode != null) - { - construct = false; - } - else - { - Retry(acc, "Couldn't find"); - return false; - } - } - acc.Logger.Information("Found it!"); - return true; - } - - private async Task IsEnoughRes(Account acc) - { - // check enough res - acc.Wb.UpdateHtml(); - HtmlNode contractNode = null; - if (construct) - { - contractNode = acc.Wb.Html.GetElementbyId($"contract_building{(int)_buildingTask.Building}"); - } - else - { - contractNode = acc.Wb.Html.GetElementbyId("contract"); - } - - var resWrapper = contractNode.Descendants().FirstOrDefault(x => x.HasClass("resourceWrapper")); - var cost = ResourceParser.GetResourceCost(resWrapper); - - acc.Logger.Information($"Need {cost}"); - - if (!ResourcesHelper.IsEnoughRes(Vill, cost.ToArray())) - { - if (ResourcesHelper.IsStorageTooLow(acc, Vill, cost)) - { - var building = Vill.Build.CurrentlyBuilding.FirstOrDefault(x => x.Building == BuildingEnum.Warehouse || x.Building == BuildingEnum.Granary); - if (building == null) - { - acc.Logger.Warning($"Storage is too low. Added storage upgrade."); - } - else - { - acc.Logger.Warning($"Storage is too low. Next building will be contructed after {building.Building} - level {building.Level} complete. ({NextExecute})"); - NextExecute = TimeHelper.RanDelay(acc, building.Duration); - StopFlag = true; - } - return false; - } - - var stillNeededRes = ResourcesHelper.SubtractResources(cost.ToArray(), Vill.Res.Stored.Resources.ToArray(), true); - acc.Logger.Information($"Not enough resources to build. Still need {stillNeededRes}"); - if (Vill.Settings.UseHeroRes && acc.AccInfo.ServerVersion == ServerVersionEnum.T4_5) // Only T4.5 has resources in hero inv - { - var heroRes = HeroHelper.GetHeroResources(acc); - - if (ResourcesHelper.IsEnoughRes(heroRes, stillNeededRes)) - { - // If we have enough hero res for our task, execute the task - // right after hero equip finishes - acc.Logger.Information("Bot will use resource from hero inventory"); - - var heroEquipTask = ResourcesHelper.UseHeroResources(acc, Vill, ref stillNeededRes, heroRes, _buildingTask); - await heroEquipTask.Execute(acc); - return false; - } - } - - acc.Logger.Information($"Bot will try finish the task later"); - DateTime enoughRes = TimeHelper.EnoughResToUpgrade(Vill, stillNeededRes); - NextExecute = TimeHelper.RanDelay(acc, enoughRes); - StopFlag = true; - return false; - } - return true; - } - } +using HtmlAgilityPack; +using OpenQA.Selenium; +using OpenQA.Selenium.Interactions; +using System; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.BuildingModels; +using TbsCore.Models.VillageModels; +using TbsCore.Parsers; +using TbsCore.TravianData; + +using static TbsCore.Helpers.Classificator; + +namespace TbsCore.Tasks.LowLevel +{ + public class UpgradeBuilding : BotTask + { + private BuildingTask _buildingTask; + private readonly Random rand = new Random(); + private bool construct = false; + private bool result = true; + + public override async Task Execute(Account acc) + { + StopFlag = false; + do + { + if (StopFlag) return TaskRes.Executed; + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Choose building to build...", this); + _buildingTask = await ChooseTask(acc); + if (StopFlag) return TaskRes.Executed; + if (_buildingTask == null) continue; + if (_buildingTask.TaskType == BuildingType.AutoUpgradeResFields) + { + acc.Logger.Information($"{_buildingTask.ResourceType} - Level {_buildingTask.Level} is chosen", this); + } + else + { + acc.Logger.Information($"{_buildingTask.Building} - Level {_buildingTask.Level} is chosen", this); + } + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Check condition ...", this); + var result = TaskTypeCondition(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Check Free crop ...", this); + result = await FreeCropCondition(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + // Fast building for TTWars + if (acc.AccInfo.ServerVersion == ServerVersionEnum.TTwars && !_buildingTask.ConstructNew) + { + acc.Logger.Information("Try using TTWars fast build method", this); + await Task.Delay(AccountHelper.Delay(acc)); + var fastUpgrade = await TTWarsTryFastUpgrade(acc, $"{acc.AccInfo.ServerUrl}/build.php?id={_buildingTask.BuildingId}"); + if (fastUpgrade) continue; + acc.Logger.Information("Using TTWars fast build method failed. Continue normal method", this); + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Moving to building ...", this); + await MoveIntoBuilding(acc); + if (StopFlag) return TaskRes.Executed; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + acc.Logger.Information("Check correct page ...", this); + var result = IsContructPage(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + { + acc.Logger.Information("Check enough resource ...", this); + var result = await IsEnoughRes(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + { + bool result; + if (construct) + { + acc.Logger.Information("Starting construct ...", this); + result = await Construct(acc); + } + else + { + acc.Logger.Information("Starting upgrade ...", this); + result = await Upgrade(acc); + } + if (StopFlag) return TaskRes.Executed; + if (!result) continue; + } + await DriverHelper.WaitPageChange(acc, "dorf"); + } + while (true); + } + + /// + /// Building isn't constructed yet - construct it + /// + /// Account + /// TaskResult + private async Task Construct(Account acc) + { + acc.Wb.UpdateHtml(); + var node = acc.Wb.Html.GetElementbyId($"contract_building{(int)_buildingTask.Building}"); + var button = node.Descendants("button").FirstOrDefault(x => x.HasClass("new")); + + // Check for prerequisites + if (button == null) + { + Retry(acc, "Button disappear."); + return false; + } + + await AccountHelper.DelayWait(acc); + var element = acc.Wb.Driver.FindElement(By.XPath(button.XPath)); + if (element == null) + { + Retry(acc, "Button disappear."); + return false; + } + element.Click(); + _buildingTask.ConstructNew = false; + + if (_buildingTask.Level == 1) + { + RemoveCurrentTask(); + } + + return true; + } + + /// + /// Building is already constructed, upgrade it + /// + /// Account + /// TaskResult + private async Task Upgrade(Account acc) + { + acc.Wb.UpdateHtml(); + HtmlNode node = acc.Wb.Html.GetElementbyId("build"); + (var buildingEnum, var lvl) = InfrastructureParser.UpgradeBuildingGetInfo(node); + + if (buildingEnum == BuildingEnum.Site || lvl == -1) + { + acc.Logger.Warning($"Can't upgrade building {_buildingTask.Building} in village {Vill.Name}. Will be removed from the queue."); + RemoveCurrentTask(); + return false; + } + + // Basic task already on/above desired level, don't upgrade further + var building = Vill.Build.Buildings.FirstOrDefault(x => x.Id == this._buildingTask.BuildingId); + lvl = building.Level; + // Check if building is under construction + if (building.UnderConstruction) + { + // Check currently building + var cb = Vill.Build.CurrentlyBuilding.OrderByDescending(x => x.Level).FirstOrDefault(x => x.Location == building.Id); + if (cb != null && lvl < cb.Level) lvl = cb.Level; + } + + if (lvl >= _buildingTask.Level) + { + acc.Logger.Information($"{_buildingTask.Building} is already level {lvl} in village {Vill.Name}. Will be removed from the queue."); + RemoveCurrentTask(); + return false; + } + + var container = acc.Wb.Html.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass("upgradeButtonsContainer")); + var buttons = container?.Descendants("button"); + if (buttons == null) + { + acc.Logger.Information($"We wanted to upgrade {_buildingTask.Building}, but no 'upgrade' button was found! Url={acc.Wb.CurrentUrl}", this); + return false; + } + + var errorMessage = acc.Wb.Html.GetElementbyId("build") + .Descendants("div") + .FirstOrDefault(x => x.HasClass("upgradeBuilding"))? + .Descendants("div")? + .FirstOrDefault(x => x.HasClass("errorMessage")); + HtmlNode upgradeButton = buttons.FirstOrDefault(x => x.HasClass("build")); + + if (upgradeButton == null) + { + Retry(acc, $"We wanted to upgrade {_buildingTask.Building}, but no 'upgrade' button was found!"); + return false; + } + + // Not enough resources? + if (acc.AccInfo.ServerVersion == ServerVersionEnum.T4_5 && errorMessage != null) + { + Retry(acc, $"We wanted to upgrade {_buildingTask.Building}, but there was an error message:\n{errorMessage.InnerText}"); + return false; + } + + var buildDuration = InfrastructureParser.GetBuildDuration(container, acc.AccInfo.ServerVersion); + + acc.Logger.Information("Complete checking"); + acc.Logger.Information($"Upgrading {_buildingTask.Building} to level {lvl + 1} in {Vill.Name}"); + + var watchAd = false; + if (acc.AccInfo.ServerVersion == ServerVersionEnum.T4_5 && buildDuration.TotalMinutes > acc.Settings.WatchAdAbove) + { + acc.Logger.Information("Try using watch ads upgrade button"); + watchAd = await TryFastUpgrade(acc); + } + + if (!watchAd) + { + await AccountHelper.DelayWait(acc); + acc.Logger.Information("Using normal upgrade button"); + + upgradeButton = buttons.FirstOrDefault(x => x.HasClass("build")); + + var element = acc.Wb.Driver.FindElement(By.XPath(upgradeButton.XPath)); + if (element == null) + { + Retry(acc, "Button disappear."); + return false; + } + element.Click(); + } + + acc.Logger.Information($"Upgraded {_buildingTask.Building} to level {lvl + 1} in {Vill.Name}"); + if (_buildingTask.Level == lvl + 1) + { + RemoveCurrentTask(); + } + return true; + } + + private void RemoveCurrentTask() => Vill.Build.Tasks.Remove(this._buildingTask); + + private void PostTaskCheckDorf(Account acc) + { + // Check if residence is getting upgraded to level 10 => train settlers + var cbResidence = Vill.Build + .CurrentlyBuilding + .FirstOrDefault(x => (x.Building == BuildingEnum.Residence || + x.Building == BuildingEnum.Palace || + x.Building == BuildingEnum.CommandCenter) && + x.Level == 10); + if (cbResidence != null && + acc.NewVillages.AutoSettleNewVillages && + Vill.Troops.Settlers == 0) + { + acc.Tasks.Add( + new TrainSettlers() + { + ExecuteAt = cbResidence.Duration.AddSeconds(5), + Vill = Vill, + // For high speed servers, you want to train settlers asap + Priority = 1000 < acc.AccInfo.ServerSpeed ? TaskPriority.High : TaskPriority.Medium, + }, true, Vill); + } + + // Check if the task is completed + var taskCb = Vill.Build + .CurrentlyBuilding + .OrderByDescending(x => x.Level) + .FirstOrDefault(x => x.Location == this._buildingTask.BuildingId); + if (taskCb != null && this._buildingTask.TaskType == BuildingType.General && this._buildingTask.Level <= taskCb.Level) RemoveCurrentTask(); + } + + /// + /// Tries to watch an Ad for +25% faster upgrade + /// + /// Account + /// Whether bot watched the ad + private async Task TryFastUpgrade(Account acc) + { + var nodeFastUpgrade = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("videoFeatureButton") && x.HasClass("green")); + if (nodeFastUpgrade == null) return false; + var href = nodeFastUpgrade.GetAttributeValue("onclick", ""); + var script = href.Replace("&", "&"); + acc.Wb.Driver.ExecuteScript(script); + await Task.Delay(rand.Next(2400, 5300)); // just random number =)) + // Confirm + + { + var result = await Update(acc); + if (!result) return false; + } + + var nodeNotShowAgainConfirm = acc.Wb.Html.DocumentNode.SelectSingleNode("//input[@name='adSalesVideoInfoScreen']"); + if (nodeNotShowAgainConfirm != null) + { + acc.Logger.Information("Detected Watch AD diaglog. Choose Don't show again. ..."); + var element = acc.Wb.Driver.FindElement(By.XPath(nodeNotShowAgainConfirm.XPath)); + Actions act = new Actions(acc.Wb.Driver); + act.MoveToElement(element).Click().Build().Perform(); + acc.Wb.Driver.ExecuteScript("jQuery(window).trigger('showVideoWindowAfterInfoScreen')"); + } + + // click to play video + acc.Logger.Information("Waiting ads video play button show"); + + { + var result = await Update(acc); + if (!result) return false; + } + { + // close all tab except current + var current = acc.Wb.Driver.CurrentWindowHandle; + while (acc.Wb.Driver.WindowHandles.Count > 1) + { + if (StopFlag) return false; + var other = acc.Wb.Driver.WindowHandles.FirstOrDefault(x => !x.Equals(current)); + acc.Wb.Driver.SwitchTo().Window(other); + acc.Wb.Driver.Close(); + acc.Wb.Driver.SwitchTo().Window(current); + } + } + { + var result = await Update(acc); + if (!result) return false; + } + { + await Task.Delay(rand.Next(20000, 25000)); // another random number + + acc.Wb.UpdateHtml(); + var nodeIframe = acc.Wb.Html.GetElementbyId("videoFeature"); + if (nodeIframe == null) + { + acc.Logger.Warning("Cannot find play ads button"); + return false; + } + + var elementIframe = acc.Wb.Driver.FindElement(By.XPath(nodeIframe.XPath)); + Actions act = new Actions(acc.Wb.Driver); + var action = act.MoveToElement(elementIframe).Click().Build(); + action.Perform(); + acc.Wb.Driver.SwitchTo().DefaultContent(); + + await Task.Delay(rand.Next(1300, 2000)); // another random number + do + { + var handles = acc.Wb.Driver.WindowHandles; + if (handles.Count == 1) break; + + acc.Logger.Information("Detect auto play ads, bot maybe pause ads. Great work Travian Devs"); + var current = acc.Wb.Driver.CurrentWindowHandle; + var other = acc.Wb.Driver.WindowHandles.FirstOrDefault(x => !x.Equals(current)); + acc.Wb.Driver.SwitchTo().Window(other); + acc.Wb.Driver.Close(); + acc.Wb.Driver.SwitchTo().Window(current); + action.Perform(); + acc.Wb.Driver.SwitchTo().DefaultContent(); + } + while (true); + } + + acc.Logger.Information("Clicked play button, if ads doesn't play please click to help bot"); + acc.Logger.Information("Cooldown 3 mins. If building cannot upgrade will use normal button"); + + { + var result = await DriverHelper.WaitPageChange(acc, "dorf", 3); + if (!result) + { + acc.Wb.UpdateHtml(); + if (acc.Wb.Html.GetElementbyId("dontShowThisAgain") != null) + { + await DriverHelper.ClickById(acc, "dontShowThisAgain"); + await Task.Delay(800); + await DriverHelper.ClickByClassName(acc, "dialogButtonOk ok"); + return true; + } + else + { + await acc.Wb.Refresh(); + return false; + } + } + } + + return true; + } + + private async Task TTWarsTryFastUpgrade(Account acc, string url) + { + var building = Vill.Build.Buildings.FirstOrDefault(x => x.Id == _buildingTask.BuildingId); + var lvl = building.Level; + if (building.UnderConstruction) lvl++; + + var neededRes = BuildingsData.GetBuildingCost(building.Type, lvl + 1); + + if (ResourcesHelper.IsEnoughRes(Vill, neededRes) && + lvl != 0 && + lvl < _buildingTask.Level) + { + await acc.Wb.Navigate(url + "&fastUP=1"); + acc.Logger.Information($"Started (fast) upgrading {building.Type} to level {lvl} in {this.Vill?.Name}"); + + var build = acc.Wb.Html.GetElementbyId("build"); + if (build != null) RemoveCurrentTask(); // Already on max lvl + else PostTaskCheckDorf(acc); + return true; + } + + return false; + } + + private async Task GoRandomDorf(Account acc) + { + var chanceDorf2 = rand.Next(1, 100); + if (chanceDorf2 >= 50) + { + await NavigationHelper.ToDorf2(acc); + } + else + { + await NavigationHelper.ToDorf1(acc); + } + } + + private async Task ChooseTask(Account acc) + { + var nextTask = UpgradeBuildingHelper.NextBuildingTask(acc, Vill); + + if (nextTask == null) + { + if (Vill.Build.Tasks.Count == 0) + { + StopFlag = true; + return nextTask; + } + + acc.Logger.Information("Cannot choose next building task."); + acc.Logger.Information("Checking current village ..."); + await NavigationHelper.SwitchVillage(acc, Vill); + acc.Logger.Information("Update currently building ... "); + await GoRandomDorf(acc); + + var firstComplete = Vill.Build.CurrentlyBuilding.FirstOrDefault(); + if (firstComplete == null) + { + Retry(acc, "Currently building list is empty"); + return nextTask; + } + + NextExecute = TimeHelper.RanDelay(acc, firstComplete.Duration); + acc.Logger.Information($"Next building will be contructed after {firstComplete.Building} - level {firstComplete.Level} complete. ({NextExecute})"); + StopFlag = true; + return nextTask; + } + + return nextTask; + } + + private bool TaskTypeCondition(Account acc) + { + switch (_buildingTask.TaskType) + { + case BuildingType.General: + if (!UpgradeBuildingHelper.CheckGeneralTaskBuildPlace(Vill, _buildingTask)) + { + acc.Logger.Warning($"Cannot find place to construct {_buildingTask.Building}. Skip this and move on next one"); + RemoveCurrentTask(); + _buildingTask = null; + return false; + } + return true; + + case BuildingType.AutoUpgradeResFields: + { + acc.Logger.Information("This is task auto upgrade res field. Choose what res fields will upgrade"); + UpgradeBuildingHelper.AddResFields(acc, Vill, _buildingTask); + var task = Vill.Build.Tasks.FirstOrDefault(); + acc.Logger.Information($"Added {task.Building} - Level {task.Level} to queue"); + return false; + } + } + + return true; + } + + private async Task FreeCropCondition(Account acc) + { + acc.Logger.Information($"Checking current village ..."); + await NavigationHelper.SwitchVillage(acc, Vill); + acc.Logger.Information($"Update free crop ..."); + + if (Vill.Res.FreeCrop <= 5 && _buildingTask.Building != BuildingEnum.Cropland) + { + acc.Logger.Warning($"Don't have enough Free Crop for {_buildingTask.Building} - level {_buildingTask.Level}. Will upgrade Cropland instead."); + + UpgradeBuildingHelper.UpgradeBuildingForOneLvl(acc, Vill, BuildingEnum.Cropland, false); + return false; + } + return true; + } + + private async Task MoveIntoBuilding(Account acc) + { + await AccountHelper.DelayWait(acc); + await NavigationHelper.EnterBuilding(acc, Vill, (int)_buildingTask.BuildingId, 0); + var build = Vill.Build.Buildings.FirstOrDefault(x => x.Id == _buildingTask.BuildingId); + if (build.Type == BuildingEnum.Site) + { + await AccountHelper.DelayWait(acc); + acc.Logger.Information($"This is contruct task, choose correct tab for building {_buildingTask.Building}"); + await NavigationHelper.ToConstructionTab(acc, _buildingTask.Building); + } + } + + private bool IsContructPage(Account acc) + { + acc.Logger.Information($"Finding button to build ..."); + + acc.Wb.UpdateHtml(); + var contractNode = acc.Wb.Html.GetElementbyId($"contract_building{(int)_buildingTask.Building}"); + if (contractNode != null) + { + construct = true; + } + else + { + contractNode = acc.Wb.Html.GetElementbyId("build"); + if (contractNode != null) + { + construct = false; + } + else + { + Retry(acc, "Couldn't find"); + return false; + } + } + acc.Logger.Information("Found it!"); + return true; + } + + private async Task IsEnoughRes(Account acc) + { + // check enough res + acc.Wb.UpdateHtml(); + HtmlNode contractNode = null; + if (construct) + { + contractNode = acc.Wb.Html.GetElementbyId($"contract_building{(int)_buildingTask.Building}"); + } + else + { + contractNode = acc.Wb.Html.GetElementbyId("contract"); + } + + var resWrapper = contractNode.Descendants().FirstOrDefault(x => x.HasClass("resourceWrapper")); + var cost = ResourceParser.GetResourceCost(resWrapper); + + acc.Logger.Information($"Need {cost}"); + + if (!ResourcesHelper.IsEnoughRes(Vill, cost.ToArray())) + { + if (ResourcesHelper.IsStorageTooLow(acc, Vill, cost)) + { + var building = Vill.Build.CurrentlyBuilding.FirstOrDefault(x => x.Building == BuildingEnum.Warehouse || x.Building == BuildingEnum.Granary); + if (building == null) + { + acc.Logger.Warning($"Storage is too low. Added storage upgrade."); + } + else + { + acc.Logger.Warning($"Storage is too low. Next building will be contructed after {building.Building} - level {building.Level} complete. ({NextExecute})"); + NextExecute = TimeHelper.RanDelay(acc, building.Duration); + StopFlag = true; + } + return false; + } + + var stillNeededRes = ResourcesHelper.SubtractResources(cost.ToArray(), Vill.Res.Stored.Resources.ToArray(), true); + acc.Logger.Information($"Not enough resources to build. Still need {stillNeededRes}"); + if (Vill.Settings.UseHeroRes && acc.AccInfo.ServerVersion == ServerVersionEnum.T4_5) // Only T4.5 has resources in hero inv + { + var heroRes = HeroHelper.GetHeroResources(acc); + + if (ResourcesHelper.IsEnoughRes(heroRes, stillNeededRes)) + { + // If we have enough hero res for our task, execute the task + // right after hero equip finishes + acc.Logger.Information("Bot will use resource from hero inventory"); + + var heroEquipTask = ResourcesHelper.UseHeroResources(acc, Vill, ref stillNeededRes, heroRes, _buildingTask); + await heroEquipTask.Execute(acc); + return false; + } + } + + acc.Logger.Information($"Bot will try finish the task later"); + DateTime enoughRes = TimeHelper.EnoughResToUpgrade(Vill, stillNeededRes); + NextExecute = TimeHelper.RanDelay(acc, enoughRes); + StopFlag = true; + return false; + } + return true; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/CheckProfile.cs b/TbsCore/Tasks/Update/CheckProfile.cs similarity index 100% rename from TbsCore/Tasks/LowLevel/CheckProfile.cs rename to TbsCore/Tasks/Update/CheckProfile.cs diff --git a/TbsCore/Tasks/LowLevel/GetServerInfo.cs b/TbsCore/Tasks/Update/GetServerInfo.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/GetServerInfo.cs rename to TbsCore/Tasks/Update/GetServerInfo.cs index 36226512e..2e2176700 100644 --- a/TbsCore/Tasks/LowLevel/GetServerInfo.cs +++ b/TbsCore/Tasks/Update/GetServerInfo.cs @@ -1,25 +1,25 @@ -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; - -namespace TbsCore.Tasks.LowLevel -{ - public class GetServerInfo : BotTask - { - public override async Task Execute(Account acc) - { - await Task.Yield(); - // Get Map size - var size = DriverHelper.GetJsObj(acc, "window.TravianDefaults.Map.Size.top"); - acc.AccInfo.MapSize = (int)size; - acc.Logger.Information($"Server map size is {acc.AccInfo.MapSize}x{acc.AccInfo.MapSize}"); - - // Get server speed - var speed = DriverHelper.GetJsObj(acc, "Travian.Game.speed"); - acc.AccInfo.ServerSpeed = (int)speed; - acc.Logger.Information($"Server speed is {acc.AccInfo.ServerSpeed}"); - - return TaskRes.Executed; - } - } +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; + +namespace TbsCore.Tasks.LowLevel +{ + public class GetServerInfo : BotTask + { + public override async Task Execute(Account acc) + { + await Task.Yield(); + // Get Map size + var size = DriverHelper.GetJsObj(acc, "window.TravianDefaults.Map.Size.top"); + acc.AccInfo.MapSize = (int)size; + acc.Logger.Information($"Server map size is {acc.AccInfo.MapSize}x{acc.AccInfo.MapSize}"); + + // Get server speed + var speed = DriverHelper.GetJsObj(acc, "Travian.Game.speed"); + acc.AccInfo.ServerSpeed = (int)speed; + acc.Logger.Information($"Server speed is {acc.AccInfo.ServerSpeed}"); + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/GetTribe.cs b/TbsCore/Tasks/Update/GetTribe.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/GetTribe.cs rename to TbsCore/Tasks/Update/GetTribe.cs index 4ca3e3007..f1b9139e7 100644 --- a/TbsCore/Tasks/LowLevel/GetTribe.cs +++ b/TbsCore/Tasks/Update/GetTribe.cs @@ -1,89 +1,89 @@ -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Helpers; -using TbsCore.Parsers; -using System; - -namespace TbsCore.Tasks.LowLevel -{ - public class GetTribe : BotTask - { - public override async Task Execute(Account acc) - { - await Task.Yield(); - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.TTwars: - { - var result = CheckTTWars(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) return TaskRes.Executed; - } - break; - - case Classificator.ServerVersionEnum.T4_5: - { - var result = CheckT45(acc); - if (StopFlag) return TaskRes.Executed; - if (!result) return TaskRes.Executed; - } - break; - - default: - break; - } - var tribeStr = acc.AccInfo.Tribe == null ? "Unknown" : $"{acc.AccInfo.Tribe}"; - acc.Logger.Information($"Tribe account is {tribeStr}"); - return TaskRes.Executed; - } - - private static bool CheckTTWars(Account acc) - { - var nodeDiv = acc.Wb.Html.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass("playerName")); - if (nodeDiv == null) - { - acc.Logger.Warning("Cannot find hero name"); - return false; - } - var nodeImage = nodeDiv.Descendants("img").FirstOrDefault(); - if (nodeImage == null) - { - acc.Logger.Warning("Cannot find image hero tribe"); - return false; - } - var tribeStr = nodeImage.GetAttributeValue("alt", ""); - var result = Enum.TryParse(tribeStr, out Classificator.TribeEnum tribe); - if (!result) - { - acc.Logger.Warning($"Cannot parse tribe name [{tribeStr}]"); - return false; - } - - acc.AccInfo.Tribe = tribe; - return true; - } - - private static bool CheckT45(Account acc) - { - var questMaster = acc.Wb.Html.GetElementbyId("questmasterButton"); - if (questMaster == null) - { - acc.Logger.Warning("Cannot find avatar tribe questmater"); - return false; - } - var vid = questMaster.GetClasses().FirstOrDefault(x => x.StartsWith("vid")); - if (vid == null) - { - acc.Logger.Warning("Cannot detect tribe"); - return false; - } - - var tribeId = Parser.RemoveNonNumeric(vid); - acc.AccInfo.Tribe = (Classificator.TribeEnum)tribeId; - - return true; - } - } +using System.Collections.Generic; +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Helpers; +using TbsCore.Parsers; +using System; + +namespace TbsCore.Tasks.LowLevel +{ + public class GetTribe : BotTask + { + public override async Task Execute(Account acc) + { + await Task.Yield(); + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.TTwars: + { + var result = CheckTTWars(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + break; + + case Classificator.ServerVersionEnum.T4_5: + { + var result = CheckT45(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + break; + + default: + break; + } + var tribeStr = acc.AccInfo.Tribe == null ? "Unknown" : $"{acc.AccInfo.Tribe}"; + acc.Logger.Information($"Tribe account is {tribeStr}"); + return TaskRes.Executed; + } + + private static bool CheckTTWars(Account acc) + { + var nodeDiv = acc.Wb.Html.DocumentNode.Descendants("div").FirstOrDefault(x => x.HasClass("playerName")); + if (nodeDiv == null) + { + acc.Logger.Warning("Cannot find hero name"); + return false; + } + var nodeImage = nodeDiv.Descendants("img").FirstOrDefault(); + if (nodeImage == null) + { + acc.Logger.Warning("Cannot find image hero tribe"); + return false; + } + var tribeStr = nodeImage.GetAttributeValue("alt", ""); + var result = Enum.TryParse(tribeStr, out Classificator.TribeEnum tribe); + if (!result) + { + acc.Logger.Warning($"Cannot parse tribe name [{tribeStr}]"); + return false; + } + + acc.AccInfo.Tribe = tribe; + return true; + } + + private static bool CheckT45(Account acc) + { + var questMaster = acc.Wb.Html.GetElementbyId("questmasterButton"); + if (questMaster == null) + { + acc.Logger.Warning("Cannot find avatar tribe questmater"); + return false; + } + var vid = questMaster.GetClasses().FirstOrDefault(x => x.StartsWith("vid")); + if (vid == null) + { + acc.Logger.Warning("Cannot detect tribe"); + return false; + } + + var tribeId = Parser.RemoveNonNumeric(vid); + acc.AccInfo.Tribe = (Classificator.TribeEnum)tribeId; + + return true; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/HeroUpdateInfo.cs b/TbsCore/Tasks/Update/HeroUpdateInfo.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/HeroUpdateInfo.cs rename to TbsCore/Tasks/Update/HeroUpdateInfo.cs index ae7cb89ec..c5336d285 100644 --- a/TbsCore/Tasks/LowLevel/HeroUpdateInfo.cs +++ b/TbsCore/Tasks/Update/HeroUpdateInfo.cs @@ -1,55 +1,55 @@ -using System; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Helpers; -using static TbsCore.Helpers.Classificator; - -namespace TbsCore.Tasks.LowLevel -{ - public class HeroUpdateInfo : BotTask - { - private readonly Random ran = new Random(); - - public override async Task Execute(Account acc) - { - await NavigationHelper.ToHero(acc, NavigationHelper.HeroTab.Attributes); - - if (acc.Hero.Settings.AutoAuction) - { - var items = acc.Hero.Items; - foreach (var item in items) - { - var (heroItemEnum, amount) = (item.Item, item.Count); - var category = HeroHelper.GetHeroItemCategory(heroItemEnum); - switch (category) - { - case HeroItemCategory.Resource: - continue; - - case HeroItemCategory.Stackable: - if (amount < 5) continue; - break; - - case HeroItemCategory.Horse: - continue; - } - - acc.Tasks.Add(new SellOnAuctions() - { - ExecuteAt = DateTime.Now - }, true); - break; - } - } - if (acc.Hero.Settings.AutoRefreshInfo) - { - this.NextExecute = DateTime.Now.AddMinutes( - ran.Next(acc.Hero.Settings.MinUpdate, acc.Hero.Settings.MaxUpdate) - ); - } - acc.Tasks.Remove(typeof(HeroUpdateInfo), thisTask: this); - - return TaskRes.Executed; - } - } +using System; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Helpers; +using static TbsCore.Helpers.Classificator; + +namespace TbsCore.Tasks.LowLevel +{ + public class HeroUpdateInfo : BotTask + { + private readonly Random ran = new Random(); + + public override async Task Execute(Account acc) + { + await NavigationHelper.ToHero(acc, NavigationHelper.HeroTab.Attributes); + + if (acc.Hero.Settings.AutoAuction) + { + var items = acc.Hero.Items; + foreach (var item in items) + { + var (heroItemEnum, amount) = (item.Item, item.Count); + var category = HeroHelper.GetHeroItemCategory(heroItemEnum); + switch (category) + { + case HeroItemCategory.Resource: + continue; + + case HeroItemCategory.Stackable: + if (amount < 5) continue; + break; + + case HeroItemCategory.Horse: + continue; + } + + acc.Tasks.Add(new SellOnAuctions() + { + ExecuteAt = DateTime.Now + }, true); + break; + } + } + if (acc.Hero.Settings.AutoRefreshInfo) + { + this.NextExecute = DateTime.Now.AddMinutes( + ran.Next(acc.Hero.Settings.MinUpdate, acc.Hero.Settings.MaxUpdate) + ); + } + acc.Tasks.Remove(typeof(HeroUpdateInfo), thisTask: this); + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/ReadMessage.cs b/TbsCore/Tasks/Update/ReadMessage.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/ReadMessage.cs rename to TbsCore/Tasks/Update/ReadMessage.cs index 84409943f..45d82bd82 100644 --- a/TbsCore/Tasks/LowLevel/ReadMessage.cs +++ b/TbsCore/Tasks/Update/ReadMessage.cs @@ -1,35 +1,35 @@ -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Helpers; - -namespace TbsCore.Tasks.LowLevel -{ - public class ReadMessage : BotTask - { - public override async Task Execute(Account acc) - { - while (true) - { - await NavigationHelper.MainNavigate(acc, NavigationHelper.MainNavigationButton.Messages); - var msg = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("messageStatusUnread")); - if (msg != null) - { - - var url = msg.ParentNode.GetAttributeValue("href", "").Replace("amp;", ""); - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.T4_5: - await acc.Wb.Navigate(acc.AccInfo.ServerUrl + url); - break; - case Classificator.ServerVersionEnum.TTwars: - await acc.Wb.Navigate(acc.AccInfo.ServerUrl + "/" + url); - break; - } - await Task.Delay(AccountHelper.Delay(acc) * 5); - } - else return TaskRes.Executed; - } - } - } -} +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Helpers; + +namespace TbsCore.Tasks.LowLevel +{ + public class ReadMessage : BotTask + { + public override async Task Execute(Account acc) + { + while (true) + { + await NavigationHelper.MainNavigate(acc, NavigationHelper.MainNavigationButton.Messages); + var msg = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("messageStatusUnread")); + if (msg != null) + { + + var url = msg.ParentNode.GetAttributeValue("href", "").Replace("amp;", ""); + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.T4_5: + await acc.Wb.Navigate(acc.AccInfo.ServerUrl + url); + break; + case Classificator.ServerVersionEnum.TTwars: + await acc.Wb.Navigate(acc.AccInfo.ServerUrl + "/" + url); + break; + } + await Task.Delay(AccountHelper.Delay(acc) * 5); + } + else return TaskRes.Executed; + } + } + } +} diff --git a/TbsCore/Tasks/LowLevel/UpdateDorf1.cs b/TbsCore/Tasks/Update/UpdateDorf1.cs similarity index 96% rename from TbsCore/Tasks/LowLevel/UpdateDorf1.cs rename to TbsCore/Tasks/Update/UpdateDorf1.cs index b89a79b8a..16851388b 100644 --- a/TbsCore/Tasks/LowLevel/UpdateDorf1.cs +++ b/TbsCore/Tasks/Update/UpdateDorf1.cs @@ -1,33 +1,33 @@ -using System; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Helpers; - -namespace TbsCore.Tasks.LowLevel -{ - public class UpdateDorf1 : BotTask - { - public override async Task Execute(Account acc) - { - acc.Tasks.Remove(this.GetType(), Vill, thisTask: this); - - if (!acc.Wb.CurrentUrl.Contains("/dorf1.php")) // Don't re-navigate - { - await NavigationHelper.ToDorf1(acc); - } - - // 60% to check update dorf2 - Random ran = new Random(); - if (ran.Next(1, 100) > 40) - { - acc.Tasks.Add(new UpdateDorf2() - { - ExecuteAt = DateTime.Now.AddMinutes(1), - Vill = Vill - }, true, Vill); - } - - return TaskRes.Executed; - } - } +using System; +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Helpers; + +namespace TbsCore.Tasks.LowLevel +{ + public class UpdateDorf1 : BotTask + { + public override async Task Execute(Account acc) + { + acc.Tasks.Remove(this.GetType(), Vill, thisTask: this); + + if (!acc.Wb.CurrentUrl.Contains("/dorf1.php")) // Don't re-navigate + { + await NavigationHelper.ToDorf1(acc); + } + + // 60% to check update dorf2 + Random ran = new Random(); + if (ran.Next(1, 100) > 40) + { + acc.Tasks.Add(new UpdateDorf2() + { + ExecuteAt = DateTime.Now.AddMinutes(1), + Vill = Vill + }, true, Vill); + } + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/UpdateDorf2.cs b/TbsCore/Tasks/Update/UpdateDorf2.cs similarity index 96% rename from TbsCore/Tasks/LowLevel/UpdateDorf2.cs rename to TbsCore/Tasks/Update/UpdateDorf2.cs index ee5d29d42..06ca9eb9e 100644 --- a/TbsCore/Tasks/LowLevel/UpdateDorf2.cs +++ b/TbsCore/Tasks/Update/UpdateDorf2.cs @@ -1,21 +1,21 @@ -using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Helpers; - -namespace TbsCore.Tasks.LowLevel -{ - public class UpdateDorf2 : BotTask - { - public override async Task Execute(Account acc) - { - acc.Tasks.Remove(this.GetType(), Vill, thisTask: this); - - if (!acc.Wb.CurrentUrl.Contains("/dorf2.php")) // Don't re-navigate - { - await NavigationHelper.ToDorf2(acc); - } - - return TaskRes.Executed; - } - } +using System.Threading.Tasks; +using TbsCore.Models.AccModels; +using TbsCore.Helpers; + +namespace TbsCore.Tasks.LowLevel +{ + public class UpdateDorf2 : BotTask + { + public override async Task Execute(Account acc) + { + acc.Tasks.Remove(this.GetType(), Vill, thisTask: this); + + if (!acc.Wb.CurrentUrl.Contains("/dorf2.php")) // Don't re-navigate + { + await NavigationHelper.ToDorf2(acc); + } + + return TaskRes.Executed; + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/UpdateTaskUseRes.cs b/TbsCore/Tasks/Update/UpdateTaskUseRes.cs similarity index 100% rename from TbsCore/Tasks/LowLevel/UpdateTaskUseRes.cs rename to TbsCore/Tasks/Update/UpdateTaskUseRes.cs diff --git a/TbsCore/Tasks/LowLevel/UpdateTroops.cs b/TbsCore/Tasks/Update/UpdateTroops.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/UpdateTroops.cs rename to TbsCore/Tasks/Update/UpdateTroops.cs index 4c85aba02..9f79e2fad 100644 --- a/TbsCore/Tasks/LowLevel/UpdateTroops.cs +++ b/TbsCore/Tasks/Update/UpdateTroops.cs @@ -1,59 +1,59 @@ -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.VillageModels; -using TbsCore.Parsers; - -namespace TbsCore.Tasks.LowLevel -{ - public class UpdateTroops : BotTask - { - /// - /// When new village is found by the bot, it should firstly check barracks, then stable and then workshop, - /// to see which troops are researched - /// - public override async Task Execute(Account acc) - { - // If we have Plus account, just check that. - if (acc.AccInfo.PlusAccount) - { - await NavigationHelper.ToOverview(acc, NavigationHelper.OverviewTab.Overview); - await VersionHelper.Navigate(acc, "/dorf3.php?s=5&su=2", "/village/statistics/troops?su=2"); - - OverviewParser.UpdateTroopsLevels(acc.Wb.Html, ref acc); - // We have updated all villages at the same time. No need to continue. - acc.Tasks.Remove(typeof(UpdateTroops)); - return TaskRes.Executed; - } - - var smithy = Vill.Build.Buildings.FirstOrDefault(x => x.Type == Classificator.BuildingEnum.Smithy); - if (smithy != null) - { - await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?id={smithy.Id}"); - Vill.Troops.Levels = TroopsParser.GetTroopLevels(acc.Wb.Html); - TroopsHelper.UpdateResearchedTroops(Vill); - return TaskRes.Executed; - } - - for (int i = 0; i < 3; i++) - { - //var building = GetBuilding(i); - //await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?id={building.Id}"); - // TODO: parse content - } - return TaskRes.Executed; - } - - private Building GetBuilding(int check) - { - switch (check) - { - case 1: return Vill.Build.Buildings.FirstOrDefault(x => x.Type == Classificator.BuildingEnum.Barracks); - case 2: return Vill.Build.Buildings.FirstOrDefault(x => x.Type == Classificator.BuildingEnum.Stable); - case 3: return Vill.Build.Buildings.FirstOrDefault(x => x.Type == Classificator.BuildingEnum.Workshop); - default: return null; - } - } - } +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.VillageModels; +using TbsCore.Parsers; + +namespace TbsCore.Tasks.LowLevel +{ + public class UpdateTroops : BotTask + { + /// + /// When new village is found by the bot, it should firstly check barracks, then stable and then workshop, + /// to see which troops are researched + /// + public override async Task Execute(Account acc) + { + // If we have Plus account, just check that. + if (acc.AccInfo.PlusAccount) + { + await NavigationHelper.ToOverview(acc, NavigationHelper.OverviewTab.Overview); + await VersionHelper.Navigate(acc, "/dorf3.php?s=5&su=2", "/village/statistics/troops?su=2"); + + OverviewParser.UpdateTroopsLevels(acc.Wb.Html, ref acc); + // We have updated all villages at the same time. No need to continue. + acc.Tasks.Remove(typeof(UpdateTroops)); + return TaskRes.Executed; + } + + var smithy = Vill.Build.Buildings.FirstOrDefault(x => x.Type == Classificator.BuildingEnum.Smithy); + if (smithy != null) + { + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?id={smithy.Id}"); + Vill.Troops.Levels = TroopsParser.GetTroopLevels(acc.Wb.Html); + TroopsHelper.UpdateResearchedTroops(Vill); + return TaskRes.Executed; + } + + for (int i = 0; i < 3; i++) + { + //var building = GetBuilding(i); + //await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/build.php?id={building.Id}"); + // TODO: parse content + } + return TaskRes.Executed; + } + + private Building GetBuilding(int check) + { + switch (check) + { + case 1: return Vill.Build.Buildings.FirstOrDefault(x => x.Type == Classificator.BuildingEnum.Barracks); + case 2: return Vill.Build.Buildings.FirstOrDefault(x => x.Type == Classificator.BuildingEnum.Stable); + case 3: return Vill.Build.Buildings.FirstOrDefault(x => x.Type == Classificator.BuildingEnum.Workshop); + default: return null; + } + } + } } \ No newline at end of file diff --git a/TbsCore/Tasks/LowLevel/UpdateVillage.cs b/TbsCore/Tasks/Update/UpdateVillage.cs similarity index 97% rename from TbsCore/Tasks/LowLevel/UpdateVillage.cs rename to TbsCore/Tasks/Update/UpdateVillage.cs index 526c6e4dd..326d5d5ee 100644 --- a/TbsCore/Tasks/LowLevel/UpdateVillage.cs +++ b/TbsCore/Tasks/Update/UpdateVillage.cs @@ -1,110 +1,110 @@ -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.TravianData; -using TbsCore.Parsers; - -namespace TbsCore.Tasks.LowLevel -{ - public class UpdateVillage : BotTask - { - /// - /// If village is new, we want to import the building tasks to the village - /// - public bool ImportTasks { get; set; } - - public override async Task Execute(Account acc) - { - acc.Tasks.Remove(typeof(UpdateDorf1), Vill, thisTask: this); - acc.Tasks.Remove(typeof(UpdateDorf2), Vill, thisTask: this); - - await NavigationHelper.ToDorf1(acc); - await NavigationHelper.ToDorf2(acc); - - // On new village import the building tasks - if (ImportTasks && !string.IsNullOrEmpty(acc.NewVillages.BuildingTasksLocationNewVillage)) - { - IoHelperCore.AddBuildTasksFromFile(acc, Vill, acc.NewVillages.BuildingTasksLocationNewVillage); - } - - await UpdateTroopsResearchedAndLevels(acc); - - await Task.Delay(AccountHelper.Delay(acc)); - await UpdateTroopsTraining(acc); - - var firstTroop = TroopsData.TribeFirstTroop(acc.AccInfo.Tribe); - Vill.Troops.TroopToTrain = firstTroop; - Vill.Troops.Researched.Add(firstTroop); - - return TaskRes.Executed; - } - - // Copied from UpdateTroops BotTask - public async Task UpdateTroopsResearchedAndLevels(Account acc) - { - if (acc.AccInfo.PlusAccount) - { - // From overview we get all researched troops and their levels - await NavigationHelper.ToOverview(acc, NavigationHelper.OverviewTab.Troops, NavigationHelper.TroopOverview.Smithy); - - OverviewParser.UpdateTroopsLevels(acc.Wb.Html, ref acc); - // We have updated all villages at the same time. No need to continue. - acc.Tasks.Remove(typeof(UpdateTroops)); - return; - } - - // If smithy exists, we get all researched troops and their levels - if (await NavigationHelper.EnterBuilding(acc, Vill, Classificator.BuildingEnum.Smithy)) - { - Vill.Troops.Levels = TroopsParser.GetTroopLevels(acc.Wb.Html); - TroopsHelper.UpdateResearchedTroops(Vill); - return; - } - } - - private readonly Classificator.BuildingEnum[] trainingBuildings = new Classificator.BuildingEnum[] { - Classificator.BuildingEnum.Barracks, - Classificator.BuildingEnum.Stable, - Classificator.BuildingEnum.Workshop, - Classificator.BuildingEnum.GreatBarracks, - Classificator.BuildingEnum.GreatStable - }; - - public async Task UpdateTroopsTraining(Account acc) - { - foreach (var trainingBuilding in trainingBuildings) - { - if (!await NavigationHelper.EnterBuilding(acc, Vill, trainingBuilding)) continue; - - // Mark troops that user can train in building as researched - TroopsHelper.UpdateTroopsResearched(Vill, acc.Wb.Html); - - var ct = TroopsParser.GetTroopsCurrentlyTraining(acc.Wb.Html); - switch (trainingBuilding) - { - case Classificator.BuildingEnum.Barracks: - Vill.Troops.CurrentlyTraining.Barracks = ct; - break; - - case Classificator.BuildingEnum.Stable: - Vill.Troops.CurrentlyTraining.Stable = ct; - break; - - case Classificator.BuildingEnum.GreatBarracks: - Vill.Troops.CurrentlyTraining.GB = ct; - break; - - case Classificator.BuildingEnum.GreatStable: - Vill.Troops.CurrentlyTraining.GS = ct; - break; - - case Classificator.BuildingEnum.Workshop: - Vill.Troops.CurrentlyTraining.Workshop = ct; - break; - } - await Task.Delay(AccountHelper.Delay(acc)); - } - } - } +using System.Linq; +using System.Threading.Tasks; +using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.TravianData; +using TbsCore.Parsers; + +namespace TbsCore.Tasks.LowLevel +{ + public class UpdateVillage : BotTask + { + /// + /// If village is new, we want to import the building tasks to the village + /// + public bool ImportTasks { get; set; } + + public override async Task Execute(Account acc) + { + acc.Tasks.Remove(typeof(UpdateDorf1), Vill, thisTask: this); + acc.Tasks.Remove(typeof(UpdateDorf2), Vill, thisTask: this); + + await NavigationHelper.ToDorf1(acc); + await NavigationHelper.ToDorf2(acc); + + // On new village import the building tasks + if (ImportTasks && !string.IsNullOrEmpty(acc.NewVillages.BuildingTasksLocationNewVillage)) + { + IoHelperCore.AddBuildTasksFromFile(acc, Vill, acc.NewVillages.BuildingTasksLocationNewVillage); + } + + await UpdateTroopsResearchedAndLevels(acc); + + await Task.Delay(AccountHelper.Delay(acc)); + await UpdateTroopsTraining(acc); + + var firstTroop = TroopsData.TribeFirstTroop(acc.AccInfo.Tribe); + Vill.Troops.TroopToTrain = firstTroop; + Vill.Troops.Researched.Add(firstTroop); + + return TaskRes.Executed; + } + + // Copied from UpdateTroops BotTask + public async Task UpdateTroopsResearchedAndLevels(Account acc) + { + if (acc.AccInfo.PlusAccount) + { + // From overview we get all researched troops and their levels + await NavigationHelper.ToOverview(acc, NavigationHelper.OverviewTab.Troops, NavigationHelper.TroopOverview.Smithy); + + OverviewParser.UpdateTroopsLevels(acc.Wb.Html, ref acc); + // We have updated all villages at the same time. No need to continue. + acc.Tasks.Remove(typeof(UpdateTroops)); + return; + } + + // If smithy exists, we get all researched troops and their levels + if (await NavigationHelper.EnterBuilding(acc, Vill, Classificator.BuildingEnum.Smithy)) + { + Vill.Troops.Levels = TroopsParser.GetTroopLevels(acc.Wb.Html); + TroopsHelper.UpdateResearchedTroops(Vill); + return; + } + } + + private readonly Classificator.BuildingEnum[] trainingBuildings = new Classificator.BuildingEnum[] { + Classificator.BuildingEnum.Barracks, + Classificator.BuildingEnum.Stable, + Classificator.BuildingEnum.Workshop, + Classificator.BuildingEnum.GreatBarracks, + Classificator.BuildingEnum.GreatStable + }; + + public async Task UpdateTroopsTraining(Account acc) + { + foreach (var trainingBuilding in trainingBuildings) + { + if (!await NavigationHelper.EnterBuilding(acc, Vill, trainingBuilding)) continue; + + // Mark troops that user can train in building as researched + TroopsHelper.UpdateTroopsResearched(Vill, acc.Wb.Html); + + var ct = TroopsParser.GetTroopsCurrentlyTraining(acc.Wb.Html); + switch (trainingBuilding) + { + case Classificator.BuildingEnum.Barracks: + Vill.Troops.CurrentlyTraining.Barracks = ct; + break; + + case Classificator.BuildingEnum.Stable: + Vill.Troops.CurrentlyTraining.Stable = ct; + break; + + case Classificator.BuildingEnum.GreatBarracks: + Vill.Troops.CurrentlyTraining.GB = ct; + break; + + case Classificator.BuildingEnum.GreatStable: + Vill.Troops.CurrentlyTraining.GS = ct; + break; + + case Classificator.BuildingEnum.Workshop: + Vill.Troops.CurrentlyTraining.Workshop = ct; + break; + } + await Task.Delay(AccountHelper.Delay(acc)); + } + } + } } \ No newline at end of file From a5798bed4d4c5b7acf87ba50650c5ea455dcc37f Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 14:27:53 +0700 Subject: [PATCH 04/16] Tasks.Browser namespace --- TbsCore/Core/TaskExecutor.cs | 1 + TbsCore/Core/TaskTimer.cs | 1 + TbsCore/Helpers/AccountHelper.cs | 3 ++- TbsCore/Models/AccModels/TaskList.cs | 17 +++++++---------- TbsCore/Tasks/Browser/ChangeAccess.cs | 2 +- TbsCore/Tasks/Browser/ReopenDriver.cs | 2 +- TbsCore/Tasks/Browser/RestartChrome.cs | 2 +- TbsCore/Tasks/Browser/TaskSleep.cs | 2 +- TbsCore/Tasks/Browser/TimeSleep.cs | 2 +- .../Tasks/{Browser => Update}/CheckAttacks.cs | 0 TravBotSharp/Views/GeneralUc.cs | 7 ++++--- 11 files changed, 20 insertions(+), 19 deletions(-) rename TbsCore/Tasks/{Browser => Update}/CheckAttacks.cs (100%) diff --git a/TbsCore/Core/TaskExecutor.cs b/TbsCore/Core/TaskExecutor.cs index 8fa88df5d..a3cce7433 100644 --- a/TbsCore/Core/TaskExecutor.cs +++ b/TbsCore/Core/TaskExecutor.cs @@ -7,6 +7,7 @@ using TbsCore.Models.VillageModels; using TbsCore.Parsers; using TbsCore.Tasks; +using TbsCore.Tasks.Browser; using TbsCore.Tasks.LowLevel; using static TbsCore.Tasks.BotTask; diff --git a/TbsCore/Core/TaskTimer.cs b/TbsCore/Core/TaskTimer.cs index 08a3e1631..f8bb755be 100644 --- a/TbsCore/Core/TaskTimer.cs +++ b/TbsCore/Core/TaskTimer.cs @@ -4,6 +4,7 @@ using System.Timers; using TbsCore.Helpers; using TbsCore.Tasks; +using TbsCore.Tasks.Browser; using TbsCore.Tasks.LowLevel; using static TbsCore.Tasks.BotTask; diff --git a/TbsCore/Helpers/AccountHelper.cs b/TbsCore/Helpers/AccountHelper.cs index f2a5a2cf8..74e7fdc94 100644 --- a/TbsCore/Helpers/AccountHelper.cs +++ b/TbsCore/Helpers/AccountHelper.cs @@ -3,6 +3,7 @@ using System.Threading.Tasks; using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; +using TbsCore.Tasks.Browser; using TbsCore.Tasks.LowLevel; using TbsCore.Tasks.SecondLevel; @@ -10,7 +11,7 @@ namespace TbsCore.Helpers { public static class AccountHelper { - private static Random rnd = new Random(); + private static readonly Random rnd = new Random(); public static Village GetMainVillage(Account acc) { diff --git a/TbsCore/Models/AccModels/TaskList.cs b/TbsCore/Models/AccModels/TaskList.cs index 6b25c1c44..a53612f0a 100644 --- a/TbsCore/Models/AccModels/TaskList.cs +++ b/TbsCore/Models/AccModels/TaskList.cs @@ -1,13 +1,13 @@ -using System; -using System.Linq; +using Newtonsoft.Json; +using System; using System.Collections.Generic; +using System.IO; +using System.Linq; +using TbsCore.Helpers; using TbsCore.Models.VillageModels; using TbsCore.Tasks; +using TbsCore.Tasks.Browser; using static TbsCore.Tasks.BotTask; -using Newtonsoft.Json; -using System.IO; -using TbsCore.Helpers; -using TbsCore.Tasks.LowLevel; namespace TbsCore.Models.AccModels { @@ -182,10 +182,7 @@ public void Load() foreach (var task in list) { var type = Type.GetType(task.Type); - if (type == typeof(TimeSleep)) - { - continue; - } + var botTask = JsonConvert.DeserializeObject(task.Content, type) as BotTask; if (botTask.Stage == TaskStage.Executing) botTask.Stage = TaskStage.Start; if (botTask.Vill != null) diff --git a/TbsCore/Tasks/Browser/ChangeAccess.cs b/TbsCore/Tasks/Browser/ChangeAccess.cs index ddf6aee3f..b74ab15fd 100644 --- a/TbsCore/Tasks/Browser/ChangeAccess.cs +++ b/TbsCore/Tasks/Browser/ChangeAccess.cs @@ -3,7 +3,7 @@ using TbsCore.Models.AccModels; using TbsCore.Helpers; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Browser { /// /// This task changes access (and restarts selenium driver) for the account and sets the next access change, if there are multiple access'. diff --git a/TbsCore/Tasks/Browser/ReopenDriver.cs b/TbsCore/Tasks/Browser/ReopenDriver.cs index e22ebcfa3..051d01716 100644 --- a/TbsCore/Tasks/Browser/ReopenDriver.cs +++ b/TbsCore/Tasks/Browser/ReopenDriver.cs @@ -4,7 +4,7 @@ using TbsCore.Helpers; using System.Linq; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Browser { /// /// Task will close and reopen driver then the next Normal/High priority task has to be executed diff --git a/TbsCore/Tasks/Browser/RestartChrome.cs b/TbsCore/Tasks/Browser/RestartChrome.cs index 3ccf0858b..747ae418a 100644 --- a/TbsCore/Tasks/Browser/RestartChrome.cs +++ b/TbsCore/Tasks/Browser/RestartChrome.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Browser { public class RestartChrome : ReopenDriver { diff --git a/TbsCore/Tasks/Browser/TaskSleep.cs b/TbsCore/Tasks/Browser/TaskSleep.cs index 260883139..6c5caceff 100644 --- a/TbsCore/Tasks/Browser/TaskSleep.cs +++ b/TbsCore/Tasks/Browser/TaskSleep.cs @@ -3,7 +3,7 @@ using TbsCore.Models.AccModels; using System.Linq; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Browser { public class TaskSleep : ReopenDriver { diff --git a/TbsCore/Tasks/Browser/TimeSleep.cs b/TbsCore/Tasks/Browser/TimeSleep.cs index f225025a5..296adb94b 100644 --- a/TbsCore/Tasks/Browser/TimeSleep.cs +++ b/TbsCore/Tasks/Browser/TimeSleep.cs @@ -3,7 +3,7 @@ using TbsCore.Models.AccModels; using TbsCore.Helpers; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Browser { public class TimeSleep : ReopenDriver { diff --git a/TbsCore/Tasks/Browser/CheckAttacks.cs b/TbsCore/Tasks/Update/CheckAttacks.cs similarity index 100% rename from TbsCore/Tasks/Browser/CheckAttacks.cs rename to TbsCore/Tasks/Update/CheckAttacks.cs diff --git a/TravBotSharp/Views/GeneralUc.cs b/TravBotSharp/Views/GeneralUc.cs index e3d82335b..a86f14894 100644 --- a/TravBotSharp/Views/GeneralUc.cs +++ b/TravBotSharp/Views/GeneralUc.cs @@ -1,15 +1,16 @@ using System; using System.Drawing; -using System.Threading; using System.Reflection; +using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.Settings; -using TbsCore.Helpers; +using TbsCore.Tasks.Browser; using TbsCore.Tasks.LowLevel; -using TravBotSharp.Interfaces; using TravBotSharp.Forms; +using TravBotSharp.Interfaces; namespace TravBotSharp.Views { From ec0dde72f701242ecf2131eba1e297be33c0536b Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 14:46:03 +0700 Subject: [PATCH 05/16] remove unused using --- TbsCore/Core/PostLoadHelper.cs | 1 - TbsCore/Core/TaskTimer.cs | 1 - TbsCore/Core/WebBrowserInfo.cs | 11 +++------- TbsCore/Database/DbRepository.cs | 1 - TbsCore/Database/TbsContext.cs | 2 +- TbsCore/Extensions/AccountExtension.cs | 6 +----- .../Extensions/RallyPointNavigationHelper.cs | 9 +-------- TbsCore/Helpers/AttackHelper.cs | 5 +---- TbsCore/Helpers/BuildingHelper.cs | 3 --- .../ChromeExtension/DisableWebRTCLeak.cs | 2 -- TbsCore/Helpers/GithubHelper.cs | 4 ++-- TbsCore/Helpers/HeroHelper.cs | 3 --- TbsCore/Helpers/HttpHelper.cs | 1 - TbsCore/Helpers/IoHelperCore.cs | 3 --- TbsCore/Helpers/MapHelper.cs | 7 ++----- TbsCore/Helpers/ObjectHelper.cs | 1 - TbsCore/Helpers/ResSpendingHelper.cs | 2 -- TbsCore/Helpers/ResourcesHelper.cs | 1 - TbsCore/Helpers/TimeHelper.cs | 2 -- TbsCore/Helpers/TroopsHelper.cs | 4 +--- TbsCore/Helpers/UpdateAccountObject.cs | 1 - TbsCore/Helpers/UpgradeBuildingHelper.cs | 8 +++----- TbsCore/Helpers/VersionHelper.cs | 5 +---- TbsCore/Helpers/VillageHelper.cs | 3 --- TbsCore/Models/AccModels/AccInfo.cs | 4 ++-- TbsCore/Models/AccModels/Account.cs | 13 ++++-------- TbsCore/Models/AccModels/Hero.cs | 2 +- .../Models/AccModels/NewVillageSettings.cs | 3 +-- TbsCore/Models/AccModels/TaskList.cs | 1 - TbsCore/Models/Access/AccessInfo.cs | 2 -- TbsCore/Models/AttackModels/AttackReport.cs | 7 ++----- TbsCore/Models/AttackModels/VillageReport.cs | 5 +---- TbsCore/Models/CombatModels/Combat.cs | 4 +--- TbsCore/Models/CombatModels/CombatArmy.cs | 6 +----- TbsCore/Models/CombatModels/CombatArmyBase.cs | 2 -- TbsCore/Models/CombatModels/CombatAttacker.cs | 8 ++------ .../Models/CombatModels/CombatDeffender.cs | 10 ++++------ TbsCore/Models/CombatModels/CombatHero.cs | 3 +-- TbsCore/Models/CombatModels/CombatPoints.cs | 10 +++++----- TbsCore/Models/JsObjects/BldJsObject.cs | 7 +------ TbsCore/Models/JsObjects/ResourcesJsObject.cs | 5 +---- TbsCore/Models/Logging/Logger.cs | 4 ++-- TbsCore/Models/Logging/SerilogSingleton.cs | 4 ++-- TbsCore/Models/MapModels/Coordinates.cs | 4 +--- .../ResourceModels/MerchantsUnderWay.cs | 1 - TbsCore/Models/Settings/GeneralSettings.cs | 5 +---- TbsCore/Models/SideBarModels/Quest.cs | 4 +--- TbsCore/Models/TroopsModels/FarmList.cs | 1 - TbsCore/Models/TroopsModels/TroopLevel.cs | 2 +- TbsCore/Models/TroopsModels/TroopsBase.cs | 4 ++-- TbsCore/Models/TroopsModels/VillTroops.cs | 1 - .../TroopsMovementModels/SendWaveModel.cs | 2 +- .../TroopMovementDorf1.cs | 2 -- .../TroopsMovementModels/TroopsSendModel.cs | 5 +---- TbsCore/Models/VillageModels/VillBuilding.cs | 2 +- TbsCore/Models/VillageModels/VillDeffing.cs | 6 +----- .../VillageModels/VillTroopMovements.cs | 6 ++---- .../VillageModels/VillUnfinishedTask.cs | 5 +---- TbsCore/Models/VillageModels/Village.cs | 6 +++--- TbsCore/Models/World/AccServerData.cs | 5 +---- TbsCore/Models/World/TravianUser.cs | 5 ++--- TbsCore/Models/World/TravianVillage.cs | 5 +---- TbsCore/Parsers/AdventureParser.cs | 2 +- TbsCore/Parsers/AttackParser.cs | 8 +++----- TbsCore/Parsers/HeroParser.cs | 2 +- TbsCore/Parsers/InfrastructureParser.cs | 6 +++--- TbsCore/Parsers/LeftbarParser.cs | 2 +- TbsCore/Parsers/MarketParser.cs | 2 -- TbsCore/Parsers/OverviewParser.cs | 2 +- TbsCore/Parsers/ProfileParser.cs | 7 +------ TbsCore/Parsers/ResourceParser.cs | 2 +- TbsCore/Parsers/RightBarParser.cs | 2 +- TbsCore/Parsers/TroopsMovementParser.cs | 5 ++--- TbsCore/Parsers/TroopsParser.cs | 2 +- TbsCore/Tasks/Browser/ChangeAccess.cs | 2 +- TbsCore/Tasks/Browser/ReopenDriver.cs | 5 +---- TbsCore/Tasks/Browser/TaskSleep.cs | 2 +- TbsCore/Tasks/Browser/TimeSleep.cs | 2 +- TbsCore/Tasks/Farm/AttackOasis.cs | 5 ++--- TbsCore/Tasks/Farm/ScoutPlayer.cs | 7 +------ TbsCore/Tasks/Farm/SendFLs.cs | 2 +- TbsCore/Tasks/Farm/SendReinforcementScouts.cs | 18 ++++++----------- TbsCore/Tasks/Farm/SendWaves.cs | 3 +-- TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs | 4 ---- .../Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs | 5 ++--- TbsCore/Tasks/Farm/TransitToMainAcc.cs | 2 +- TbsCore/Tasks/Farm/UpdateFarmLists.cs | 10 +++++----- TbsCore/Tasks/Others/HeroSetPoints.cs | 2 +- TbsCore/Tasks/Others/ReviveHero.cs | 6 +++--- TbsCore/Tasks/Others/SendResFillTroops.cs | 2 +- TbsCore/Tasks/Others/SendResToMain.cs | 2 +- TbsCore/Tasks/Others/SendResources.cs | 2 +- TbsCore/Tasks/Others/SetCapital.cs | 2 +- TbsCore/Tasks/Others/TTWarsExpandStorage.cs | 2 +- TbsCore/Tasks/Others/TTWarsPlusAndBoost.cs | 2 +- TbsCore/Tasks/Update/CheckAttacks.cs | 2 +- TbsCore/Tasks/Update/CheckProfile.cs | 3 ++- TbsCore/Tasks/Update/GetTribe.cs | 5 ++--- TbsCore/Tasks/Update/HeroUpdateInfo.cs | 2 +- TbsCore/Tasks/Update/ReadMessage.cs | 4 ++-- TbsCore/Tasks/Update/UpdateDorf1.cs | 2 +- TbsCore/Tasks/Update/UpdateDorf2.cs | 2 +- TbsCore/Tasks/Update/UpdateTaskUseRes.cs | 5 ++--- TbsCore/Tasks/Update/UpdateVillage.cs | 5 ++--- TbsCore/TravianData/CombatSimulator.cs | 5 +---- TbsCore/TravianData/Localizations.cs | 4 ---- TbsCore/TravianData/TroopCost.cs | 1 - TbsCore/TravianData/TroopsData.cs | 7 +++---- TbsCoreTest/BuildingTest.cs | 6 +----- TbsCoreTest/CombatSimulationTest.cs | 8 ++------ TbsCoreTest/Factories/AccountFactory.cs | 5 ----- TbsCoreTest/Factories/BuildingFactory.cs | 4 +--- TbsCoreTest/Factories/CombatFactory.cs | 12 +++++------ TbsCoreTest/Helpers/IoHelperCoreTest.cs | 3 --- TbsCoreTest/ResSpendingTest.cs | 3 +-- TravBotSharp/ControlPanel.cs | 9 +++------ TravBotSharp/Forms/AddFarmNonGold.cs | 9 +-------- TravBotSharp/Forms/Closing.cs | 10 +--------- TravBotSharp/Forms/Helper.cs | 7 ------- TravBotSharp/Forms/NewRelease.cs | 2 +- TravBotSharp/Forms/Splash.cs | 10 +--------- TravBotSharp/Forms/TroopsSelector.cs | 7 ------- TravBotSharp/UserControls/CoordinatesUc.cs | 14 +++---------- TravBotSharp/UserControls/TroopSelector.cs | 10 +--------- TravBotSharp/UserControls/TroopsDisplayUc.cs | 9 +-------- TravBotSharp/UserControls/TroopsSelectorUc.cs | 10 +--------- TravBotSharp/Views/DeffendingUc.cs | 2 -- TravBotSharp/Views/DiscordUc.cs | 3 +-- TravBotSharp/Views/FarmingUc.cs | 6 ++---- TravBotSharp/Views/HeroUc.cs | 4 ++-- TravBotSharp/Views/NewVillagesUc.cs | 3 +-- TravBotSharp/Views/OverviewUc.cs | 2 +- TravBotSharp/Views/VillageViews/AttackUc.cs | 8 +++----- TravBotSharp/Views/VillageViews/BuildUc.cs | 2 +- .../Views/VillageViews/FarmingNonGoldUc.cs | 20 ++++++++----------- TravBotSharp/Views/VillageViews/InfoUc.cs | 3 --- TravBotSharp/Views/VillageViews/MarketUc.cs | 1 - TravBotSharp/Views/VillageViews/TroopsUc.cs | 3 ++- TravBotSharp/Views/VillagesUc.cs | 2 +- 139 files changed, 180 insertions(+), 450 deletions(-) diff --git a/TbsCore/Core/PostLoadHelper.cs b/TbsCore/Core/PostLoadHelper.cs index e6fb62fe0..42cd310fd 100644 --- a/TbsCore/Core/PostLoadHelper.cs +++ b/TbsCore/Core/PostLoadHelper.cs @@ -5,7 +5,6 @@ using TbsCore.Models.AccModels; using TbsCore.Models.JsObjects; using TbsCore.Models.VillageModels; -using TbsCore.Helpers; using TbsCore.Parsers; using TbsCore.Tasks.LowLevel; using static TbsCore.Tasks.BotTask; diff --git a/TbsCore/Core/TaskTimer.cs b/TbsCore/Core/TaskTimer.cs index f8bb755be..cdddc04c5 100644 --- a/TbsCore/Core/TaskTimer.cs +++ b/TbsCore/Core/TaskTimer.cs @@ -3,7 +3,6 @@ using System.Threading.Tasks; using System.Timers; using TbsCore.Helpers; -using TbsCore.Tasks; using TbsCore.Tasks.Browser; using TbsCore.Tasks.LowLevel; using static TbsCore.Tasks.BotTask; diff --git a/TbsCore/Core/WebBrowserInfo.cs b/TbsCore/Core/WebBrowserInfo.cs index 8a4c7d8bd..2ea08e049 100644 --- a/TbsCore/Core/WebBrowserInfo.cs +++ b/TbsCore/Core/WebBrowserInfo.cs @@ -1,18 +1,13 @@ using OpenQA.Selenium; using OpenQA.Selenium.Chrome; -using RestSharp; +using OpenQA.Selenium.Chrome.ChromeDriverExtensions; using System; -using System.Collections.Generic; +using System.Collections.ObjectModel; using System.IO; using System.Threading.Tasks; +using TbsCore.Database; using TbsCore.Helpers; -using TbsCore.Models; -using TbsCore.Tasks.LowLevel; using TbsCore.Helpers.ChromeExtension; -using static TbsCore.Tasks.BotTask; -using OpenQA.Selenium.Chrome.ChromeDriverExtensions; -using System.Collections.ObjectModel; -using TbsCore.Database; namespace TbsCore.Models.AccModels { diff --git a/TbsCore/Database/DbRepository.cs b/TbsCore/Database/DbRepository.cs index bb7d732bf..811bd197f 100644 --- a/TbsCore/Database/DbRepository.cs +++ b/TbsCore/Database/DbRepository.cs @@ -4,7 +4,6 @@ using System.Linq; using TbsCore.Models.AccModels; using TbsCore.Models.Database; -using TbsCore.Helpers; namespace TbsCore.Database { diff --git a/TbsCore/Database/TbsContext.cs b/TbsCore/Database/TbsContext.cs index 126f29c87..edc81910a 100644 --- a/TbsCore/Database/TbsContext.cs +++ b/TbsCore/Database/TbsContext.cs @@ -1,7 +1,7 @@ using Microsoft.EntityFrameworkCore; using System.IO; -using TbsCore.Models.Database; using TbsCore.Helpers; +using TbsCore.Models.Database; namespace TbsCore.Database { diff --git a/TbsCore/Extensions/AccountExtension.cs b/TbsCore/Extensions/AccountExtension.cs index f429d8988..9eb83e143 100644 --- a/TbsCore/Extensions/AccountExtension.cs +++ b/TbsCore/Extensions/AccountExtension.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; +using TbsCore.Models.AccModels; namespace TbsCore.Extensions { diff --git a/TbsCore/Extensions/RallyPointNavigationHelper.cs b/TbsCore/Extensions/RallyPointNavigationHelper.cs index 073e0794f..ae9f9a00f 100644 --- a/TbsCore/Extensions/RallyPointNavigationHelper.cs +++ b/TbsCore/Extensions/RallyPointNavigationHelper.cs @@ -1,11 +1,4 @@ -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; -using TbsCore.Models.VillageModels; -using static TbsCore.Helpers.Classificator; -using System; - -namespace TbsCore.Extensions +namespace TbsCore.Extensions { /// /// WIP! diff --git a/TbsCore/Helpers/AttackHelper.cs b/TbsCore/Helpers/AttackHelper.cs index 32f44a04a..cffff2bd7 100644 --- a/TbsCore/Helpers/AttackHelper.cs +++ b/TbsCore/Helpers/AttackHelper.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TbsCore.Parsers; +using TbsCore.Parsers; namespace TbsCore.Helpers { diff --git a/TbsCore/Helpers/BuildingHelper.cs b/TbsCore/Helpers/BuildingHelper.cs index 134a9a5f8..b5ec4b52d 100644 --- a/TbsCore/Helpers/BuildingHelper.cs +++ b/TbsCore/Helpers/BuildingHelper.cs @@ -1,12 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; -using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.BuildingModels; using TbsCore.Models.VillageModels; -using TbsCore.Tasks; -using TbsCore.Tasks.LowLevel; using TbsCore.TravianData; using static TbsCore.Helpers.Classificator; diff --git a/TbsCore/Helpers/ChromeExtension/DisableWebRTCLeak.cs b/TbsCore/Helpers/ChromeExtension/DisableWebRTCLeak.cs index a6b47a51e..b8adb6603 100644 --- a/TbsCore/Helpers/ChromeExtension/DisableWebRTCLeak.cs +++ b/TbsCore/Helpers/ChromeExtension/DisableWebRTCLeak.cs @@ -1,7 +1,5 @@ using System; using System.IO; -using System.IO.Compression; -using TbsCore.Models.Access; namespace TbsCore.Helpers.ChromeExtension { diff --git a/TbsCore/Helpers/GithubHelper.cs b/TbsCore/Helpers/GithubHelper.cs index 7adeeb12a..215433e70 100644 --- a/TbsCore/Helpers/GithubHelper.cs +++ b/TbsCore/Helpers/GithubHelper.cs @@ -1,6 +1,6 @@ -using System; +using Octokit; +using System; using System.Threading.Tasks; -using Octokit; namespace TbsCore.Helpers { diff --git a/TbsCore/Helpers/HeroHelper.cs b/TbsCore/Helpers/HeroHelper.cs index 48d40d83e..c5e232dfb 100644 --- a/TbsCore/Helpers/HeroHelper.cs +++ b/TbsCore/Helpers/HeroHelper.cs @@ -1,11 +1,8 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.MapModels; -using TbsCore.Models.ResourceModels; using TbsCore.Models.VillageModels; using TbsCore.Parsers; using TbsCore.Tasks.LowLevel; diff --git a/TbsCore/Helpers/HttpHelper.cs b/TbsCore/Helpers/HttpHelper.cs index 1d37573e5..7faa2616b 100644 --- a/TbsCore/Helpers/HttpHelper.cs +++ b/TbsCore/Helpers/HttpHelper.cs @@ -3,7 +3,6 @@ using System.Net; using System.Threading.Tasks; using TbsCore.Database; -using TbsCore.Models.Access; using TbsCore.Models.AccModels; namespace TbsCore.Helpers diff --git a/TbsCore/Helpers/IoHelperCore.cs b/TbsCore/Helpers/IoHelperCore.cs index 212d1d1f4..64e3ed0ed 100644 --- a/TbsCore/Helpers/IoHelperCore.cs +++ b/TbsCore/Helpers/IoHelperCore.cs @@ -4,10 +4,7 @@ using System.IO; using System.Linq; using System.Threading.Tasks; -using Discord.Webhook; using TbsCore.Database; -using TbsCore.Models.Access; -using TbsCore.Models.Logging; using TbsCore.Models.AccModels; using TbsCore.Models.BuildingModels; using TbsCore.Models.VillageModels; diff --git a/TbsCore/Helpers/MapHelper.cs b/TbsCore/Helpers/MapHelper.cs index e15d926e4..b7bf27c62 100644 --- a/TbsCore/Helpers/MapHelper.cs +++ b/TbsCore/Helpers/MapHelper.cs @@ -4,14 +4,11 @@ using System.Collections.Generic; using System.Linq; using System.Net; -using TbsCore.Helpers; +using System.Threading.Tasks; using TbsCore.Models.AccModels; using TbsCore.Models.MapModels; -using TbsCore.Models.VillageModels; -using TbsCore.TravianData; -using TbsCore.Parsers; using TbsCore.Models.TroopsModels; -using System.Threading.Tasks; +using TbsCore.Parsers; namespace TbsCore.Helpers { diff --git a/TbsCore/Helpers/ObjectHelper.cs b/TbsCore/Helpers/ObjectHelper.cs index 051a6aab6..0ddc306da 100644 --- a/TbsCore/Helpers/ObjectHelper.cs +++ b/TbsCore/Helpers/ObjectHelper.cs @@ -4,7 +4,6 @@ using System.Reflection; using System.Runtime.InteropServices; using TbsCore.Models.AccModels; -using TbsCore.Models.World; namespace TbsCore.Helpers { diff --git a/TbsCore/Helpers/ResSpendingHelper.cs b/TbsCore/Helpers/ResSpendingHelper.cs index 6762c205d..0897a0a33 100644 --- a/TbsCore/Helpers/ResSpendingHelper.cs +++ b/TbsCore/Helpers/ResSpendingHelper.cs @@ -1,12 +1,10 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Text; using TbsCore.Models.AccModels; using TbsCore.Models.ResourceModels; using TbsCore.Models.Settings; using TbsCore.Models.VillageModels; -using TbsCore.Helpers; using TbsCore.Tasks; using TbsCore.Tasks.LowLevel; diff --git a/TbsCore/Helpers/ResourcesHelper.cs b/TbsCore/Helpers/ResourcesHelper.cs index f2a199e7f..cb874e840 100644 --- a/TbsCore/Helpers/ResourcesHelper.cs +++ b/TbsCore/Helpers/ResourcesHelper.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using TbsCore.Extensions; -using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.BuildingModels; using TbsCore.Models.ResourceModels; diff --git a/TbsCore/Helpers/TimeHelper.cs b/TbsCore/Helpers/TimeHelper.cs index 52ce3f0b2..a39fca9c3 100644 --- a/TbsCore/Helpers/TimeHelper.cs +++ b/TbsCore/Helpers/TimeHelper.cs @@ -1,8 +1,6 @@ using System; -using System.Linq; using System.Threading.Tasks; using TbsCore.Models.AccModels; -using TbsCore.Models.ResourceModels; using TbsCore.Models.VillageModels; using static TbsCore.Tasks.BotTask; diff --git a/TbsCore/Helpers/TroopsHelper.cs b/TbsCore/Helpers/TroopsHelper.cs index d6335e571..74f77f5d9 100644 --- a/TbsCore/Helpers/TroopsHelper.cs +++ b/TbsCore/Helpers/TroopsHelper.cs @@ -4,11 +4,9 @@ using System.Linq; using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; -using TbsCore.TravianData; using TbsCore.Parsers; using TbsCore.Tasks.LowLevel; - -using static TbsCore.Helpers.BuildingHelper; +using TbsCore.TravianData; using static TbsCore.Helpers.Classificator; namespace TbsCore.Helpers diff --git a/TbsCore/Helpers/UpdateAccountObject.cs b/TbsCore/Helpers/UpdateAccountObject.cs index dae279a0b..cb970b5c2 100644 --- a/TbsCore/Helpers/UpdateAccountObject.cs +++ b/TbsCore/Helpers/UpdateAccountObject.cs @@ -2,7 +2,6 @@ using System.Collections.Generic; using System.Linq; using TbsCore.Models.AccModels; -using TbsCore.Models.Settings; using TbsCore.Models.SideBarModels; using TbsCore.Models.VillageModels; using TbsCore.Parsers; diff --git a/TbsCore/Helpers/UpgradeBuildingHelper.cs b/TbsCore/Helpers/UpgradeBuildingHelper.cs index b0435dfcb..bf220deef 100644 --- a/TbsCore/Helpers/UpgradeBuildingHelper.cs +++ b/TbsCore/Helpers/UpgradeBuildingHelper.cs @@ -1,14 +1,12 @@ using System; +using System.Collections.Generic; using System.Linq; using TbsCore.Models.AccModels; using TbsCore.Models.BuildingModels; using TbsCore.Models.VillageModels; -using TbsCore.Helpers; -using static TbsCore.Helpers.Classificator; -using TbsCore.TravianData; -using System.Collections.Generic; using TbsCore.Tasks; -using TbsCore.Tasks.LowLevel; +using TbsCore.TravianData; +using static TbsCore.Helpers.Classificator; namespace TbsCore.Helpers { diff --git a/TbsCore/Helpers/VersionHelper.cs b/TbsCore/Helpers/VersionHelper.cs index 964bdf800..aa974646b 100644 --- a/TbsCore/Helpers/VersionHelper.cs +++ b/TbsCore/Helpers/VersionHelper.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Threading.Tasks; +using System.Threading.Tasks; using TbsCore.Models.AccModels; using static TbsCore.Helpers.Classificator; diff --git a/TbsCore/Helpers/VillageHelper.cs b/TbsCore/Helpers/VillageHelper.cs index fa5d70243..9eb264fa3 100644 --- a/TbsCore/Helpers/VillageHelper.cs +++ b/TbsCore/Helpers/VillageHelper.cs @@ -2,12 +2,9 @@ using System; using System.Linq; using System.Threading.Tasks; -using System.Web; using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; -using TbsCore.Parsers; using TbsCore.Tasks.LowLevel; -using TbsCore.TravianData; using static TbsCore.Helpers.Classificator; namespace TbsCore.Helpers diff --git a/TbsCore/Models/AccModels/AccInfo.cs b/TbsCore/Models/AccModels/AccInfo.cs index 336acefb9..d505d29de 100644 --- a/TbsCore/Models/AccModels/AccInfo.cs +++ b/TbsCore/Models/AccModels/AccInfo.cs @@ -1,5 +1,5 @@ -using TbsCore.Models.SideBarModels; -using TbsCore.Helpers; +using TbsCore.Helpers; +using TbsCore.Models.SideBarModels; namespace TbsCore.Models.AccModels { diff --git a/TbsCore/Models/AccModels/Account.cs b/TbsCore/Models/AccModels/Account.cs index d88923c37..a6283c2cf 100644 --- a/TbsCore/Models/AccModels/Account.cs +++ b/TbsCore/Models/AccModels/Account.cs @@ -1,17 +1,12 @@ -using Newtonsoft.Json; -using System.IO; +using Discord.Webhook; +using Newtonsoft.Json; using System.Collections.Generic; -using Discord.Webhook; +using TbsCore.Helpers; using TbsCore.Models.Access; +using TbsCore.Models.Logging; using TbsCore.Models.Settings; using TbsCore.Models.VillageModels; -using TbsCore.Models.Logging; -using TbsCore.Models.AccModels; -using TbsCore.Tasks; - -using Serilog; using TbsCore.Models.World; -using TbsCore.Helpers; namespace TbsCore.Models.AccModels { diff --git a/TbsCore/Models/AccModels/Hero.cs b/TbsCore/Models/AccModels/Hero.cs index d2718c730..222abb6a4 100644 --- a/TbsCore/Models/AccModels/Hero.cs +++ b/TbsCore/Models/AccModels/Hero.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; +using TbsCore.Helpers; using TbsCore.Models.Settings; using TbsCore.Models.TroopsModels; -using TbsCore.Helpers; namespace TbsCore.Models.AccModels { diff --git a/TbsCore/Models/AccModels/NewVillageSettings.cs b/TbsCore/Models/AccModels/NewVillageSettings.cs index a134041ca..021ae63ce 100644 --- a/TbsCore/Models/AccModels/NewVillageSettings.cs +++ b/TbsCore/Models/AccModels/NewVillageSettings.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; -using TbsCore.Models.Settings; -using TbsCore.Models.VillageModels; using TbsCore.Helpers; +using TbsCore.Models.VillageModels; namespace TbsCore.Models.AccModels { diff --git a/TbsCore/Models/AccModels/TaskList.cs b/TbsCore/Models/AccModels/TaskList.cs index a53612f0a..b49bb6ea5 100644 --- a/TbsCore/Models/AccModels/TaskList.cs +++ b/TbsCore/Models/AccModels/TaskList.cs @@ -6,7 +6,6 @@ using TbsCore.Helpers; using TbsCore.Models.VillageModels; using TbsCore.Tasks; -using TbsCore.Tasks.Browser; using static TbsCore.Tasks.BotTask; namespace TbsCore.Models.AccModels diff --git a/TbsCore/Models/Access/AccessInfo.cs b/TbsCore/Models/Access/AccessInfo.cs index 251fa3dbd..2004938da 100644 --- a/TbsCore/Models/Access/AccessInfo.cs +++ b/TbsCore/Models/Access/AccessInfo.cs @@ -1,8 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; -using TbsCore.Helpers; namespace TbsCore.Models.Access { diff --git a/TbsCore/Models/AttackModels/AttackReport.cs b/TbsCore/Models/AttackModels/AttackReport.cs index 3a1f1aa21..288f0bf78 100644 --- a/TbsCore/Models/AttackModels/AttackReport.cs +++ b/TbsCore/Models/AttackModels/AttackReport.cs @@ -1,8 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Collections.Generic; using TbsCore.Helpers; -using TbsCore.Models.MapModels; using TbsCore.Models.ResourceModels; using TbsCore.Models.TroopsModels; @@ -42,7 +39,7 @@ public AttackReport(bool init = false) /// /// - public int ResidenceLevel {get;set;} + public int ResidenceLevel { get; set; } public int WallLevel { get; set; } /// diff --git a/TbsCore/Models/AttackModels/VillageReport.cs b/TbsCore/Models/AttackModels/VillageReport.cs index 5211a78b1..cdd4350e7 100644 --- a/TbsCore/Models/AttackModels/VillageReport.cs +++ b/TbsCore/Models/AttackModels/VillageReport.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TbsCore.Helpers; +using TbsCore.Helpers; namespace TbsCore.Models.AttackModels { diff --git a/TbsCore/Models/CombatModels/Combat.cs b/TbsCore/Models/CombatModels/Combat.cs index c08189a43..48d1d5021 100644 --- a/TbsCore/Models/CombatModels/Combat.cs +++ b/TbsCore/Models/CombatModels/Combat.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using TbsCore.TravianData; using static TbsCore.Helpers.Classificator; @@ -92,7 +90,7 @@ private int GetVillDeff() // getDefAbsolute var offPts = this.Attacker.Army.GetOffense(); var defPts = Deffender.GetDeffense(); var (off, def) = GetAducedDef(offPts, defPts); - baseState = ( off, def ); + baseState = (off, def); return baseState; } diff --git a/TbsCore/Models/CombatModels/CombatArmy.cs b/TbsCore/Models/CombatModels/CombatArmy.cs index ffdae6fe4..c9af55cc0 100644 --- a/TbsCore/Models/CombatModels/CombatArmy.cs +++ b/TbsCore/Models/CombatModels/CombatArmy.cs @@ -1,8 +1,4 @@ using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using TbsCore.TravianData; namespace TbsCore.Models.CombatModels { @@ -25,7 +21,7 @@ public class CombatArmy : CombatArmyBase if ((Hero?.Info?.Health ?? 0) == 0) return unitsOff; var heroOff = Hero.GetOff(); - + var (troop, boost) = Hero.GetWeaponBoost(); var weaponBoost = CombatPoints.Both(base.Troops[(int)troop % 10] * boost); diff --git a/TbsCore/Models/CombatModels/CombatArmyBase.cs b/TbsCore/Models/CombatModels/CombatArmyBase.cs index 654d15eb4..5cd7ff2b5 100644 --- a/TbsCore/Models/CombatModels/CombatArmyBase.cs +++ b/TbsCore/Models/CombatModels/CombatArmyBase.cs @@ -1,7 +1,5 @@ using System; -using System.Collections.Generic; using System.Linq; -using System.Text; using TbsCore.Helpers; using TbsCore.Models.TroopsModels; using TbsCore.TravianData; diff --git a/TbsCore/Models/CombatModels/CombatAttacker.cs b/TbsCore/Models/CombatModels/CombatAttacker.cs index e1b46cbfd..3570e0d58 100644 --- a/TbsCore/Models/CombatModels/CombatAttacker.cs +++ b/TbsCore/Models/CombatModels/CombatAttacker.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace TbsCore.Models.CombatModels +namespace TbsCore.Models.CombatModels { public class CombatAttacker { @@ -10,7 +6,7 @@ public class CombatAttacker /// Troops, hero, tribe /// public CombatArmy Army { get; set; } - + /// /// Population of the attacker, morale bonus depends on it /// diff --git a/TbsCore/Models/CombatModels/CombatDeffender.cs b/TbsCore/Models/CombatModels/CombatDeffender.cs index 9a15f859a..11c606342 100644 --- a/TbsCore/Models/CombatModels/CombatDeffender.cs +++ b/TbsCore/Models/CombatModels/CombatDeffender.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Collections.Generic; using TbsCore.Helpers; namespace TbsCore.Models.CombatModels @@ -11,12 +9,12 @@ public class CombatDeffender /// List of (Troops, hero, tribe), since deffender can have armies from multiple accounts / villages /// public List Armies { get; set; } - + /// /// Population of the deffender, morale bonus depends on it /// public int Population { get; set; } - + /// /// Level of the wall inside the village /// @@ -26,7 +24,7 @@ public class CombatDeffender /// Level of Palace / Residence /// public int PalaceLevel { get; set; } - + /// /// Which tribe is the deffender. Wall bonus depends on the tribe /// diff --git a/TbsCore/Models/CombatModels/CombatHero.cs b/TbsCore/Models/CombatModels/CombatHero.cs index 182bbf73a..17ddc3976 100644 --- a/TbsCore/Models/CombatModels/CombatHero.cs +++ b/TbsCore/Models/CombatModels/CombatHero.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using TbsCore.Helpers; using TbsCore.Models.AccModels; -using TbsCore.Models.TroopsModels; using static TbsCore.Helpers.Classificator; namespace TbsCore.Models.CombatModels @@ -17,7 +16,7 @@ public class CombatHero /// Hero power, offensive / deffensive bonus /// public HeroInfo Info { get; set; } - + /// /// Hero items (natar horn, shield, right hand items) /// diff --git a/TbsCore/Models/CombatModels/CombatPoints.cs b/TbsCore/Models/CombatModels/CombatPoints.cs index 7e7e35a85..453bcb434 100644 --- a/TbsCore/Models/CombatModels/CombatPoints.cs +++ b/TbsCore/Models/CombatModels/CombatPoints.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; namespace TbsCore.Models.CombatModels { @@ -31,7 +29,7 @@ public static CombatPoints Both(int value) public static CombatPoints Sum(CombatPoints[] arr) { var total = CombatPoints.Zero(); - foreach(var cp in arr) + foreach (var cp in arr) { total.i += cp.i; total.c += cp.c; @@ -51,11 +49,13 @@ public CombatPoints(double inf, double cav) this.c = (long)Math.Round(cav, MidpointRounding.AwayFromZero); } - public void Add(CombatPoints that) { + public void Add(CombatPoints that) + { this.i += that.i; this.c += that.c; } - public CombatPoints Mul(double m) { + public CombatPoints Mul(double m) + { return new CombatPoints(this.i * m, this.c * m); } //public CombatPoints Mask(CombatPoints mask) { diff --git a/TbsCore/Models/JsObjects/BldJsObject.cs b/TbsCore/Models/JsObjects/BldJsObject.cs index fca6e5eed..afe4f4354 100644 --- a/TbsCore/Models/JsObjects/BldJsObject.cs +++ b/TbsCore/Models/JsObjects/BldJsObject.cs @@ -1,9 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using System.Globalization; -using Newtonsoft.Json; -using Newtonsoft.Json.Converters; +using Newtonsoft.Json; using TbsCore.Helpers; namespace TbsCore.Models.JsObjects diff --git a/TbsCore/Models/JsObjects/ResourcesJsObject.cs b/TbsCore/Models/JsObjects/ResourcesJsObject.cs index 894859d1e..f935be644 100644 --- a/TbsCore/Models/JsObjects/ResourcesJsObject.cs +++ b/TbsCore/Models/JsObjects/ResourcesJsObject.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TbsCore.Models.ResourceModels; +using TbsCore.Models.ResourceModels; namespace TbsCore.Models.JsObjects { diff --git a/TbsCore/Models/Logging/Logger.cs b/TbsCore/Models/Logging/Logger.cs index 1c93fe950..6bb16bc72 100644 --- a/TbsCore/Models/Logging/Logger.cs +++ b/TbsCore/Models/Logging/Logger.cs @@ -1,5 +1,5 @@ -using System; -using Serilog; +using Serilog; +using System; using TbsCore.Extensions; using TbsCore.Tasks; diff --git a/TbsCore/Models/Logging/SerilogSingleton.cs b/TbsCore/Models/Logging/SerilogSingleton.cs index 836851ae7..2010b0754 100644 --- a/TbsCore/Models/Logging/SerilogSingleton.cs +++ b/TbsCore/Models/Logging/SerilogSingleton.cs @@ -1,5 +1,5 @@ -using System.Text; -using Serilog; +using Serilog; +using System.Text; namespace TbsCore.Models.Logging { diff --git a/TbsCore/Models/MapModels/Coordinates.cs b/TbsCore/Models/MapModels/Coordinates.cs index e99ae6086..a4397f63b 100644 --- a/TbsCore/Models/MapModels/Coordinates.cs +++ b/TbsCore/Models/MapModels/Coordinates.cs @@ -1,6 +1,4 @@ using System; -using System.ComponentModel; -using System.Globalization; using TbsCore.Models.AccModels; namespace TbsCore.Models.MapModels @@ -37,7 +35,7 @@ public bool Equals(Coordinates other) // Used in cmd=mapPositionData, gets the map JSON where public int GetKid(Account acc) { - return 1 + ((acc.AccInfo.MapSize - this.y) * (acc.AccInfo.MapSize* 2 + 1)) + acc.AccInfo.MapSize + this.x; + return 1 + ((acc.AccInfo.MapSize - this.y) * (acc.AccInfo.MapSize * 2 + 1)) + acc.AccInfo.MapSize + this.x; } /// diff --git a/TbsCore/Models/ResourceModels/MerchantsUnderWay.cs b/TbsCore/Models/ResourceModels/MerchantsUnderWay.cs index 153658904..5e6b17eef 100644 --- a/TbsCore/Models/ResourceModels/MerchantsUnderWay.cs +++ b/TbsCore/Models/ResourceModels/MerchantsUnderWay.cs @@ -1,5 +1,4 @@ using System; -using TbsCore.Models.ResourceModels; namespace TbsCore.Models.ResourceModels { diff --git a/TbsCore/Models/Settings/GeneralSettings.cs b/TbsCore/Models/Settings/GeneralSettings.cs index ab08b02e1..a824928f2 100644 --- a/TbsCore/Models/Settings/GeneralSettings.cs +++ b/TbsCore/Models/Settings/GeneralSettings.cs @@ -1,7 +1,4 @@ -using System.Collections.Generic; -using static TbsCore.Helpers.Classificator; - -namespace TbsCore.Models.Settings +namespace TbsCore.Models.Settings { public class GeneralSettings { diff --git a/TbsCore/Models/SideBarModels/Quest.cs b/TbsCore/Models/SideBarModels/Quest.cs index 4bdbb1e5b..310cac3f7 100644 --- a/TbsCore/Models/SideBarModels/Quest.cs +++ b/TbsCore/Models/SideBarModels/Quest.cs @@ -1,6 +1,4 @@ -using TbsCore.Models.SideBarModels; - -namespace TbsCore.Models.SideBarModels +namespace TbsCore.Models.SideBarModels { public class Quest { diff --git a/TbsCore/Models/TroopsModels/FarmList.cs b/TbsCore/Models/TroopsModels/FarmList.cs index 0eedfa15c..4bf97ebe4 100644 --- a/TbsCore/Models/TroopsModels/FarmList.cs +++ b/TbsCore/Models/TroopsModels/FarmList.cs @@ -1,6 +1,5 @@ using System.Collections.Generic; using TbsCore.Models.MapModels; -using TbsCore.Models.TroopsModels; namespace TbsCore.Models.TroopsModels { diff --git a/TbsCore/Models/TroopsModels/TroopLevel.cs b/TbsCore/Models/TroopsModels/TroopLevel.cs index 7fa4ccc64..ab5d51cfa 100644 --- a/TbsCore/Models/TroopsModels/TroopLevel.cs +++ b/TbsCore/Models/TroopsModels/TroopLevel.cs @@ -1,6 +1,6 @@ using System; -using TbsCore.Models.ResourceModels; using TbsCore.Helpers; +using TbsCore.Models.ResourceModels; namespace TbsCore.Models.TroopsModels { diff --git a/TbsCore/Models/TroopsModels/TroopsBase.cs b/TbsCore/Models/TroopsModels/TroopsBase.cs index a4fa0ba19..766b1664b 100644 --- a/TbsCore/Models/TroopsModels/TroopsBase.cs +++ b/TbsCore/Models/TroopsModels/TroopsBase.cs @@ -9,7 +9,7 @@ namespace TbsCore.Models.TroopsModels /// public class TroopsBase { - public TroopsBase() {} + public TroopsBase() { } public TroopsBase(int[] arr, Classificator.TribeEnum? tribe) { this.Troops = arr; @@ -33,7 +33,7 @@ public List GetTroopList() public long TotalBaseDeff() { long totalDeff = 0; - foreach(var troop in GetTroopList()) + foreach (var troop in GetTroopList()) { totalDeff += troop.Count * (TroopsData.TroopDeffenseInfrantry(troop.Type) + TroopsData.TroopDeffenseCavalry(troop.Type)); } diff --git a/TbsCore/Models/TroopsModels/VillTroops.cs b/TbsCore/Models/TroopsModels/VillTroops.cs index 1e867d709..48712888c 100644 --- a/TbsCore/Models/TroopsModels/VillTroops.cs +++ b/TbsCore/Models/TroopsModels/VillTroops.cs @@ -1,5 +1,4 @@ using System.Collections.Generic; -using TbsCore.Models.AccModels; using TbsCore.Helpers; namespace TbsCore.Models.TroopsModels diff --git a/TbsCore/Models/TroopsMovementModels/SendWaveModel.cs b/TbsCore/Models/TroopsMovementModels/SendWaveModel.cs index afcdf1462..3c5ddaea7 100644 --- a/TbsCore/Models/TroopsMovementModels/SendWaveModel.cs +++ b/TbsCore/Models/TroopsMovementModels/SendWaveModel.cs @@ -7,7 +7,7 @@ public class SendWaveModel : TroopsSendModel /// If delay is set, Arrival will be ignored for all proceeding waves /// public int DelayMs { get; set; } - + /// /// Dirty hack like one above. 19 troops + catapult /// diff --git a/TbsCore/Models/TroopsMovementModels/TroopMovementDorf1.cs b/TbsCore/Models/TroopsMovementModels/TroopMovementDorf1.cs index dc139f8e1..4a5131c59 100644 --- a/TbsCore/Models/TroopsMovementModels/TroopMovementDorf1.cs +++ b/TbsCore/Models/TroopsMovementModels/TroopMovementDorf1.cs @@ -1,6 +1,4 @@ using System; -using System.Collections.Generic; -using System.Text; using TbsCore.Helpers; namespace TbsCore.Models.TroopsMovementModels diff --git a/TbsCore/Models/TroopsMovementModels/TroopsSendModel.cs b/TbsCore/Models/TroopsMovementModels/TroopsSendModel.cs index db4f3cff3..d8a30c4c1 100644 --- a/TbsCore/Models/TroopsMovementModels/TroopsSendModel.cs +++ b/TbsCore/Models/TroopsMovementModels/TroopsSendModel.cs @@ -1,7 +1,4 @@ -using System; -using TbsCore.Models.MapModels; -using TbsCore.Helpers; -using static TbsCore.Helpers.Classificator; +using static TbsCore.Helpers.Classificator; namespace TbsCore.Models.SendTroopsModels { diff --git a/TbsCore/Models/VillageModels/VillBuilding.cs b/TbsCore/Models/VillageModels/VillBuilding.cs index 6dc8e0f08..a573e6c0d 100644 --- a/TbsCore/Models/VillageModels/VillBuilding.cs +++ b/TbsCore/Models/VillageModels/VillBuilding.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.BuildingModels; -using TbsCore.Helpers; using TbsCore.TravianData; namespace TbsCore.Models.VillageModels diff --git a/TbsCore/Models/VillageModels/VillDeffing.cs b/TbsCore/Models/VillageModels/VillDeffing.cs index 574794036..0c97f79f1 100644 --- a/TbsCore/Models/VillageModels/VillDeffing.cs +++ b/TbsCore/Models/VillageModels/VillDeffing.cs @@ -1,8 +1,4 @@ -using System.Collections.Generic; -using TbsCore.Models.SendTroopsModels; -using TbsCore.Models.VillageModels; - -namespace TbsCore.Models.VillageModels +namespace TbsCore.Models.VillageModels { public class VillDeffing { diff --git a/TbsCore/Models/VillageModels/VillTroopMovements.cs b/TbsCore/Models/VillageModels/VillTroopMovements.cs index b9568df06..2d4f74668 100644 --- a/TbsCore/Models/VillageModels/VillTroopMovements.cs +++ b/TbsCore/Models/VillageModels/VillTroopMovements.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Collections.Generic; using TbsCore.Models.SendTroopsModels; using TbsCore.Models.TroopsMovementModels; @@ -8,7 +6,7 @@ namespace TbsCore.Models.VillageModels { public class VillTroopMovements { - public void Init() + public void Init() { IncomingAttacks = new List(); } diff --git a/TbsCore/Models/VillageModels/VillUnfinishedTask.cs b/TbsCore/Models/VillageModels/VillUnfinishedTask.cs index d27b89435..d00d83218 100644 --- a/TbsCore/Models/VillageModels/VillUnfinishedTask.cs +++ b/TbsCore/Models/VillageModels/VillUnfinishedTask.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TbsCore.Models.ResourceModels; +using TbsCore.Models.ResourceModels; using TbsCore.Tasks; namespace TbsCore.Models.VillageModels diff --git a/TbsCore/Models/VillageModels/Village.cs b/TbsCore/Models/VillageModels/Village.cs index 6d8d92765..4094b1556 100644 --- a/TbsCore/Models/VillageModels/Village.cs +++ b/TbsCore/Models/VillageModels/Village.cs @@ -1,10 +1,10 @@ -using System.Collections.Generic; -using Newtonsoft.Json; +using Newtonsoft.Json; +using System.Collections.Generic; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.MapModels; using TbsCore.Models.Settings; using TbsCore.Models.TroopsModels; -using TbsCore.Helpers; namespace TbsCore.Models.VillageModels { diff --git a/TbsCore/Models/World/AccServerData.cs b/TbsCore/Models/World/AccServerData.cs index 6526de677..8807cfdcc 100644 --- a/TbsCore/Models/World/AccServerData.cs +++ b/TbsCore/Models/World/AccServerData.cs @@ -1,8 +1,5 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Collections.Generic; using TbsCore.Models.AttackModels; -using TbsCore.Models.MapModels; namespace TbsCore.Models.World { diff --git a/TbsCore/Models/World/TravianUser.cs b/TbsCore/Models/World/TravianUser.cs index 22bee3f57..63f3f5b3c 100644 --- a/TbsCore/Models/World/TravianUser.cs +++ b/TbsCore/Models/World/TravianUser.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; namespace TbsCore.Models.AttackModels { @@ -10,7 +9,7 @@ public class TravianUser // Tribe // Ally // Hero!! For checking if anything changed, to recognize fake attacks - + public List Villages { get; set; } } diff --git a/TbsCore/Models/World/TravianVillage.cs b/TbsCore/Models/World/TravianVillage.cs index 75ce37c02..2d9dd5504 100644 --- a/TbsCore/Models/World/TravianVillage.cs +++ b/TbsCore/Models/World/TravianVillage.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; -using TbsCore.Models.MapModels; +using TbsCore.Models.MapModels; namespace TbsCore.Models.AttackModels { diff --git a/TbsCore/Parsers/AdventureParser.cs b/TbsCore/Parsers/AdventureParser.cs index 8bbae1601..4b29305e5 100644 --- a/TbsCore/Parsers/AdventureParser.cs +++ b/TbsCore/Parsers/AdventureParser.cs @@ -1,7 +1,7 @@ using System.Collections.Generic; using System.Linq; -using TbsCore.Models; using TbsCore.Helpers; +using TbsCore.Models; using static TbsCore.Helpers.Classificator; namespace TbsCore.Parsers diff --git a/TbsCore/Parsers/AttackParser.cs b/TbsCore/Parsers/AttackParser.cs index e450c923d..75de1cadb 100644 --- a/TbsCore/Parsers/AttackParser.cs +++ b/TbsCore/Parsers/AttackParser.cs @@ -1,8 +1,6 @@ using HtmlAgilityPack; -using System; using System.Collections.Generic; using System.Linq; -using System.Text; using TbsCore.Helpers; using TbsCore.Models.AttackModels; using TbsCore.Models.ResourceModels; @@ -47,7 +45,7 @@ internal static AttackReport ParseAttack(HtmlAgilityPack.HtmlDocument html) // Deffender List var attacker = content.Descendants("div").First(x => x.HasClass("attacker")); var deffender = content.Descendants("div").First(x => x.HasClass("defender")); - + report.Deffender = ParseHeader(deffender); report.Attacker = ParseHeader(attacker); @@ -65,8 +63,8 @@ internal static AttackReport ParseAttack(HtmlAgilityPack.HtmlDocument html) private static CombatParticipant ParseHeader(HtmlNode header) { - var headline = header.Descendants("div").First(x => x.HasClass("troopHeadline")).ChildNodes.First(x=>x.Name == "div"); - var ahref = headline.ChildNodes.Where(x=>x.Name == "a").ToArray(); + var headline = header.Descendants("div").First(x => x.HasClass("troopHeadline")).ChildNodes.First(x => x.Name == "div"); + var ahref = headline.ChildNodes.Where(x => x.Name == "a").ToArray(); var ret = new CombatParticipant(); ret.Username = ahref[0].InnerText; diff --git a/TbsCore/Parsers/HeroParser.cs b/TbsCore/Parsers/HeroParser.cs index f9412d54d..7ae43f8b9 100644 --- a/TbsCore/Parsers/HeroParser.cs +++ b/TbsCore/Parsers/HeroParser.cs @@ -2,9 +2,9 @@ using System; using System.Collections.Generic; using System.Linq; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.TroopsModels; -using TbsCore.Helpers; namespace TbsCore.Parsers { diff --git a/TbsCore/Parsers/InfrastructureParser.cs b/TbsCore/Parsers/InfrastructureParser.cs index 37e68f998..15d5dfb63 100644 --- a/TbsCore/Parsers/InfrastructureParser.cs +++ b/TbsCore/Parsers/InfrastructureParser.cs @@ -1,11 +1,11 @@ -using System; +using HtmlAgilityPack; +using System; using System.Collections.Generic; using System.Linq; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; -using TbsCore.Helpers; using TbsCore.TravianData; -using HtmlAgilityPack; namespace TbsCore.Parsers { diff --git a/TbsCore/Parsers/LeftbarParser.cs b/TbsCore/Parsers/LeftbarParser.cs index eb500080a..aceecd63e 100644 --- a/TbsCore/Parsers/LeftbarParser.cs +++ b/TbsCore/Parsers/LeftbarParser.cs @@ -1,6 +1,6 @@ using System.Linq; -using TbsCore.Models.AccModels; using TbsCore.Helpers; +using TbsCore.Models.AccModels; namespace TbsCore.Parsers { diff --git a/TbsCore/Parsers/MarketParser.cs b/TbsCore/Parsers/MarketParser.cs index 7f2f191e6..0096297b7 100644 --- a/TbsCore/Parsers/MarketParser.cs +++ b/TbsCore/Parsers/MarketParser.cs @@ -4,8 +4,6 @@ using System.Linq; using TbsCore.Models.ResourceModels; -using TbsCore.TravianData; - namespace TbsCore.Parsers { public static class MarketParser diff --git a/TbsCore/Parsers/OverviewParser.cs b/TbsCore/Parsers/OverviewParser.cs index f9827e284..e25641efe 100644 --- a/TbsCore/Parsers/OverviewParser.cs +++ b/TbsCore/Parsers/OverviewParser.cs @@ -1,9 +1,9 @@ using HtmlAgilityPack; using System; using System.Linq; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.TroopsModels; -using TbsCore.Helpers; namespace TbsCore.Parsers { diff --git a/TbsCore/Parsers/ProfileParser.cs b/TbsCore/Parsers/ProfileParser.cs index 776e5e975..58a00c75b 100644 --- a/TbsCore/Parsers/ProfileParser.cs +++ b/TbsCore/Parsers/ProfileParser.cs @@ -1,13 +1,8 @@ using HtmlAgilityPack; -using System; -using System.Collections.Generic; using System.Linq; -using System.Text; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.MapModels; -using TbsCore.Models.VillageModels; -using TbsCore.Helpers; -using TbsCore.Parsers; namespace TbsCore.Parsers { diff --git a/TbsCore/Parsers/ResourceParser.cs b/TbsCore/Parsers/ResourceParser.cs index e3dc61377..2eedb9f8b 100644 --- a/TbsCore/Parsers/ResourceParser.cs +++ b/TbsCore/Parsers/ResourceParser.cs @@ -2,9 +2,9 @@ using System; using System.Collections.Generic; using System.Linq; +using TbsCore.Helpers; using TbsCore.Models.ResourceModels; using TbsCore.Models.VillageModels; -using TbsCore.Helpers; namespace TbsCore.Parsers { diff --git a/TbsCore/Parsers/RightBarParser.cs b/TbsCore/Parsers/RightBarParser.cs index bb50ee89e..9c3d992fc 100644 --- a/TbsCore/Parsers/RightBarParser.cs +++ b/TbsCore/Parsers/RightBarParser.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; +using TbsCore.Helpers; using TbsCore.Models.MapModels; using TbsCore.Models.SideBarModels; -using TbsCore.Helpers; using static TbsCore.Helpers.Classificator; namespace TbsCore.Parsers diff --git a/TbsCore/Parsers/TroopsMovementParser.cs b/TbsCore/Parsers/TroopsMovementParser.cs index 15b2406c4..9523c0e04 100644 --- a/TbsCore/Parsers/TroopsMovementParser.cs +++ b/TbsCore/Parsers/TroopsMovementParser.cs @@ -3,13 +3,12 @@ using System.Collections.Generic; using System.Linq; using System.Net; +using TbsCore.Helpers; using TbsCore.Models.AccModels; +using TbsCore.Models.MapModels; using TbsCore.Models.SendTroopsModels; using TbsCore.Models.TroopsMovementModels; -using TbsCore.Helpers; using static TbsCore.Helpers.Classificator; -using TbsCore.Models.TroopsModels; -using TbsCore.Models.MapModels; namespace TbsCore.Parsers { diff --git a/TbsCore/Parsers/TroopsParser.cs b/TbsCore/Parsers/TroopsParser.cs index 6bc579fd8..76e6e754b 100644 --- a/TbsCore/Parsers/TroopsParser.cs +++ b/TbsCore/Parsers/TroopsParser.cs @@ -2,9 +2,9 @@ using System; using System.Collections.Generic; using System.Linq; +using TbsCore.Helpers; using TbsCore.Models.ResourceModels; using TbsCore.Models.TroopsModels; -using TbsCore.Helpers; namespace TbsCore.Parsers { diff --git a/TbsCore/Tasks/Browser/ChangeAccess.cs b/TbsCore/Tasks/Browser/ChangeAccess.cs index b74ab15fd..5d49ab71f 100644 --- a/TbsCore/Tasks/Browser/ChangeAccess.cs +++ b/TbsCore/Tasks/Browser/ChangeAccess.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; -using TbsCore.Models.AccModels; using TbsCore.Helpers; +using TbsCore.Models.AccModels; namespace TbsCore.Tasks.Browser { diff --git a/TbsCore/Tasks/Browser/ReopenDriver.cs b/TbsCore/Tasks/Browser/ReopenDriver.cs index 051d01716..fc3dfef37 100644 --- a/TbsCore/Tasks/Browser/ReopenDriver.cs +++ b/TbsCore/Tasks/Browser/ReopenDriver.cs @@ -1,8 +1,5 @@ -using System; -using System.Threading.Tasks; +using System.Threading.Tasks; using TbsCore.Models.AccModels; -using TbsCore.Helpers; -using System.Linq; namespace TbsCore.Tasks.Browser { diff --git a/TbsCore/Tasks/Browser/TaskSleep.cs b/TbsCore/Tasks/Browser/TaskSleep.cs index 6c5caceff..746fe8330 100644 --- a/TbsCore/Tasks/Browser/TaskSleep.cs +++ b/TbsCore/Tasks/Browser/TaskSleep.cs @@ -1,7 +1,7 @@ using System; +using System.Linq; using System.Threading.Tasks; using TbsCore.Models.AccModels; -using System.Linq; namespace TbsCore.Tasks.Browser { diff --git a/TbsCore/Tasks/Browser/TimeSleep.cs b/TbsCore/Tasks/Browser/TimeSleep.cs index 296adb94b..1421e4f0d 100644 --- a/TbsCore/Tasks/Browser/TimeSleep.cs +++ b/TbsCore/Tasks/Browser/TimeSleep.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; -using TbsCore.Models.AccModels; using TbsCore.Helpers; +using TbsCore.Models.AccModels; namespace TbsCore.Tasks.Browser { diff --git a/TbsCore/Tasks/Farm/AttackOasis.cs b/TbsCore/Tasks/Farm/AttackOasis.cs index 81d2e01ff..e2d53bcbd 100644 --- a/TbsCore/Tasks/Farm/AttackOasis.cs +++ b/TbsCore/Tasks/Farm/AttackOasis.cs @@ -1,15 +1,14 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Net; using System.Threading.Tasks; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.MapModels; using TbsCore.Models.SendTroopsModels; +using TbsCore.Models.TroopsModels; using TbsCore.Models.VillageModels; using TbsCore.TravianData; -using TbsCore.Helpers; -using TbsCore.Models.TroopsModels; namespace TbsCore.Tasks.LowLevel { diff --git a/TbsCore/Tasks/Farm/ScoutPlayer.cs b/TbsCore/Tasks/Farm/ScoutPlayer.cs index 69a59f00a..6e28d8a89 100644 --- a/TbsCore/Tasks/Farm/ScoutPlayer.cs +++ b/TbsCore/Tasks/Farm/ScoutPlayer.cs @@ -1,12 +1,7 @@ using System; -using System.Collections.Generic; -using System.Linq; using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.Models.MapModels; -using TbsCore.Models.TroopsModels; using TbsCore.Helpers; -using TbsCore.Parsers; +using TbsCore.Models.AccModels; using TbsCore.Tasks.LowLevel; using TbsCore.TravianData; diff --git a/TbsCore/Tasks/Farm/SendFLs.cs b/TbsCore/Tasks/Farm/SendFLs.cs index 1bccdfaf4..676e6ef6d 100644 --- a/TbsCore/Tasks/Farm/SendFLs.cs +++ b/TbsCore/Tasks/Farm/SendFLs.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; -using TbsCore.Models.AccModels; using TbsCore.Helpers; +using TbsCore.Models.AccModels; using TbsCore.Tasks.LowLevel; namespace TbsCore.Tasks.SecondLevel diff --git a/TbsCore/Tasks/Farm/SendReinforcementScouts.cs b/TbsCore/Tasks/Farm/SendReinforcementScouts.cs index 37a6aabfc..95710c29e 100644 --- a/TbsCore/Tasks/Farm/SendReinforcementScouts.cs +++ b/TbsCore/Tasks/Farm/SendReinforcementScouts.cs @@ -1,16 +1,10 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Threading.Tasks; +using System.Threading.Tasks; +using TbsCore.Helpers; using TbsCore.Models.AccModels; -using TbsCore.Models.MapModels; using TbsCore.Models.SendTroopsModels; -using TbsCore.Models.VillageModels; -using TbsCore.TravianData; -using TbsCore.Helpers; -using TbsCore.Tasks.LowLevel; using TbsCore.Models.TroopsModels; +using TbsCore.Tasks.LowLevel; +using TbsCore.TravianData; namespace TbsCore.Tasks.SecondLevel { @@ -25,7 +19,7 @@ public override async Task Execute(Account acc) if (Scouts == 0) return TaskRes.Executed; bool stop = false; - foreach(var vill in acc.Villages) + foreach (var vill in acc.Villages) { if (vill == this.Vill || stop) continue; base.TroopsMovement = new TroopsSendModel(); @@ -63,7 +57,7 @@ private int[] ScoutsOnly(Account acc) break; } } - return ret; + return ret; } } } \ No newline at end of file diff --git a/TbsCore/Tasks/Farm/SendWaves.cs b/TbsCore/Tasks/Farm/SendWaves.cs index f60ecd429..8db56969f 100644 --- a/TbsCore/Tasks/Farm/SendWaves.cs +++ b/TbsCore/Tasks/Farm/SendWaves.cs @@ -4,10 +4,9 @@ using System.Linq; using System.Net.NetworkInformation; using System.Threading.Tasks; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.SendTroopsModels; -using TbsCore.TravianData; -using TbsCore.Helpers; using TbsCore.Parsers; namespace TbsCore.Tasks.LowLevel diff --git a/TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs b/TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs index 1d6b6b2fd..cec9242ab 100644 --- a/TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs +++ b/TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs @@ -1,12 +1,8 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using TbsCore.Models.AccModels; -using TbsCore.Models.MapModels; using TbsCore.Models.TroopsModels; -using TbsCore.Helpers; -using TbsCore.Parsers; using TbsCore.Tasks.LowLevel; namespace TbsCore.Tasks.SecondLevel diff --git a/TbsCore/Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs b/TbsCore/Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs index bd54f1251..29ca10388 100644 --- a/TbsCore/Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs +++ b/TbsCore/Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs @@ -1,5 +1,4 @@ -using System; -using System.Linq; +using System.Linq; using System.Threading.Tasks; using TbsCore.Models.AccModels; using TbsCore.Tasks.LowLevel; @@ -19,7 +18,7 @@ public override async Task Execute(Account acc) var villages = base.Profile.Villages .Where(vill => MinPop < vill.Population && vill.Population < MaxPop) - .OrderBy(x=>x.Coordinates.CalculateDistance(acc, this.Vill.Coordinates)) + .OrderBy(x => x.Coordinates.CalculateDistance(acc, this.Vill.Coordinates)) .ToList(); for (int i = 0; i < villages.Count; i++) diff --git a/TbsCore/Tasks/Farm/TransitToMainAcc.cs b/TbsCore/Tasks/Farm/TransitToMainAcc.cs index 4c762b134..e36453253 100644 --- a/TbsCore/Tasks/Farm/TransitToMainAcc.cs +++ b/TbsCore/Tasks/Farm/TransitToMainAcc.cs @@ -1,8 +1,8 @@ using System; using System.Threading.Tasks; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.MapModels; -using TbsCore.Helpers; namespace TbsCore.Tasks.LowLevel { diff --git a/TbsCore/Tasks/Farm/UpdateFarmLists.cs b/TbsCore/Tasks/Farm/UpdateFarmLists.cs index 339bb0bd7..2612618ff 100644 --- a/TbsCore/Tasks/Farm/UpdateFarmLists.cs +++ b/TbsCore/Tasks/Farm/UpdateFarmLists.cs @@ -1,13 +1,13 @@ -using System; +using HtmlAgilityPack; +using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; -using TbsCore.Models.AccModels; using TbsCore.Helpers; +using TbsCore.Models.AccModels; +using TbsCore.Models.TroopsModels; using TbsCore.Parsers; using static TbsCore.Helpers.Classificator; -using HtmlAgilityPack; -using TbsCore.Models.TroopsModels; -using System.Collections.Generic; namespace TbsCore.Tasks.LowLevel { diff --git a/TbsCore/Tasks/Others/HeroSetPoints.cs b/TbsCore/Tasks/Others/HeroSetPoints.cs index 8a939e946..b03e3bae1 100644 --- a/TbsCore/Tasks/Others/HeroSetPoints.cs +++ b/TbsCore/Tasks/Others/HeroSetPoints.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; -using TbsCore.Models.AccModels; using TbsCore.Helpers; +using TbsCore.Models.AccModels; namespace TbsCore.Tasks.LowLevel { diff --git a/TbsCore/Tasks/Others/ReviveHero.cs b/TbsCore/Tasks/Others/ReviveHero.cs index 8d1aacd0c..b4f9514e0 100644 --- a/TbsCore/Tasks/Others/ReviveHero.cs +++ b/TbsCore/Tasks/Others/ReviveHero.cs @@ -1,8 +1,8 @@ -using System; +using OpenQA.Selenium; +using System; using System.Threading.Tasks; -using TbsCore.Models.AccModels; using TbsCore.Helpers; -using OpenQA.Selenium; +using TbsCore.Models.AccModels; namespace TbsCore.Tasks.LowLevel { diff --git a/TbsCore/Tasks/Others/SendResFillTroops.cs b/TbsCore/Tasks/Others/SendResFillTroops.cs index ad063d6c6..82c8bb0b9 100644 --- a/TbsCore/Tasks/Others/SendResFillTroops.cs +++ b/TbsCore/Tasks/Others/SendResFillTroops.cs @@ -1,9 +1,9 @@ using System; using System.Linq; using System.Threading.Tasks; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; -using TbsCore.Helpers; using TbsCore.TravianData; namespace TbsCore.Tasks.LowLevel diff --git a/TbsCore/Tasks/Others/SendResToMain.cs b/TbsCore/Tasks/Others/SendResToMain.cs index 21beab772..3f9711d53 100644 --- a/TbsCore/Tasks/Others/SendResToMain.cs +++ b/TbsCore/Tasks/Others/SendResToMain.cs @@ -1,8 +1,8 @@ using System; using System.Threading.Tasks; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.Settings; -using TbsCore.Helpers; namespace TbsCore.Tasks.LowLevel { diff --git a/TbsCore/Tasks/Others/SendResources.cs b/TbsCore/Tasks/Others/SendResources.cs index 0aec0c751..3533f5221 100644 --- a/TbsCore/Tasks/Others/SendResources.cs +++ b/TbsCore/Tasks/Others/SendResources.cs @@ -1,10 +1,10 @@ using System; using System.Linq; using System.Threading.Tasks; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.MapModels; using TbsCore.Models.ResourceModels; -using TbsCore.Helpers; namespace TbsCore.Tasks.LowLevel { diff --git a/TbsCore/Tasks/Others/SetCapital.cs b/TbsCore/Tasks/Others/SetCapital.cs index c719f2a29..b4758845a 100644 --- a/TbsCore/Tasks/Others/SetCapital.cs +++ b/TbsCore/Tasks/Others/SetCapital.cs @@ -9,7 +9,7 @@ public class SetCapital : BotTask { public override async Task Execute(Account acc) { - if(!Vill.Build.Buildings.Any(x => x.Type == Classificator.BuildingEnum.Palace)) + if (!Vill.Build.Buildings.Any(x => x.Type == Classificator.BuildingEnum.Palace)) { // TODO: Check for residence, if it exists demolish it and build palace acc.Logger.Information("Palace was not found in the village!"); diff --git a/TbsCore/Tasks/Others/TTWarsExpandStorage.cs b/TbsCore/Tasks/Others/TTWarsExpandStorage.cs index a4b692f47..44a7d4401 100644 --- a/TbsCore/Tasks/Others/TTWarsExpandStorage.cs +++ b/TbsCore/Tasks/Others/TTWarsExpandStorage.cs @@ -1,8 +1,8 @@ using System; using System.Linq; using System.Threading.Tasks; -using TbsCore.Models.AccModels; using TbsCore.Helpers; +using TbsCore.Models.AccModels; namespace TbsCore.Tasks.LowLevel { diff --git a/TbsCore/Tasks/Others/TTWarsPlusAndBoost.cs b/TbsCore/Tasks/Others/TTWarsPlusAndBoost.cs index 116c54778..62b4704d3 100644 --- a/TbsCore/Tasks/Others/TTWarsPlusAndBoost.cs +++ b/TbsCore/Tasks/Others/TTWarsPlusAndBoost.cs @@ -1,7 +1,7 @@ using System.Linq; using System.Threading.Tasks; -using TbsCore.Models.AccModels; using TbsCore.Helpers; +using TbsCore.Models.AccModels; namespace TbsCore.Tasks.LowLevel { diff --git a/TbsCore/Tasks/Update/CheckAttacks.cs b/TbsCore/Tasks/Update/CheckAttacks.cs index ca0900a17..cefd74c59 100644 --- a/TbsCore/Tasks/Update/CheckAttacks.cs +++ b/TbsCore/Tasks/Update/CheckAttacks.cs @@ -3,9 +3,9 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.SendTroopsModels; -using TbsCore.Helpers; using TbsCore.Models.VillageModels; using TbsCore.Parsers; diff --git a/TbsCore/Tasks/Update/CheckProfile.cs b/TbsCore/Tasks/Update/CheckProfile.cs index 68e5bc0af..019311e61 100644 --- a/TbsCore/Tasks/Update/CheckProfile.cs +++ b/TbsCore/Tasks/Update/CheckProfile.cs @@ -11,7 +11,8 @@ namespace TbsCore.Tasks.LowLevel public class CheckProfile : BotTask { public int UserId { get; set; } - public TravianUser Profile { get; } = new TravianUser() { + public TravianUser Profile { get; } = new TravianUser() + { Villages = new List() }; diff --git a/TbsCore/Tasks/Update/GetTribe.cs b/TbsCore/Tasks/Update/GetTribe.cs index f1b9139e7..bd737c189 100644 --- a/TbsCore/Tasks/Update/GetTribe.cs +++ b/TbsCore/Tasks/Update/GetTribe.cs @@ -1,10 +1,9 @@ -using System.Collections.Generic; +using System; using System.Linq; using System.Threading.Tasks; -using TbsCore.Models.AccModels; using TbsCore.Helpers; +using TbsCore.Models.AccModels; using TbsCore.Parsers; -using System; namespace TbsCore.Tasks.LowLevel { diff --git a/TbsCore/Tasks/Update/HeroUpdateInfo.cs b/TbsCore/Tasks/Update/HeroUpdateInfo.cs index c5336d285..ace75fa5c 100644 --- a/TbsCore/Tasks/Update/HeroUpdateInfo.cs +++ b/TbsCore/Tasks/Update/HeroUpdateInfo.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; -using TbsCore.Models.AccModels; using TbsCore.Helpers; +using TbsCore.Models.AccModels; using static TbsCore.Helpers.Classificator; namespace TbsCore.Tasks.LowLevel diff --git a/TbsCore/Tasks/Update/ReadMessage.cs b/TbsCore/Tasks/Update/ReadMessage.cs index 45d82bd82..5e0bc9175 100644 --- a/TbsCore/Tasks/Update/ReadMessage.cs +++ b/TbsCore/Tasks/Update/ReadMessage.cs @@ -1,7 +1,7 @@ using System.Linq; using System.Threading.Tasks; -using TbsCore.Models.AccModels; using TbsCore.Helpers; +using TbsCore.Models.AccModels; namespace TbsCore.Tasks.LowLevel { @@ -15,7 +15,7 @@ public override async Task Execute(Account acc) var msg = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("messageStatusUnread")); if (msg != null) { - + var url = msg.ParentNode.GetAttributeValue("href", "").Replace("amp;", ""); switch (acc.AccInfo.ServerVersion) { diff --git a/TbsCore/Tasks/Update/UpdateDorf1.cs b/TbsCore/Tasks/Update/UpdateDorf1.cs index 16851388b..ebfe0e239 100644 --- a/TbsCore/Tasks/Update/UpdateDorf1.cs +++ b/TbsCore/Tasks/Update/UpdateDorf1.cs @@ -1,7 +1,7 @@ using System; using System.Threading.Tasks; -using TbsCore.Models.AccModels; using TbsCore.Helpers; +using TbsCore.Models.AccModels; namespace TbsCore.Tasks.LowLevel { diff --git a/TbsCore/Tasks/Update/UpdateDorf2.cs b/TbsCore/Tasks/Update/UpdateDorf2.cs index 06ca9eb9e..edd463832 100644 --- a/TbsCore/Tasks/Update/UpdateDorf2.cs +++ b/TbsCore/Tasks/Update/UpdateDorf2.cs @@ -1,6 +1,6 @@ using System.Threading.Tasks; -using TbsCore.Models.AccModels; using TbsCore.Helpers; +using TbsCore.Models.AccModels; namespace TbsCore.Tasks.LowLevel { diff --git a/TbsCore/Tasks/Update/UpdateTaskUseRes.cs b/TbsCore/Tasks/Update/UpdateTaskUseRes.cs index 505ed1565..54aa9236b 100644 --- a/TbsCore/Tasks/Update/UpdateTaskUseRes.cs +++ b/TbsCore/Tasks/Update/UpdateTaskUseRes.cs @@ -1,7 +1,6 @@ -using System.Linq; -using System.Threading.Tasks; -using TbsCore.Models.AccModels; +using System.Threading.Tasks; using TbsCore.Helpers; +using TbsCore.Models.AccModels; namespace TbsCore.Tasks.LowLevel { diff --git a/TbsCore/Tasks/Update/UpdateVillage.cs b/TbsCore/Tasks/Update/UpdateVillage.cs index 326d5d5ee..ce57c31f8 100644 --- a/TbsCore/Tasks/Update/UpdateVillage.cs +++ b/TbsCore/Tasks/Update/UpdateVillage.cs @@ -1,9 +1,8 @@ -using System.Linq; -using System.Threading.Tasks; +using System.Threading.Tasks; using TbsCore.Helpers; using TbsCore.Models.AccModels; -using TbsCore.TravianData; using TbsCore.Parsers; +using TbsCore.TravianData; namespace TbsCore.Tasks.LowLevel { diff --git a/TbsCore/TravianData/CombatSimulator.cs b/TbsCore/TravianData/CombatSimulator.cs index 46e4a2b9a..b6667249c 100644 --- a/TbsCore/TravianData/CombatSimulator.cs +++ b/TbsCore/TravianData/CombatSimulator.cs @@ -1,7 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using TbsCore.Models.CombatModels; +using TbsCore.Models.CombatModels; namespace TbsCore.TravianData { diff --git a/TbsCore/TravianData/Localizations.cs b/TbsCore/TravianData/Localizations.cs index 71fca5435..aa5c6f8b7 100644 --- a/TbsCore/TravianData/Localizations.cs +++ b/TbsCore/TravianData/Localizations.cs @@ -1,9 +1,5 @@ using System.Collections.Generic; -using System.Linq; -using System.Net; -using TbsCore.Models.AccModels; using TbsCore.Models.ResourceModels; -using static TbsCore.Helpers.Classificator; namespace TbsCore.TravianData { diff --git a/TbsCore/TravianData/TroopCost.cs b/TbsCore/TravianData/TroopCost.cs index 96615712d..f92669d00 100644 --- a/TbsCore/TravianData/TroopCost.cs +++ b/TbsCore/TravianData/TroopCost.cs @@ -3,7 +3,6 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; -using TbsCore.TravianData; namespace TbsCore.TravianData { diff --git a/TbsCore/TravianData/TroopsData.cs b/TbsCore/TravianData/TroopsData.cs index 84b4041a9..a0a6a1a18 100644 --- a/TbsCore/TravianData/TroopsData.cs +++ b/TbsCore/TravianData/TroopsData.cs @@ -1,12 +1,11 @@ using System; using System.Collections.Generic; -using System.Text; +using System.Linq; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.BuildingModels; -using TbsCore.Helpers; -using static TbsCore.Helpers.Classificator; using TbsCore.Models.VillageModels; -using System.Linq; +using static TbsCore.Helpers.Classificator; namespace TbsCore.TravianData { diff --git a/TbsCoreTest/BuildingTest.cs b/TbsCoreTest/BuildingTest.cs index 08396a326..7dbc42345 100644 --- a/TbsCoreTest/BuildingTest.cs +++ b/TbsCoreTest/BuildingTest.cs @@ -1,12 +1,8 @@ -using System; +using System.Linq; using TbsCore.Helpers; -using TbsCore.Models.ResourceModels; -using TbsCore.Models.Settings; using TbsCore.Models.VillageModels; using TbsCoreTest.Factories; -using TbsCore.Tasks.LowLevel; using Xunit; -using System.Linq; using static TbsCore.Helpers.Classificator; namespace TbsCoreTest diff --git a/TbsCoreTest/CombatSimulationTest.cs b/TbsCoreTest/CombatSimulationTest.cs index 93947dd27..38f73317a 100644 --- a/TbsCoreTest/CombatSimulationTest.cs +++ b/TbsCoreTest/CombatSimulationTest.cs @@ -1,10 +1,6 @@ using System; -using System.Collections.Generic; using TbsCore.Helpers; using TbsCore.Models.CombatModels; -using TbsCore.Models.ResourceModels; -using TbsCore.Models.Settings; -using TbsCore.Models.VillageModels; using TbsCore.TravianData; using TbsCoreTest.Factories; using Xunit; @@ -71,7 +67,7 @@ public void TestRealDeff() Assert.Equal((261000, 4598), GetBaseVals(attackers[1], deffenders[0])); Assert.Equal((261000, 131523), GetBaseVals(attackers[1], deffenders[1])); Assert.Equal((261000, 294580), GetBaseVals(attackers[1], deffenders[2])); - + Assert.Equal((640000, 4563), GetBaseVals(attackers[2], deffenders[0])); Assert.Equal((640000, 131875), GetBaseVals(attackers[2], deffenders[1])); Assert.Equal((640000, 294281), GetBaseVals(attackers[2], deffenders[2])); @@ -96,7 +92,7 @@ public void TestMorale() combat.Attacker.Population = 4; Assert.Equal(0.94, Rnd(combat.GetMoraleBonus())); - + combat.Attacker.Population = 2; combat.Deffender.Population = 2; Assert.Equal(1, combat.GetMoraleBonus()); diff --git a/TbsCoreTest/Factories/AccountFactory.cs b/TbsCoreTest/Factories/AccountFactory.cs index f28600b00..2307e441b 100644 --- a/TbsCoreTest/Factories/AccountFactory.cs +++ b/TbsCoreTest/Factories/AccountFactory.cs @@ -1,12 +1,7 @@ using System; using System.Collections.Generic; -using System.Text; -using TbsCore.Helpers; using TbsCore.Models.AccModels; -using TbsCore.Models.ResourceModels; -using TbsCore.Models.Settings; using TbsCore.Models.VillageModels; -using TbsCore.Tasks.LowLevel; namespace TbsCoreTest.Factories { diff --git a/TbsCoreTest/Factories/BuildingFactory.cs b/TbsCoreTest/Factories/BuildingFactory.cs index 404132922..75263ede7 100644 --- a/TbsCoreTest/Factories/BuildingFactory.cs +++ b/TbsCoreTest/Factories/BuildingFactory.cs @@ -1,6 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Text; +using System.Collections.Generic; using TbsCore.Models.BuildingModels; using TbsCore.Models.VillageModels; using static TbsCore.Helpers.Classificator; diff --git a/TbsCoreTest/Factories/CombatFactory.cs b/TbsCoreTest/Factories/CombatFactory.cs index 87ab61b70..56fcfbf58 100644 --- a/TbsCoreTest/Factories/CombatFactory.cs +++ b/TbsCoreTest/Factories/CombatFactory.cs @@ -74,12 +74,12 @@ public CombatDeffender CreateDeffender2() }; } - /// - /// Deff1: 2000 phalanx (20), 500 druids (15), 200 heudans, Hero: 50 strenght, 50 bonus, max phalanx, horse - /// Deff2: 1000 legionnaires (18), 1000 praetorian (19), 500 EC - /// Deffender: 450 Population, romans, wall level 15 - /// - public CombatDeffender CreateDeffender3() + /// + /// Deff1: 2000 phalanx (20), 500 druids (15), 200 heudans, Hero: 50 strenght, 50 bonus, max phalanx, horse + /// Deff2: 1000 legionnaires (18), 1000 praetorian (19), 500 EC + /// Deffender: 450 Population, romans, wall level 15 + /// + public CombatDeffender CreateDeffender3() { return new CombatDeffender { diff --git a/TbsCoreTest/Helpers/IoHelperCoreTest.cs b/TbsCoreTest/Helpers/IoHelperCoreTest.cs index 573690bb6..5a5ae20cb 100644 --- a/TbsCoreTest/Helpers/IoHelperCoreTest.cs +++ b/TbsCoreTest/Helpers/IoHelperCoreTest.cs @@ -1,7 +1,4 @@ using System; -using System.Collections.Generic; -using System.IO; -using System.Text; using TbsCore.Helpers; using Xunit; diff --git a/TbsCoreTest/ResSpendingTest.cs b/TbsCoreTest/ResSpendingTest.cs index c75881df8..90948eb45 100644 --- a/TbsCoreTest/ResSpendingTest.cs +++ b/TbsCoreTest/ResSpendingTest.cs @@ -1,10 +1,9 @@ -using System; using TbsCore.Helpers; using TbsCore.Models.ResourceModels; using TbsCore.Models.Settings; using TbsCore.Models.VillageModels; -using TbsCoreTest.Factories; using TbsCore.Tasks.LowLevel; +using TbsCoreTest.Factories; using Xunit; namespace TbsCoreTest diff --git a/TravBotSharp/ControlPanel.cs b/TravBotSharp/ControlPanel.cs index 141cdca5d..3453acade 100644 --- a/TravBotSharp/ControlPanel.cs +++ b/TravBotSharp/ControlPanel.cs @@ -3,21 +3,18 @@ using System.Drawing; using System.IO; using System.Linq; +using System.Reflection; using System.Threading; using System.Threading.Tasks; using System.Timers; -using System.Reflection; using System.Windows.Forms; using TbsCore.Database; +using TbsCore.Extensions; using TbsCore.Helpers; using TbsCore.Models.AccModels; - +using TbsCore.Models.Logging; using TravBotSharp.Forms; using TravBotSharp.Interfaces; -using TravBotSharp.Views; -using TbsCore.Models.Logging; -using TbsCore.Models.VillageModels; -using TbsCore.Extensions; namespace TravBotSharp { diff --git a/TravBotSharp/Forms/AddFarmNonGold.cs b/TravBotSharp/Forms/AddFarmNonGold.cs index 132974c0d..fb6a6c5df 100644 --- a/TravBotSharp/Forms/AddFarmNonGold.cs +++ b/TravBotSharp/Forms/AddFarmNonGold.cs @@ -1,14 +1,7 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Windows.Forms; -using TbsCore.Models.VillageModels; using TbsCore.Helpers; +using TbsCore.Models.VillageModels; namespace TravBotSharp.Forms { diff --git a/TravBotSharp/Forms/Closing.cs b/TravBotSharp/Forms/Closing.cs index 2040d49b1..78b736401 100644 --- a/TravBotSharp/Forms/Closing.cs +++ b/TravBotSharp/Forms/Closing.cs @@ -1,12 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; +using System.Windows.Forms; namespace TravBotSharp.Forms { diff --git a/TravBotSharp/Forms/Helper.cs b/TravBotSharp/Forms/Helper.cs index 8220eec97..3469ff773 100644 --- a/TravBotSharp/Forms/Helper.cs +++ b/TravBotSharp/Forms/Helper.cs @@ -1,11 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Windows.Forms; namespace TravBotSharp.Forms diff --git a/TravBotSharp/Forms/NewRelease.cs b/TravBotSharp/Forms/NewRelease.cs index 4279e24f6..fc0acaac3 100644 --- a/TravBotSharp/Forms/NewRelease.cs +++ b/TravBotSharp/Forms/NewRelease.cs @@ -1,7 +1,7 @@ using System; +using System.Drawing; using System.Windows.Forms; using TbsCore.Helpers; -using System.Drawing; namespace TravBotSharp.Forms { diff --git a/TravBotSharp/Forms/Splash.cs b/TravBotSharp/Forms/Splash.cs index 84638654b..e1916cd73 100644 --- a/TravBotSharp/Forms/Splash.cs +++ b/TravBotSharp/Forms/Splash.cs @@ -1,12 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; +using System.Threading; using System.Windows.Forms; namespace TravBotSharp.Forms diff --git a/TravBotSharp/Forms/TroopsSelector.cs b/TravBotSharp/Forms/TroopsSelector.cs index aebe10eb2..512b16738 100644 --- a/TravBotSharp/Forms/TroopsSelector.cs +++ b/TravBotSharp/Forms/TroopsSelector.cs @@ -1,11 +1,4 @@ using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; using System.Windows.Forms; namespace TravBotSharp.Forms diff --git a/TravBotSharp/UserControls/CoordinatesUc.cs b/TravBotSharp/UserControls/CoordinatesUc.cs index e1eacc52b..eb3455585 100644 --- a/TravBotSharp/UserControls/CoordinatesUc.cs +++ b/TravBotSharp/UserControls/CoordinatesUc.cs @@ -1,12 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; +using System.Windows.Forms; using TbsCore.Models.MapModels; namespace TravBotSharp.UserControls @@ -15,13 +7,13 @@ public partial class CoordinatesUc : UserControl { public Coordinates Coords { - get + get { var x = (int)X.Value; var y = (int)Y.Value; return new Coordinates(x, y); } - set + set { X.Value = value.x; Y.Value = value.y; diff --git a/TravBotSharp/UserControls/TroopSelector.cs b/TravBotSharp/UserControls/TroopSelector.cs index a2eb6c3ad..ce647924e 100644 --- a/TravBotSharp/UserControls/TroopSelector.cs +++ b/TravBotSharp/UserControls/TroopSelector.cs @@ -1,12 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; +using System.Windows.Forms; using TbsCore.Helpers; namespace TravBotSharp.UserControls diff --git a/TravBotSharp/UserControls/TroopsDisplayUc.cs b/TravBotSharp/UserControls/TroopsDisplayUc.cs index 19a6147b5..d2b8ddb71 100644 --- a/TravBotSharp/UserControls/TroopsDisplayUc.cs +++ b/TravBotSharp/UserControls/TroopsDisplayUc.cs @@ -1,11 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Drawing; using System.Windows.Forms; using TbsCore.Helpers; diff --git a/TravBotSharp/UserControls/TroopsSelectorUc.cs b/TravBotSharp/UserControls/TroopsSelectorUc.cs index c85f42505..d3e19aa5a 100644 --- a/TravBotSharp/UserControls/TroopsSelectorUc.cs +++ b/TravBotSharp/UserControls/TroopsSelectorUc.cs @@ -1,12 +1,4 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Linq; -using System.Text; -using System.Threading.Tasks; -using System.Windows.Forms; +using System.Windows.Forms; using TbsCore.Helpers; namespace TravBotSharp.Forms diff --git a/TravBotSharp/Views/DeffendingUc.cs b/TravBotSharp/Views/DeffendingUc.cs index f723c694b..37bc6c414 100644 --- a/TravBotSharp/Views/DeffendingUc.cs +++ b/TravBotSharp/Views/DeffendingUc.cs @@ -2,10 +2,8 @@ using System.Collections.Generic; using System.Linq; using System.Windows.Forms; -using TbsCore.Models.MapModels; using TbsCore.Models.SendTroopsModels; using TbsCore.Models.VillageModels; -using TbsCore.Helpers; using TbsCore.Tasks.LowLevel; using TravBotSharp.Interfaces; diff --git a/TravBotSharp/Views/DiscordUc.cs b/TravBotSharp/Views/DiscordUc.cs index b98600608..0696d8d65 100644 --- a/TravBotSharp/Views/DiscordUc.cs +++ b/TravBotSharp/Views/DiscordUc.cs @@ -1,7 +1,6 @@ using System.Windows.Forms; -using System.Drawing; -using TravBotSharp.Interfaces; using TbsCore.Helpers; +using TravBotSharp.Interfaces; namespace TravBotSharp.Views { diff --git a/TravBotSharp/Views/FarmingUc.cs b/TravBotSharp/Views/FarmingUc.cs index 94ba539ba..e6a21de20 100644 --- a/TravBotSharp/Views/FarmingUc.cs +++ b/TravBotSharp/Views/FarmingUc.cs @@ -2,14 +2,12 @@ using System.Data; using System.Linq; using System.Windows.Forms; -using TbsCore.Models.TroopsModels; using TbsCore.Helpers; - +using TbsCore.Models.MapModels; +using TbsCore.Models.TroopsModels; using TbsCore.Tasks.LowLevel; using TbsCore.Tasks.SecondLevel; using TravBotSharp.Interfaces; -using TravBotSharp.Forms; -using TbsCore.Models.MapModels; namespace TravBotSharp.Views { diff --git a/TravBotSharp/Views/HeroUc.cs b/TravBotSharp/Views/HeroUc.cs index 227f39686..b9fe5e8fb 100644 --- a/TravBotSharp/Views/HeroUc.cs +++ b/TravBotSharp/Views/HeroUc.cs @@ -1,11 +1,11 @@ using System; using System.Collections.Generic; using System.Windows.Forms; -using TbsCore.Models.AccModels; using TbsCore.Helpers; +using TbsCore.Models.AccModels; using TbsCore.Tasks.LowLevel; -using TravBotSharp.Interfaces; using TravBotSharp.Forms.Hero; +using TravBotSharp.Interfaces; namespace TravBotSharp.Views { diff --git a/TravBotSharp/Views/NewVillagesUc.cs b/TravBotSharp/Views/NewVillagesUc.cs index 3d2c30fdb..2f6a534fd 100644 --- a/TravBotSharp/Views/NewVillagesUc.cs +++ b/TravBotSharp/Views/NewVillagesUc.cs @@ -1,9 +1,8 @@ using System; using System.Windows.Forms; +using TbsCore.Helpers; using TbsCore.Models.MapModels; using TbsCore.Models.VillageModels; -using TbsCore.Helpers; -using TbsCore.Tasks.LowLevel; using TravBotSharp.Interfaces; namespace TravBotSharp.Views diff --git a/TravBotSharp/Views/OverviewUc.cs b/TravBotSharp/Views/OverviewUc.cs index 0a9e4fae7..c7992a3b7 100644 --- a/TravBotSharp/Views/OverviewUc.cs +++ b/TravBotSharp/Views/OverviewUc.cs @@ -1,9 +1,9 @@ using System; using System.Collections.Generic; using System.Linq; +using TbsCore.Helpers; using TbsCore.Models.Settings; using TbsCore.Models.VillageModels; -using TbsCore.Helpers; using TbsCore.Tasks.LowLevel; using TravBotSharp.Interfaces; using XPTable.Editors; diff --git a/TravBotSharp/Views/VillageViews/AttackUc.cs b/TravBotSharp/Views/VillageViews/AttackUc.cs index fe2072155..bf842b7a1 100644 --- a/TravBotSharp/Views/VillageViews/AttackUc.cs +++ b/TravBotSharp/Views/VillageViews/AttackUc.cs @@ -1,16 +1,14 @@ using System; using System.Collections.Generic; -using System.Data; using System.Linq; using System.Windows.Forms; -using TbsCore.Models.MapModels; +using TbsCore.Helpers; using TbsCore.Models.SendTroopsModels; using TbsCore.Models.VillageModels; -using TbsCore.TravianData; -using TbsCore.Helpers; using TbsCore.Tasks.LowLevel; -using TravBotSharp.Interfaces; using TbsCore.Tasks.SecondLevel; +using TbsCore.TravianData; +using TravBotSharp.Interfaces; namespace TravBotSharp.Views { diff --git a/TravBotSharp/Views/VillageViews/BuildUc.cs b/TravBotSharp/Views/VillageViews/BuildUc.cs index c898a845e..15770ce17 100644 --- a/TravBotSharp/Views/VillageViews/BuildUc.cs +++ b/TravBotSharp/Views/VillageViews/BuildUc.cs @@ -3,10 +3,10 @@ using System.Drawing; using System.Linq; using System.Windows.Forms; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.BuildingModels; using TbsCore.Models.VillageModels; -using TbsCore.Helpers; using TbsCore.Tasks; using TbsCore.Tasks.LowLevel; using TravBotSharp.Interfaces; diff --git a/TravBotSharp/Views/VillageViews/FarmingNonGoldUc.cs b/TravBotSharp/Views/VillageViews/FarmingNonGoldUc.cs index 9ea6b4eaf..847be546a 100644 --- a/TravBotSharp/Views/VillageViews/FarmingNonGoldUc.cs +++ b/TravBotSharp/Views/VillageViews/FarmingNonGoldUc.cs @@ -1,20 +1,16 @@ using System; -using System.Windows.Forms; +using System.Collections.Generic; using System.Drawing; - -using TravBotSharp.Interfaces; +using System.Linq; +using System.Windows.Forms; using TbsCore.Helpers; -using TbsCore.Tasks; -using TbsCore.Tasks.LowLevel; - -using TbsCore.Models.VillageModels; -using TbsCore.Models.SendTroopsModels; using TbsCore.Models.MapModels; -using TbsCore.Models.AccModels; -using TravBotSharp.Forms; -using System.Collections.Generic; -using System.Linq; +using TbsCore.Models.SendTroopsModels; +using TbsCore.Models.VillageModels; +using TbsCore.Tasks.LowLevel; using TbsCore.Tasks.SecondLevel; +using TravBotSharp.Forms; +using TravBotSharp.Interfaces; namespace TravBotSharp.Views { diff --git a/TravBotSharp/Views/VillageViews/InfoUc.cs b/TravBotSharp/Views/VillageViews/InfoUc.cs index 80ff313e7..f8306b94a 100644 --- a/TravBotSharp/Views/VillageViews/InfoUc.cs +++ b/TravBotSharp/Views/VillageViews/InfoUc.cs @@ -1,9 +1,6 @@ using System; -using System.Collections.Generic; using TbsCore.Extensions; -using TbsCore.Helpers; using TravBotSharp.Interfaces; -using TbsCore.Tasks.LowLevel; namespace TravBotSharp.Views { diff --git a/TravBotSharp/Views/VillageViews/MarketUc.cs b/TravBotSharp/Views/VillageViews/MarketUc.cs index c7ec56ed2..f4ef5bdfc 100644 --- a/TravBotSharp/Views/VillageViews/MarketUc.cs +++ b/TravBotSharp/Views/VillageViews/MarketUc.cs @@ -1,7 +1,6 @@ using System; using System.Windows.Forms; using TbsCore.Tasks; -using TbsCore.Tasks.LowLevel; using TravBotSharp.Interfaces; namespace TravBotSharp.Views diff --git a/TravBotSharp/Views/VillageViews/TroopsUc.cs b/TravBotSharp/Views/VillageViews/TroopsUc.cs index b45bc4449..7f8a23ac5 100644 --- a/TravBotSharp/Views/VillageViews/TroopsUc.cs +++ b/TravBotSharp/Views/VillageViews/TroopsUc.cs @@ -60,7 +60,8 @@ private void button1_Click(object sender, EventArgs e) // Add to improve private void button2_Click(object sender, EventArgs e) // scouts { - GetSelectedAcc().Tasks.Add(new SendReinforcementScouts { + GetSelectedAcc().Tasks.Add(new SendReinforcementScouts + { Scouts = (int)scouts.Value, Vill = GetSelectedVillage() }, true); diff --git a/TravBotSharp/Views/VillagesUc.cs b/TravBotSharp/Views/VillagesUc.cs index 7c484d400..2296218a6 100644 --- a/TravBotSharp/Views/VillagesUc.cs +++ b/TravBotSharp/Views/VillagesUc.cs @@ -3,9 +3,9 @@ using System.Drawing; using System.Linq; using System.Windows.Forms; +using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; -using TbsCore.Helpers; using TbsCore.Tasks.LowLevel; using TravBotSharp.Interfaces; From fc604efbe2adba412fa103d11cb002967dfa8a06 Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 15:04:23 +0700 Subject: [PATCH 06/16] Tasks.Sim namespace --- TbsCore/Core/PostLoadHelper.cs | 1 + TbsCore/Core/TaskTimer.cs | 11 ----------- TbsCore/Helpers/AccountHelper.cs | 1 + TbsCore/Helpers/BuildingHelper.cs | 1 + TbsCore/Helpers/ResSpendingHelper.cs | 1 + TbsCore/Helpers/UpgradeBuildingHelper.cs | 1 + TbsCore/Tasks/Sim/Celebration.cs | 10 +++++----- TbsCore/Tasks/Sim/ClaimBeginnerTask.cs | 2 +- TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs | 3 ++- TbsCore/Tasks/Sim/ClaimDailyTask.cs | 3 +-- TbsCore/Tasks/Sim/DemolishBuilding.cs | 2 +- TbsCore/Tasks/Sim/ExtendProtection.cs | 2 +- TbsCore/Tasks/Sim/FindVillageToSettle.cs | 2 +- TbsCore/Tasks/Sim/InstaUpgrade.cs | 2 +- TbsCore/Tasks/Sim/NPC.cs | 6 +++--- TbsCore/Tasks/Sim/SendSettlers.cs | 2 +- TbsCore/Tasks/Sim/TrainSettlers.cs | 6 +++--- TbsCore/Tasks/Sim/UpgradeBuilding.cs | 3 +-- TbsCoreTest/ResSpendingTest.cs | 1 + TravBotSharp/Views/NewVillagesUc.cs | 1 + TravBotSharp/Views/VillageViews/BuildUc.cs | 1 + TravBotSharp/Views/VillageViews/InfoUc.cs | 1 + TravBotSharp/Views/VillageViews/MarketUc.cs | 16 +++++++++++----- 23 files changed, 41 insertions(+), 38 deletions(-) diff --git a/TbsCore/Core/PostLoadHelper.cs b/TbsCore/Core/PostLoadHelper.cs index 42cd310fd..8e7adf030 100644 --- a/TbsCore/Core/PostLoadHelper.cs +++ b/TbsCore/Core/PostLoadHelper.cs @@ -7,6 +7,7 @@ using TbsCore.Models.VillageModels; using TbsCore.Parsers; using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Sim; using static TbsCore.Tasks.BotTask; namespace TbsCore.Helpers diff --git a/TbsCore/Core/TaskTimer.cs b/TbsCore/Core/TaskTimer.cs index cdddc04c5..dfb454ec1 100644 --- a/TbsCore/Core/TaskTimer.cs +++ b/TbsCore/Core/TaskTimer.cs @@ -100,17 +100,6 @@ private async void NewTick() } task.Stage = TaskStage.Executing; - - //If correct village is selected, otherwise change village - if (task.Vill != null && task.GetType() != typeof(UpgradeBuilding)) - { - var active = _acc.Villages.FirstOrDefault(x => x.Active); - if (active != null && active != task.Vill) - { - await VillageHelper.SwitchVillage(_acc, task.Vill.Id); - } - } - await TaskExecutor.Execute(_acc, task); IsTaskExcuting = false; diff --git a/TbsCore/Helpers/AccountHelper.cs b/TbsCore/Helpers/AccountHelper.cs index 74e7fdc94..c19fa9c01 100644 --- a/TbsCore/Helpers/AccountHelper.cs +++ b/TbsCore/Helpers/AccountHelper.cs @@ -6,6 +6,7 @@ using TbsCore.Tasks.Browser; using TbsCore.Tasks.LowLevel; using TbsCore.Tasks.SecondLevel; +using TbsCore.Tasks.Sim; namespace TbsCore.Helpers { diff --git a/TbsCore/Helpers/BuildingHelper.cs b/TbsCore/Helpers/BuildingHelper.cs index b5ec4b52d..925d46517 100644 --- a/TbsCore/Helpers/BuildingHelper.cs +++ b/TbsCore/Helpers/BuildingHelper.cs @@ -4,6 +4,7 @@ using TbsCore.Models.AccModels; using TbsCore.Models.BuildingModels; using TbsCore.Models.VillageModels; +using TbsCore.Tasks.Sim; using TbsCore.TravianData; using static TbsCore.Helpers.Classificator; diff --git a/TbsCore/Helpers/ResSpendingHelper.cs b/TbsCore/Helpers/ResSpendingHelper.cs index 0897a0a33..618cc9f5a 100644 --- a/TbsCore/Helpers/ResSpendingHelper.cs +++ b/TbsCore/Helpers/ResSpendingHelper.cs @@ -7,6 +7,7 @@ using TbsCore.Models.VillageModels; using TbsCore.Tasks; using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Sim; namespace TbsCore.Helpers { diff --git a/TbsCore/Helpers/UpgradeBuildingHelper.cs b/TbsCore/Helpers/UpgradeBuildingHelper.cs index bf220deef..5087d5a30 100644 --- a/TbsCore/Helpers/UpgradeBuildingHelper.cs +++ b/TbsCore/Helpers/UpgradeBuildingHelper.cs @@ -5,6 +5,7 @@ using TbsCore.Models.BuildingModels; using TbsCore.Models.VillageModels; using TbsCore.Tasks; +using TbsCore.Tasks.Sim; using TbsCore.TravianData; using static TbsCore.Helpers.Classificator; diff --git a/TbsCore/Tasks/Sim/Celebration.cs b/TbsCore/Tasks/Sim/Celebration.cs index 9341b497d..112476d5b 100644 --- a/TbsCore/Tasks/Sim/Celebration.cs +++ b/TbsCore/Tasks/Sim/Celebration.cs @@ -1,16 +1,16 @@ -using System; +using HtmlAgilityPack; +using OpenQA.Selenium; +using System; using System.Linq; using System.Threading.Tasks; using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; -using TbsCore.TravianData; using TbsCore.Parsers; +using TbsCore.TravianData; using static TbsCore.Helpers.Classificator; -using HtmlAgilityPack; -using OpenQA.Selenium; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Sim { public class Celebration : BotTask { diff --git a/TbsCore/Tasks/Sim/ClaimBeginnerTask.cs b/TbsCore/Tasks/Sim/ClaimBeginnerTask.cs index d6aa6dd8a..4d8fc82d0 100644 --- a/TbsCore/Tasks/Sim/ClaimBeginnerTask.cs +++ b/TbsCore/Tasks/Sim/ClaimBeginnerTask.cs @@ -4,7 +4,7 @@ using TbsCore.Models.AccModels; using TbsCore.Models.SideBarModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Sim { public class ClaimBeginnerTask : BotTask { diff --git a/TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs b/TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs index a161e16b5..6bc1abdf6 100644 --- a/TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs +++ b/TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs @@ -3,8 +3,9 @@ using System.Threading.Tasks; using TbsCore.Helpers; using TbsCore.Models.AccModels; +using TbsCore.Tasks.LowLevel; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Sim { public class ClaimBeginnerTask2021 : BotTask { diff --git a/TbsCore/Tasks/Sim/ClaimDailyTask.cs b/TbsCore/Tasks/Sim/ClaimDailyTask.cs index efa63b726..4b4d241e8 100644 --- a/TbsCore/Tasks/Sim/ClaimDailyTask.cs +++ b/TbsCore/Tasks/Sim/ClaimDailyTask.cs @@ -2,13 +2,12 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Sim { public class ClaimDailyTask : BotTask { public override async Task Execute(Account acc) { - switch (acc.AccInfo.ServerVersion) { case Classificator.ServerVersionEnum.TTwars: diff --git a/TbsCore/Tasks/Sim/DemolishBuilding.cs b/TbsCore/Tasks/Sim/DemolishBuilding.cs index 6aed16650..448453cf7 100644 --- a/TbsCore/Tasks/Sim/DemolishBuilding.cs +++ b/TbsCore/Tasks/Sim/DemolishBuilding.cs @@ -7,7 +7,7 @@ using TbsCore.Models.VillageModels; using TbsCore.Parsers; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Sim { public class DemolishBuilding : BotTask { diff --git a/TbsCore/Tasks/Sim/ExtendProtection.cs b/TbsCore/Tasks/Sim/ExtendProtection.cs index 13e870a67..5d3e9a181 100644 --- a/TbsCore/Tasks/Sim/ExtendProtection.cs +++ b/TbsCore/Tasks/Sim/ExtendProtection.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Sim { /// /// Extend beginners protection diff --git a/TbsCore/Tasks/Sim/FindVillageToSettle.cs b/TbsCore/Tasks/Sim/FindVillageToSettle.cs index 54d3b02f7..cc346ce57 100644 --- a/TbsCore/Tasks/Sim/FindVillageToSettle.cs +++ b/TbsCore/Tasks/Sim/FindVillageToSettle.cs @@ -7,7 +7,7 @@ using TbsCore.Models.VillageModels; using TbsCore.Parsers; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Sim { public class FindVillageToSettle : BotTask { diff --git a/TbsCore/Tasks/Sim/InstaUpgrade.cs b/TbsCore/Tasks/Sim/InstaUpgrade.cs index 06d1071e7..28911c623 100644 --- a/TbsCore/Tasks/Sim/InstaUpgrade.cs +++ b/TbsCore/Tasks/Sim/InstaUpgrade.cs @@ -4,7 +4,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Sim { /// /// Instantly upgrade currently building diff --git a/TbsCore/Tasks/Sim/NPC.cs b/TbsCore/Tasks/Sim/NPC.cs index 4372b89a1..19a207885 100644 --- a/TbsCore/Tasks/Sim/NPC.cs +++ b/TbsCore/Tasks/Sim/NPC.cs @@ -1,12 +1,12 @@ -using System; +using HtmlAgilityPack; +using System; using System.Linq; using System.Threading.Tasks; using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Parsers; -using HtmlAgilityPack; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Sim { public class NPC : BotTask { diff --git a/TbsCore/Tasks/Sim/SendSettlers.cs b/TbsCore/Tasks/Sim/SendSettlers.cs index 8cd90f669..9b7379086 100644 --- a/TbsCore/Tasks/Sim/SendSettlers.cs +++ b/TbsCore/Tasks/Sim/SendSettlers.cs @@ -5,7 +5,7 @@ using TbsCore.Models.AccModels; using TbsCore.Parsers; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Sim { public class SendSettlers : BotTask { diff --git a/TbsCore/Tasks/Sim/TrainSettlers.cs b/TbsCore/Tasks/Sim/TrainSettlers.cs index a420ee00f..2aafecfa0 100644 --- a/TbsCore/Tasks/Sim/TrainSettlers.cs +++ b/TbsCore/Tasks/Sim/TrainSettlers.cs @@ -1,13 +1,13 @@ using System; using System.Linq; using System.Threading.Tasks; -using TbsCore.Models.AccModels; -using TbsCore.TravianData; using TbsCore.Helpers; +using TbsCore.Models.AccModels; using TbsCore.Parsers; +using TbsCore.TravianData; using static TbsCore.Helpers.Classificator; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Sim { public class TrainSettlers : BotTask { diff --git a/TbsCore/Tasks/Sim/UpgradeBuilding.cs b/TbsCore/Tasks/Sim/UpgradeBuilding.cs index cf2d88000..b31938706 100644 --- a/TbsCore/Tasks/Sim/UpgradeBuilding.cs +++ b/TbsCore/Tasks/Sim/UpgradeBuilding.cs @@ -7,13 +7,12 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.BuildingModels; -using TbsCore.Models.VillageModels; using TbsCore.Parsers; using TbsCore.TravianData; using static TbsCore.Helpers.Classificator; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Sim { public class UpgradeBuilding : BotTask { diff --git a/TbsCoreTest/ResSpendingTest.cs b/TbsCoreTest/ResSpendingTest.cs index 90948eb45..f824d51fd 100644 --- a/TbsCoreTest/ResSpendingTest.cs +++ b/TbsCoreTest/ResSpendingTest.cs @@ -3,6 +3,7 @@ using TbsCore.Models.Settings; using TbsCore.Models.VillageModels; using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Sim; using TbsCoreTest.Factories; using Xunit; diff --git a/TravBotSharp/Views/NewVillagesUc.cs b/TravBotSharp/Views/NewVillagesUc.cs index 2f6a534fd..679e961ae 100644 --- a/TravBotSharp/Views/NewVillagesUc.cs +++ b/TravBotSharp/Views/NewVillagesUc.cs @@ -3,6 +3,7 @@ using TbsCore.Helpers; using TbsCore.Models.MapModels; using TbsCore.Models.VillageModels; +using TbsCore.Tasks.Sim; using TravBotSharp.Interfaces; namespace TravBotSharp.Views diff --git a/TravBotSharp/Views/VillageViews/BuildUc.cs b/TravBotSharp/Views/VillageViews/BuildUc.cs index 15770ce17..dc7bab61b 100644 --- a/TravBotSharp/Views/VillageViews/BuildUc.cs +++ b/TravBotSharp/Views/VillageViews/BuildUc.cs @@ -9,6 +9,7 @@ using TbsCore.Models.VillageModels; using TbsCore.Tasks; using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Sim; using TravBotSharp.Interfaces; using static TbsCore.Helpers.Classificator; diff --git a/TravBotSharp/Views/VillageViews/InfoUc.cs b/TravBotSharp/Views/VillageViews/InfoUc.cs index f8306b94a..af28368c6 100644 --- a/TravBotSharp/Views/VillageViews/InfoUc.cs +++ b/TravBotSharp/Views/VillageViews/InfoUc.cs @@ -1,5 +1,6 @@ using System; using TbsCore.Extensions; +using TbsCore.Tasks.Sim; using TravBotSharp.Interfaces; namespace TravBotSharp.Views diff --git a/TravBotSharp/Views/VillageViews/MarketUc.cs b/TravBotSharp/Views/VillageViews/MarketUc.cs index f4ef5bdfc..b52ac4134 100644 --- a/TravBotSharp/Views/VillageViews/MarketUc.cs +++ b/TravBotSharp/Views/VillageViews/MarketUc.cs @@ -1,6 +1,7 @@ using System; using System.Windows.Forms; using TbsCore.Tasks; +using TbsCore.Tasks.Sim; using TravBotSharp.Interfaces; namespace TravBotSharp.Views @@ -63,6 +64,7 @@ private void npcEnabled_CheckedChanged(object sender, EventArgs e) => GetSelectedVillage().Market.Npc.Enabled = npcEnabled.Checked; #region SendMainVill Callbacks + private void woodSend_ValueChanged(object sender, EventArgs e) => GetSelectedVillage().Market.Settings.Configuration.SendResLimit.Wood = (long)woodSend.Value; @@ -74,9 +76,11 @@ private void ironSend_ValueChanged(object sender, EventArgs e) => private void cropSend_ValueChanged(object sender, EventArgs e) => GetSelectedVillage().Market.Settings.Configuration.SendResLimit.Crop = (long)cropSend.Value; - #endregion + + #endregion SendMainVill Callbacks #region TargetLimit Callbacks + private void TargetLimitWood_ValueChanged(object sender, EventArgs e) => GetSelectedVillage().Market.Settings.Configuration.TargetLimit.Wood = (long)TargetLimitWood.Value; @@ -88,9 +92,11 @@ private void TargetLimitIron_ValueChanged(object sender, EventArgs e) => private void TargetLimitCrop_ValueChanged(object sender, EventArgs e) => GetSelectedVillage().Market.Settings.Configuration.TargetLimit.Crop = (long)TargetLimitCrop.Value; - #endregion + + #endregion TargetLimit Callbacks #region FillLimit Callbacks + private void FillLimitWood_ValueChanged(object sender, EventArgs e) => GetSelectedVillage().Market.Settings.Configuration.FillLimit.Wood = (long)FillLimitWood.Value; @@ -102,7 +108,8 @@ private void FillLimitIron_ValueChanged(object sender, EventArgs e) => private void FillLimitCrop_ValueChanged(object sender, EventArgs e) => GetSelectedVillage().Market.Settings.Configuration.FillLimit.Crop = (long)FillLimitCrop.Value; - #endregion + + #endregion FillLimit Callbacks private void npc_Click(object sender, EventArgs e) { @@ -116,8 +123,7 @@ private void npc_Click(object sender, EventArgs e) { Vill = vill, Priority = BotTask.TaskPriority.High - }, true, vill); } } -} +} \ No newline at end of file From ca2f7af4c134c5dc9a708fed144fec43f9d67c35 Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 15:31:03 +0700 Subject: [PATCH 07/16] Tasks.Update namespace --- TbsCore/Core/PostLoadHelper.cs | 1 + TbsCore/Core/TaskExecutor.cs | 1 + TbsCore/Helpers/AccountHelper.cs | 1 + TbsCore/Helpers/UpdateAccountObject.cs | 3 ++- TbsCore/Helpers/VillageHelper.cs | 2 +- TbsCore/Tasks/Farm/ScoutPlayer.cs | 1 + TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs | 1 + TbsCore/Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs | 1 + TbsCore/Tasks/Farm/TrainTroops.cs | 1 + TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs | 1 + TbsCore/Tasks/Update/CheckAttacks.cs | 3 ++- TbsCore/Tasks/Update/CheckProfile.cs | 4 +++- TbsCore/Tasks/Update/GetServerInfo.cs | 4 ++-- TbsCore/Tasks/Update/GetTribe.cs | 2 +- TbsCore/Tasks/Update/HeroUpdateInfo.cs | 3 ++- TbsCore/Tasks/Update/ReadMessage.cs | 6 +++--- TbsCore/Tasks/Update/UpdateDorf1.cs | 2 +- TbsCore/Tasks/Update/UpdateDorf2.cs | 2 +- TbsCore/Tasks/Update/UpdateTaskUseRes.cs | 2 +- TbsCore/Tasks/Update/UpdateTroops.cs | 2 +- TbsCore/Tasks/Update/UpdateVillage.cs | 2 +- TravBotSharp/Views/HeroUc.cs | 1 + TravBotSharp/Views/VillageViews/BuildUc.cs | 1 + TravBotSharp/Views/VillagesUc.cs | 1 + 24 files changed, 32 insertions(+), 16 deletions(-) diff --git a/TbsCore/Core/PostLoadHelper.cs b/TbsCore/Core/PostLoadHelper.cs index 8e7adf030..666704f37 100644 --- a/TbsCore/Core/PostLoadHelper.cs +++ b/TbsCore/Core/PostLoadHelper.cs @@ -8,6 +8,7 @@ using TbsCore.Parsers; using TbsCore.Tasks.LowLevel; using TbsCore.Tasks.Sim; +using TbsCore.Tasks.Update; using static TbsCore.Tasks.BotTask; namespace TbsCore.Helpers diff --git a/TbsCore/Core/TaskExecutor.cs b/TbsCore/Core/TaskExecutor.cs index a3cce7433..aa9ff9d65 100644 --- a/TbsCore/Core/TaskExecutor.cs +++ b/TbsCore/Core/TaskExecutor.cs @@ -9,6 +9,7 @@ using TbsCore.Tasks; using TbsCore.Tasks.Browser; using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Update; using static TbsCore.Tasks.BotTask; namespace TbsCore.Helpers diff --git a/TbsCore/Helpers/AccountHelper.cs b/TbsCore/Helpers/AccountHelper.cs index c19fa9c01..615ae6a24 100644 --- a/TbsCore/Helpers/AccountHelper.cs +++ b/TbsCore/Helpers/AccountHelper.cs @@ -7,6 +7,7 @@ using TbsCore.Tasks.LowLevel; using TbsCore.Tasks.SecondLevel; using TbsCore.Tasks.Sim; +using TbsCore.Tasks.Update; namespace TbsCore.Helpers { diff --git a/TbsCore/Helpers/UpdateAccountObject.cs b/TbsCore/Helpers/UpdateAccountObject.cs index cb970b5c2..339f09175 100644 --- a/TbsCore/Helpers/UpdateAccountObject.cs +++ b/TbsCore/Helpers/UpdateAccountObject.cs @@ -6,6 +6,7 @@ using TbsCore.Models.VillageModels; using TbsCore.Parsers; using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Update; namespace TbsCore.Helpers { @@ -32,7 +33,7 @@ public static bool UpdateVillages(HtmlAgilityPack.HtmlDocument htmlDoc, Account if (oldVill.UnderAttack != foundVill.UnderAttack && foundVill.UnderAttack && - oldVill.Deffing.AlertType != Models.VillageModels.AlertTypeEnum.Disabled) + oldVill.Deffing.AlertType != AlertTypeEnum.Disabled) { acc.Tasks.Add(new CheckAttacks() { Vill = oldVill, Priority = Tasks.BotTask.TaskPriority.High }, true, oldVill); } diff --git a/TbsCore/Helpers/VillageHelper.cs b/TbsCore/Helpers/VillageHelper.cs index 9eb264fa3..7e7ef94b9 100644 --- a/TbsCore/Helpers/VillageHelper.cs +++ b/TbsCore/Helpers/VillageHelper.cs @@ -4,7 +4,7 @@ using System.Threading.Tasks; using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Update; using static TbsCore.Helpers.Classificator; namespace TbsCore.Helpers diff --git a/TbsCore/Tasks/Farm/ScoutPlayer.cs b/TbsCore/Tasks/Farm/ScoutPlayer.cs index 6e28d8a89..785acbe3b 100644 --- a/TbsCore/Tasks/Farm/ScoutPlayer.cs +++ b/TbsCore/Tasks/Farm/ScoutPlayer.cs @@ -3,6 +3,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Update; using TbsCore.TravianData; namespace TbsCore.Tasks.SecondLevel diff --git a/TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs b/TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs index cec9242ab..f25e40587 100644 --- a/TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs +++ b/TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs @@ -4,6 +4,7 @@ using TbsCore.Models.AccModels; using TbsCore.Models.TroopsModels; using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Update; namespace TbsCore.Tasks.SecondLevel { diff --git a/TbsCore/Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs b/TbsCore/Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs index 29ca10388..bc77ea9db 100644 --- a/TbsCore/Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs +++ b/TbsCore/Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs @@ -2,6 +2,7 @@ using System.Threading.Tasks; using TbsCore.Models.AccModels; using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Update; namespace TbsCore.Tasks.SecondLevel { diff --git a/TbsCore/Tasks/Farm/TrainTroops.cs b/TbsCore/Tasks/Farm/TrainTroops.cs index d4122bff7..6310a802e 100644 --- a/TbsCore/Tasks/Farm/TrainTroops.cs +++ b/TbsCore/Tasks/Farm/TrainTroops.cs @@ -6,6 +6,7 @@ using TbsCore.Models.AccModels; using TbsCore.Models.ResourceModels; using TbsCore.Parsers; +using TbsCore.Tasks.Update; using TbsCore.TravianData; using static TbsCore.Helpers.Classificator; diff --git a/TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs b/TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs index 6bc1abdf6..0d4a9a914 100644 --- a/TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs +++ b/TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs @@ -4,6 +4,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Update; namespace TbsCore.Tasks.Sim { diff --git a/TbsCore/Tasks/Update/CheckAttacks.cs b/TbsCore/Tasks/Update/CheckAttacks.cs index cefd74c59..3aee3623f 100644 --- a/TbsCore/Tasks/Update/CheckAttacks.cs +++ b/TbsCore/Tasks/Update/CheckAttacks.cs @@ -8,8 +8,9 @@ using TbsCore.Models.SendTroopsModels; using TbsCore.Models.VillageModels; using TbsCore.Parsers; +using TbsCore.Tasks.LowLevel; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Update { public class CheckAttacks : BotTask { diff --git a/TbsCore/Tasks/Update/CheckProfile.cs b/TbsCore/Tasks/Update/CheckProfile.cs index 019311e61..60a304f62 100644 --- a/TbsCore/Tasks/Update/CheckProfile.cs +++ b/TbsCore/Tasks/Update/CheckProfile.cs @@ -6,11 +6,12 @@ using TbsCore.Models.AttackModels; using TbsCore.Parsers; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Update { public class CheckProfile : BotTask { public int UserId { get; set; } + public TravianUser Profile { get; } = new TravianUser() { Villages = new List() @@ -26,6 +27,7 @@ public override async Task Execute(Account acc) case Classificator.ServerVersionEnum.T4_5: await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/profile/{UserId}"); break; + case Classificator.ServerVersionEnum.TTwars: await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/spieler.php?uid={UserId}"); break; diff --git a/TbsCore/Tasks/Update/GetServerInfo.cs b/TbsCore/Tasks/Update/GetServerInfo.cs index 2e2176700..d7fa46653 100644 --- a/TbsCore/Tasks/Update/GetServerInfo.cs +++ b/TbsCore/Tasks/Update/GetServerInfo.cs @@ -2,7 +2,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Update { public class GetServerInfo : BotTask { @@ -17,7 +17,7 @@ public override async Task Execute(Account acc) // Get server speed var speed = DriverHelper.GetJsObj(acc, "Travian.Game.speed"); acc.AccInfo.ServerSpeed = (int)speed; - acc.Logger.Information($"Server speed is {acc.AccInfo.ServerSpeed}"); + acc.Logger.Information($"Server speed is {acc.AccInfo.ServerSpeed}x"); return TaskRes.Executed; } diff --git a/TbsCore/Tasks/Update/GetTribe.cs b/TbsCore/Tasks/Update/GetTribe.cs index bd737c189..c91b5c2bf 100644 --- a/TbsCore/Tasks/Update/GetTribe.cs +++ b/TbsCore/Tasks/Update/GetTribe.cs @@ -5,7 +5,7 @@ using TbsCore.Models.AccModels; using TbsCore.Parsers; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Update { public class GetTribe : BotTask { diff --git a/TbsCore/Tasks/Update/HeroUpdateInfo.cs b/TbsCore/Tasks/Update/HeroUpdateInfo.cs index ace75fa5c..b76566b8b 100644 --- a/TbsCore/Tasks/Update/HeroUpdateInfo.cs +++ b/TbsCore/Tasks/Update/HeroUpdateInfo.cs @@ -2,9 +2,10 @@ using System.Threading.Tasks; using TbsCore.Helpers; using TbsCore.Models.AccModels; +using TbsCore.Tasks.LowLevel; using static TbsCore.Helpers.Classificator; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Update { public class HeroUpdateInfo : BotTask { diff --git a/TbsCore/Tasks/Update/ReadMessage.cs b/TbsCore/Tasks/Update/ReadMessage.cs index 5e0bc9175..4a5fe945a 100644 --- a/TbsCore/Tasks/Update/ReadMessage.cs +++ b/TbsCore/Tasks/Update/ReadMessage.cs @@ -3,7 +3,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Update { public class ReadMessage : BotTask { @@ -15,13 +15,13 @@ public override async Task Execute(Account acc) var msg = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("messageStatusUnread")); if (msg != null) { - var url = msg.ParentNode.GetAttributeValue("href", "").Replace("amp;", ""); switch (acc.AccInfo.ServerVersion) { case Classificator.ServerVersionEnum.T4_5: await acc.Wb.Navigate(acc.AccInfo.ServerUrl + url); break; + case Classificator.ServerVersionEnum.TTwars: await acc.Wb.Navigate(acc.AccInfo.ServerUrl + "/" + url); break; @@ -32,4 +32,4 @@ public override async Task Execute(Account acc) } } } -} +} \ No newline at end of file diff --git a/TbsCore/Tasks/Update/UpdateDorf1.cs b/TbsCore/Tasks/Update/UpdateDorf1.cs index ebfe0e239..53cd922a5 100644 --- a/TbsCore/Tasks/Update/UpdateDorf1.cs +++ b/TbsCore/Tasks/Update/UpdateDorf1.cs @@ -3,7 +3,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Update { public class UpdateDorf1 : BotTask { diff --git a/TbsCore/Tasks/Update/UpdateDorf2.cs b/TbsCore/Tasks/Update/UpdateDorf2.cs index edd463832..0c1ab46a0 100644 --- a/TbsCore/Tasks/Update/UpdateDorf2.cs +++ b/TbsCore/Tasks/Update/UpdateDorf2.cs @@ -2,7 +2,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Update { public class UpdateDorf2 : BotTask { diff --git a/TbsCore/Tasks/Update/UpdateTaskUseRes.cs b/TbsCore/Tasks/Update/UpdateTaskUseRes.cs index 54aa9236b..e9d57dd5d 100644 --- a/TbsCore/Tasks/Update/UpdateTaskUseRes.cs +++ b/TbsCore/Tasks/Update/UpdateTaskUseRes.cs @@ -2,7 +2,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Update { internal class UpdateTaskUseRes : BotTask { diff --git a/TbsCore/Tasks/Update/UpdateTroops.cs b/TbsCore/Tasks/Update/UpdateTroops.cs index 9f79e2fad..b9afe3b39 100644 --- a/TbsCore/Tasks/Update/UpdateTroops.cs +++ b/TbsCore/Tasks/Update/UpdateTroops.cs @@ -5,7 +5,7 @@ using TbsCore.Models.VillageModels; using TbsCore.Parsers; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Update { public class UpdateTroops : BotTask { diff --git a/TbsCore/Tasks/Update/UpdateVillage.cs b/TbsCore/Tasks/Update/UpdateVillage.cs index ce57c31f8..e020d862f 100644 --- a/TbsCore/Tasks/Update/UpdateVillage.cs +++ b/TbsCore/Tasks/Update/UpdateVillage.cs @@ -4,7 +4,7 @@ using TbsCore.Parsers; using TbsCore.TravianData; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Update { public class UpdateVillage : BotTask { diff --git a/TravBotSharp/Views/HeroUc.cs b/TravBotSharp/Views/HeroUc.cs index b9fe5e8fb..98f3ab329 100644 --- a/TravBotSharp/Views/HeroUc.cs +++ b/TravBotSharp/Views/HeroUc.cs @@ -4,6 +4,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Update; using TravBotSharp.Forms.Hero; using TravBotSharp.Interfaces; diff --git a/TravBotSharp/Views/VillageViews/BuildUc.cs b/TravBotSharp/Views/VillageViews/BuildUc.cs index dc7bab61b..0c4e443db 100644 --- a/TravBotSharp/Views/VillageViews/BuildUc.cs +++ b/TravBotSharp/Views/VillageViews/BuildUc.cs @@ -10,6 +10,7 @@ using TbsCore.Tasks; using TbsCore.Tasks.LowLevel; using TbsCore.Tasks.Sim; +using TbsCore.Tasks.Update; using TravBotSharp.Interfaces; using static TbsCore.Helpers.Classificator; diff --git a/TravBotSharp/Views/VillagesUc.cs b/TravBotSharp/Views/VillagesUc.cs index 2296218a6..9f4639178 100644 --- a/TravBotSharp/Views/VillagesUc.cs +++ b/TravBotSharp/Views/VillagesUc.cs @@ -7,6 +7,7 @@ using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Update; using TravBotSharp.Interfaces; namespace TravBotSharp.Views From 604d242dd57950ad626e7c8204e7c10107a9fe17 Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 15:49:40 +0700 Subject: [PATCH 08/16] add check to get server info & get tribe --- TbsCore/Tasks/Update/GetServerInfo.cs | 5 ++++- TbsCore/Tasks/Update/GetTribe.cs | 6 +++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/TbsCore/Tasks/Update/GetServerInfo.cs b/TbsCore/Tasks/Update/GetServerInfo.cs index d7fa46653..5100efd80 100644 --- a/TbsCore/Tasks/Update/GetServerInfo.cs +++ b/TbsCore/Tasks/Update/GetServerInfo.cs @@ -8,7 +8,10 @@ public class GetServerInfo : BotTask { public override async Task Execute(Account acc) { - await Task.Yield(); + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } // Get Map size var size = DriverHelper.GetJsObj(acc, "window.TravianDefaults.Map.Size.top"); acc.AccInfo.MapSize = (int)size; diff --git a/TbsCore/Tasks/Update/GetTribe.cs b/TbsCore/Tasks/Update/GetTribe.cs index c91b5c2bf..3553fc6d2 100644 --- a/TbsCore/Tasks/Update/GetTribe.cs +++ b/TbsCore/Tasks/Update/GetTribe.cs @@ -11,7 +11,11 @@ public class GetTribe : BotTask { public override async Task Execute(Account acc) { - await Task.Yield(); + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + switch (acc.AccInfo.ServerVersion) { case Classificator.ServerVersionEnum.TTwars: From 06154ec92a41ab491a5b6a2385122c213791dcff Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 15:49:55 +0700 Subject: [PATCH 09/16] rework update hero task --- TbsCore/Helpers/NavigationHelper.cs | 123 +++++++++++++------------ TbsCore/Tasks/Update/HeroUpdateInfo.cs | 15 ++- 2 files changed, 77 insertions(+), 61 deletions(-) diff --git a/TbsCore/Helpers/NavigationHelper.cs b/TbsCore/Helpers/NavigationHelper.cs index 44a7bd677..02e229007 100644 --- a/TbsCore/Helpers/NavigationHelper.cs +++ b/TbsCore/Helpers/NavigationHelper.cs @@ -283,91 +283,96 @@ public static async Task ToRallyPoint(Account acc, Village vill, RallyPoin public static async Task ToTreasury(Account acc, Village vill, TreasuryTab tab) => await EnterBuilding(acc, vill, BuildingEnum.Treasury, (int)tab); - public static async Task ToHero(Account acc, HeroTab tab) + public static async Task ToHero(Account acc, HeroTab tab) { switch (acc.AccInfo.ServerVersion) { case ServerVersionEnum.TTwars: - await ToHeroTTwar(acc, tab); - break; + return await ToHeroTTwar(acc, tab); case ServerVersionEnum.T4_5: - await ToHeroT45(acc, tab); - break; + return await ToHeroT45(acc, tab); } } - private static async Task ToHeroTTwar(Account acc, HeroTab tab) + private static async Task ToHeroTTwar(Account acc, HeroTab tab) { - do + HtmlNode node; + switch (tab) { - switch (tab) - { - case HeroTab.Appearance: - throw new NotImplementedException(); + case HeroTab.Appearance: + throw new NotImplementedException(); - case HeroTab.Attributes: - await DriverHelper.ClickById(acc, "heroImageButton"); - break; + case HeroTab.Attributes: + node = acc.Wb.Html.GetElementbyId("heroImageButton"); + break; - case HeroTab.Adventures: - await DriverHelper.ClickByClassName(acc, "adventureWhite"); - break; + case HeroTab.Adventures: + node = acc.Wb.Html.DocumentNode.Descendants().FirstOrDefault(x => x.HasClass("adventureWhite")); + break; - case HeroTab.Auctions: - await DriverHelper.ClickByClassName(acc, "auctionWhite"); - break; - } + case HeroTab.Auctions: + node = acc.Wb.Html.DocumentNode.Descendants().FirstOrDefault(x => x.HasClass("auctionWhite")); + break; - try - { - await DriverHelper.WaitPageChange(acc, "hero.php"); + default: + node = null; + break; + } - if (tab == HeroTab.Attributes) HeroHelper.ParseHeroPage(acc); - } - catch - { - continue; - } - return; + if (node == null) + { + acc.Logger.Warning($"Cannot find button to go to {tab}"); + return false; } - while (true); + + var element = acc.Wb.Driver.FindElement(By.XPath(node.XPath)); + element.Click(); + + var result = await DriverHelper.WaitPageChange(acc, "hero.php"); + if (!result) return false; + if (tab == HeroTab.Attributes) HeroHelper.ParseHeroPage(acc); + return true; } - private static async Task ToHeroT45(Account acc, HeroTab tab) + private static async Task ToHeroT45(Account acc, HeroTab tab) { - do + HtmlNode node; + switch (tab) { - switch (tab) - { - case HeroTab.Appearance: - throw new NotImplementedException(); + case HeroTab.Appearance: + throw new NotImplementedException(); - case HeroTab.Attributes: - await DriverHelper.ClickById(acc, "heroImageButton"); - break; + case HeroTab.Attributes: + node = acc.Wb.Html.GetElementbyId("heroImageButton"); + break; - case HeroTab.Adventures: - await DriverHelper.ClickByClassName(acc, "adventure"); - break; + case HeroTab.Adventures: + node = acc.Wb.Html.DocumentNode.Descendants().FirstOrDefault(x => x.HasClass("adventure")); + break; - case HeroTab.Auctions: - await DriverHelper.ClickByClassName(acc, "auction"); - break; - } + case HeroTab.Auctions: + node = acc.Wb.Html.DocumentNode.Descendants().FirstOrDefault(x => x.HasClass("auction")); + break; - try - { - await DriverHelper.WaitPageChange(acc, "hero"); - if (tab == HeroTab.Attributes) HeroHelper.ParseHeroPage(acc); - } - catch - { - continue; - } - return; + default: + node = null; + break; + } + + if (node == null) + { + acc.Logger.Warning($"Cannot find button to go to {tab}"); + return false; } - while (true); + + var element = acc.Wb.Driver.FindElement(By.XPath(node.XPath)); + element.Click(); + + var result = await DriverHelper.WaitPageChange(acc, "hero"); + if (!result) return false; + if (tab == HeroTab.Attributes) HeroHelper.ParseHeroPage(acc); + return true; } public static async Task ToOverview(Account acc, OverviewTab tab, TroopOverview subTab = TroopOverview.OwnTroops) diff --git a/TbsCore/Tasks/Update/HeroUpdateInfo.cs b/TbsCore/Tasks/Update/HeroUpdateInfo.cs index b76566b8b..f52a854d5 100644 --- a/TbsCore/Tasks/Update/HeroUpdateInfo.cs +++ b/TbsCore/Tasks/Update/HeroUpdateInfo.cs @@ -13,7 +13,16 @@ public class HeroUpdateInfo : BotTask public override async Task Execute(Account acc) { - await NavigationHelper.ToHero(acc, NavigationHelper.HeroTab.Attributes); + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + var result = await NavigationHelper.ToHero(acc, NavigationHelper.HeroTab.Attributes); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } if (acc.Hero.Settings.AutoAuction) { @@ -42,12 +51,14 @@ public override async Task Execute(Account acc) break; } } + if (acc.Hero.Settings.AutoRefreshInfo) { - this.NextExecute = DateTime.Now.AddMinutes( + NextExecute = DateTime.Now.AddMinutes( ran.Next(acc.Hero.Settings.MinUpdate, acc.Hero.Settings.MaxUpdate) ); } + acc.Tasks.Remove(typeof(HeroUpdateInfo), thisTask: this); return TaskRes.Executed; From 54b8d6335c99707491220fb7ae7d75667cd1e04a Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 16:04:46 +0700 Subject: [PATCH 10/16] rework read message --- TbsCore/Helpers/AccountHelper.cs | 2 +- TbsCore/Helpers/NavigationHelper.cs | 2 +- TbsCore/Tasks/Update/ReadMessage.cs | 52 +++++++++++++++++++---------- 3 files changed, 37 insertions(+), 19 deletions(-) diff --git a/TbsCore/Helpers/AccountHelper.cs b/TbsCore/Helpers/AccountHelper.cs index 615ae6a24..8c4b6b781 100644 --- a/TbsCore/Helpers/AccountHelper.cs +++ b/TbsCore/Helpers/AccountHelper.cs @@ -59,7 +59,7 @@ public static Village GetQuestsClaimVillage(Account acc) /// Random delay in milliseconds public static int Delay(Account acc) => rnd.Next(acc.Settings.DelayClickingMin, acc.Settings.DelayClickingMax); - public static Task DelayWait(Account acc) => Task.Delay(Delay(acc)); + public static Task DelayWait(Account acc, int multiple = 1) => Task.Delay(Delay(acc) * multiple); public static void StartAccountTasks(Account acc) { diff --git a/TbsCore/Helpers/NavigationHelper.cs b/TbsCore/Helpers/NavigationHelper.cs index 02e229007..b3153c2b0 100644 --- a/TbsCore/Helpers/NavigationHelper.cs +++ b/TbsCore/Helpers/NavigationHelper.cs @@ -54,7 +54,7 @@ public static async Task MainNavigate(Account acc, MainNavigationButton bu await DriverHelper.ClickByAttributeValue(acc, "accesskey", ((int)button).ToString()); if (buttonInt < urlMaianNavigation.Length) { - await DriverHelper.WaitPageChange(acc, urlMaianNavigation[(int)button]); + return await DriverHelper.WaitPageChange(acc, urlMaianNavigation[(int)button]); } return true; } diff --git a/TbsCore/Tasks/Update/ReadMessage.cs b/TbsCore/Tasks/Update/ReadMessage.cs index 4a5fe945a..47aa9c51b 100644 --- a/TbsCore/Tasks/Update/ReadMessage.cs +++ b/TbsCore/Tasks/Update/ReadMessage.cs @@ -9,27 +9,45 @@ public class ReadMessage : BotTask { public override async Task Execute(Account acc) { - while (true) + StopFlag = false; + do { - await NavigationHelper.MainNavigate(acc, NavigationHelper.MainNavigationButton.Messages); + if (StopFlag) return TaskRes.Executed; + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + var result = await NavigationHelper.MainNavigate(acc, NavigationHelper.MainNavigationButton.Messages); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + var msg = acc.Wb.Html.DocumentNode.Descendants("img").FirstOrDefault(x => x.HasClass("messageStatusUnread")); - if (msg != null) + if (msg == null) { - var url = msg.ParentNode.GetAttributeValue("href", "").Replace("amp;", ""); - switch (acc.AccInfo.ServerVersion) - { - case Classificator.ServerVersionEnum.T4_5: - await acc.Wb.Navigate(acc.AccInfo.ServerUrl + url); - break; - - case Classificator.ServerVersionEnum.TTwars: - await acc.Wb.Navigate(acc.AccInfo.ServerUrl + "/" + url); - break; - } - await Task.Delay(AccountHelper.Delay(acc) * 5); + acc.Logger.Information("Cannot found any unread message"); + return TaskRes.Executed; } - else return TaskRes.Executed; - } + + var url = msg.ParentNode.GetAttributeValue("href", "").Replace("amp;", ""); + + switch (acc.AccInfo.ServerVersion) + { + case Classificator.ServerVersionEnum.T4_5: + await acc.Wb.Navigate(acc.AccInfo.ServerUrl + url); + break; + + case Classificator.ServerVersionEnum.TTwars: + await acc.Wb.Navigate(acc.AccInfo.ServerUrl + "/" + url); + break; + } + + if (StopFlag) return TaskRes.Executed; + await AccountHelper.DelayWait(acc, 5); + } while (true); } } } \ No newline at end of file From 9e49eccbadd797a8108a9f411cb90b9dc266f8cd Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 16:13:51 +0700 Subject: [PATCH 11/16] rework updatedorf --- TbsCore/Tasks/Update/UpdateDorf1.cs | 19 ++++++++++++++-- TbsCore/Tasks/Update/UpdateDorf2.cs | 18 +++++++++++++-- TbsCore/Tasks/Update/UpdateTaskUseRes.cs | 28 ------------------------ 3 files changed, 33 insertions(+), 32 deletions(-) delete mode 100644 TbsCore/Tasks/Update/UpdateTaskUseRes.cs diff --git a/TbsCore/Tasks/Update/UpdateDorf1.cs b/TbsCore/Tasks/Update/UpdateDorf1.cs index 53cd922a5..02ce899f0 100644 --- a/TbsCore/Tasks/Update/UpdateDorf1.cs +++ b/TbsCore/Tasks/Update/UpdateDorf1.cs @@ -9,11 +9,26 @@ public class UpdateDorf1 : BotTask { public override async Task Execute(Account acc) { - acc.Tasks.Remove(this.GetType(), Vill, thisTask: this); + StopFlag = false; + + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } if (!acc.Wb.CurrentUrl.Contains("/dorf1.php")) // Don't re-navigate { - await NavigationHelper.ToDorf1(acc); + var result = await NavigationHelper.ToDorf1(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + + { + var result = await Update(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; } // 60% to check update dorf2 diff --git a/TbsCore/Tasks/Update/UpdateDorf2.cs b/TbsCore/Tasks/Update/UpdateDorf2.cs index 0c1ab46a0..525b4e7fc 100644 --- a/TbsCore/Tasks/Update/UpdateDorf2.cs +++ b/TbsCore/Tasks/Update/UpdateDorf2.cs @@ -8,11 +8,25 @@ public class UpdateDorf2 : BotTask { public override async Task Execute(Account acc) { - acc.Tasks.Remove(this.GetType(), Vill, thisTask: this); + StopFlag = false; + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } if (!acc.Wb.CurrentUrl.Contains("/dorf2.php")) // Don't re-navigate { - await NavigationHelper.ToDorf2(acc); + var result = await NavigationHelper.ToDorf2(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + + { + var result = await Update(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; } return TaskRes.Executed; diff --git a/TbsCore/Tasks/Update/UpdateTaskUseRes.cs b/TbsCore/Tasks/Update/UpdateTaskUseRes.cs deleted file mode 100644 index e9d57dd5d..000000000 --- a/TbsCore/Tasks/Update/UpdateTaskUseRes.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Threading.Tasks; -using TbsCore.Helpers; -using TbsCore.Models.AccModels; - -namespace TbsCore.Tasks.Update -{ - internal class UpdateTaskUseRes : BotTask - { - public override async Task Execute(Account acc) - { - // Troops task - TroopsHelper.ReStartTroopTraining(acc, Vill); - await Task.Delay(AccountHelper.Delay(acc)); - TroopsHelper.ReStartResearchAndImprovement(acc, Vill); - await Task.Delay(AccountHelper.Delay(acc)); - - // Building task - UpgradeBuildingHelper.ReStartBuilding(acc, Vill); - await Task.Delay(AccountHelper.Delay(acc)); - BuildingHelper.ReStartDemolishing(acc, Vill); - await Task.Delay(AccountHelper.Delay(acc)); - - // Celebration task - AccountHelper.ReStartCelebration(acc, Vill); - return TaskRes.Executed; - } - } -} \ No newline at end of file From 9c2c108fdd24a830322e6545374f7b7d3a429111 Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 17:50:33 +0700 Subject: [PATCH 12/16] rework claim beginer task --- TbsCore/Core/PostLoadHelper.cs | 2 +- TbsCore/Helpers/NavigationHelper.cs | 3 + TbsCore/Tasks/Sim/ClaimBeginnerTask.cs | 50 +++++++--- TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs | 101 +++++++++++++++++---- TbsCore/Tasks/Update/UpdateDorf1.cs | 1 - 5 files changed, 121 insertions(+), 36 deletions(-) diff --git a/TbsCore/Core/PostLoadHelper.cs b/TbsCore/Core/PostLoadHelper.cs index 666704f37..2caae124d 100644 --- a/TbsCore/Core/PostLoadHelper.cs +++ b/TbsCore/Core/PostLoadHelper.cs @@ -92,7 +92,7 @@ public static List GetPostLoadTasks(Account acc) acc.Wb.Html.GetElementbyId("mentorTaskList") == null && acc.Quests.ClaimBeginnerQuests) { - acc.Tasks.Add(new ClaimBeginnerTask2021() { ExecuteAt = DateTime.Now}, true); + acc.Tasks.Add(new ClaimBeginnerTask2021() { Vill = vill, ExecuteAt = DateTime.Now}, true); ; return; } diff --git a/TbsCore/Helpers/NavigationHelper.cs b/TbsCore/Helpers/NavigationHelper.cs index b3153c2b0..1f06f4e1a 100644 --- a/TbsCore/Helpers/NavigationHelper.cs +++ b/TbsCore/Helpers/NavigationHelper.cs @@ -292,6 +292,9 @@ public static async Task ToHero(Account acc, HeroTab tab) case ServerVersionEnum.T4_5: return await ToHeroT45(acc, tab); + + default: + return false; } } diff --git a/TbsCore/Tasks/Sim/ClaimBeginnerTask.cs b/TbsCore/Tasks/Sim/ClaimBeginnerTask.cs index 4d8fc82d0..da89ea2d7 100644 --- a/TbsCore/Tasks/Sim/ClaimBeginnerTask.cs +++ b/TbsCore/Tasks/Sim/ClaimBeginnerTask.cs @@ -1,6 +1,6 @@ -using System.Linq; +using OpenQA.Selenium; +using System.Linq; using System.Threading.Tasks; -using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.SideBarModels; @@ -12,24 +12,44 @@ public class ClaimBeginnerTask : BotTask public override async Task Execute(Account acc) { - var script = $"document.getElementById('mentorTaskList').querySelector('[data-questid=\"{this.QuestToClaim.Id}\"]').click();"; - await DriverHelper.ExecuteScript(acc, script); - await Task.Delay(AccountHelper.Delay(acc) * 2); + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } - string buttonId = ""; - switch (acc.AccInfo.ServerVersion) + var mentorTaskNode = acc.Wb.Html.GetElementbyId("mentorTaskList"); + if (mentorTaskNode == null) + { + acc.Logger.Warning("Cannot find mentor."); + return TaskRes.Executed; + } + var questNode = mentorTaskNode.Descendants().FirstOrDefault(x => x.GetAttributeValue("data-questid", "").Equals($"{QuestToClaim.Id}")); + if (questNode == null) { - case Classificator.ServerVersionEnum.T4_5: - buttonId = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.GetAttributeValue("questid", "") == this.QuestToClaim.Id).Id; - break; + acc.Logger.Warning("Cannot find quest."); + return TaskRes.Executed; + } + var questElement = acc.Wb.Driver.FindElement(By.XPath(questNode.XPath)); + questElement.Click(); - case Classificator.ServerVersionEnum.TTwars: - buttonId = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("questButtonNext"))?.Id; - break; + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; } - await DriverHelper.ClickById(acc, buttonId); - await DriverHelper.WaitPageLoaded(acc); // Optional + var buttonNode = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("questButtonNext")); + if (buttonNode == null) + { + acc.Logger.Warning("Cannot find Next button"); + return TaskRes.Executed; + } + var buttonElement = acc.Wb.Driver.FindElement(By.XPath(buttonNode.XPath)); + buttonElement.Click(); + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } return TaskRes.Executed; } diff --git a/TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs b/TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs index 0d4a9a914..a5a38ad6e 100644 --- a/TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs +++ b/TbsCore/Tasks/Sim/ClaimBeginnerTask2021.cs @@ -1,9 +1,9 @@ -using System; +using OpenQA.Selenium; +using System; using System.Linq; using System.Threading.Tasks; using TbsCore.Helpers; using TbsCore.Models.AccModels; -using TbsCore.Tasks.LowLevel; using TbsCore.Tasks.Update; namespace TbsCore.Tasks.Sim @@ -12,37 +12,100 @@ public class ClaimBeginnerTask2021 : BotTask { public override async Task Execute(Account acc) { - // Claim village-wide rewards - await DriverHelper.ClickById(acc, "questmasterButton"); - await ClaimRewards(acc); + StopFlag = false; - if (acc.Wb.Html - .GetElementbyId("sidebarBoxQuestmaster")? - .Descendants()? - .Any(x => x.HasClass("newQuestSpeechBubble")) ?? false) { - // Claim account-wide rewards - await DriverHelper.ClickByClassName(acc, "tabItem", 1); - await ClaimRewards(acc); + acc.Tasks.Add(new HeroUpdateInfo() { ExecuteAt = DateTime.Now }); } - acc.Tasks.Add(new HeroUpdateInfo() { ExecuteAt = DateTime.Now }); + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + + { + var result = await Update(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + + { + var questMasterNode = acc.Wb.Html.GetElementbyId("questmasterButton"); + if (questMasterNode == null) + { + acc.Logger.Warning("Cannot find quest master"); + return TaskRes.Executed; + } + var questMasterElement = acc.Wb.Driver.FindElement(By.XPath(questMasterNode.XPath)); + questMasterElement.Click(); + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + var result = await ClaimRewards(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + + { + var result = await Update(acc); + if (!result) return TaskRes.Executed; + } + + { + var sidebarBox = acc.Wb.Html.GetElementbyId("sidebarBoxQuestmaster"); + if (sidebarBox != null && sidebarBox.Descendants().Any(x => x.HasClass("newQuestSpeechBubble"))) + { + var tabNode = acc.Wb.Html.DocumentNode.Descendants("a").FirstOrDefault(x => x.HasClass("tabItem") && x.GetAttributeValue("data-tab", "").Equals("2")); + if (tabNode != null) + { + var tabElement = acc.Wb.Driver.FindElement(By.XPath(tabNode.XPath)); + tabElement.Click(); + + var result = await ClaimRewards(acc); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + } + } return TaskRes.Executed; } - private async Task ClaimRewards(Account acc) + private async Task ClaimRewards(Account acc) { int count = 0; do { - await DriverHelper.ClickByClassName(acc, "collect", log: false); - await Task.Delay(AccountHelper.Delay(acc)); - acc.Wb.UpdateHtml(); + { + var result = await Update(acc); + if (!result) return false; + } + + var collectNode = acc.Wb.Html.DocumentNode.Descendants("button").FirstOrDefault(x => x.HasClass("collect")); + if (collectNode == null) return true; + + var collectElement = acc.Wb.Driver.FindElement(By.XPath(collectNode.XPath)); + collectElement.Click(); + if (StopFlag) return false; + + await AccountHelper.DelayWait(acc, 5); + + { + var result = await Update(acc); + if (!result) return false; + } + count++; - if (count > 50) break; // infinite loop ( i dont think there is over 50 quest waiting bot ) + if (count > 50) return true; // infinite loop ( i dont think there is over 50 quest waiting bot ) } - while (acc.Wb.Html.DocumentNode.Descendants("button").Any(x => x.HasClass("collect"))); + while (true); } } } \ No newline at end of file diff --git a/TbsCore/Tasks/Update/UpdateDorf1.cs b/TbsCore/Tasks/Update/UpdateDorf1.cs index 02ce899f0..b9422fb6e 100644 --- a/TbsCore/Tasks/Update/UpdateDorf1.cs +++ b/TbsCore/Tasks/Update/UpdateDorf1.cs @@ -27,7 +27,6 @@ public override async Task Execute(Account acc) { var result = await Update(acc); - if (StopFlag) return TaskRes.Executed; if (!result) return TaskRes.Executed; } From 4f2cca71897c486680c3626b7fee95fa8de825df Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 20:27:03 +0700 Subject: [PATCH 13/16] add switch village to Task.Farm --- TbsCore/Helpers/NavigationHelper.cs | 2 +- TbsCore/Tasks/Farm/AddFarm.cs | 6 ++++++ TbsCore/Tasks/Farm/ImproveTroop.cs | 7 ++++++- TbsCore/Tasks/Farm/ResearchTroop.cs | 6 ++++++ TbsCore/Tasks/Farm/SendDeff.cs | 7 +++++++ TbsCore/Tasks/Farm/SendFarmlist.cs | 6 ++++++ TbsCore/Tasks/Farm/SendTroops.cs | 7 +++++++ TbsCore/Tasks/Farm/SendWaves.cs | 6 ++++++ TbsCore/Tasks/Farm/TrainExchangeRes.cs | 7 ++++++- TbsCore/Tasks/Farm/TrainTroops.cs | 7 +++++++ TbsCore/Tasks/Farm/UpdateFarmLists.cs | 7 +++++++ 11 files changed, 65 insertions(+), 3 deletions(-) diff --git a/TbsCore/Helpers/NavigationHelper.cs b/TbsCore/Helpers/NavigationHelper.cs index 1f06f4e1a..df66dfd07 100644 --- a/TbsCore/Helpers/NavigationHelper.cs +++ b/TbsCore/Helpers/NavigationHelper.cs @@ -251,7 +251,7 @@ public static async Task EnterBuilding(Account acc, Village vill, int buil public static async Task EnterBuilding(Account acc, Village vill, BuildingEnum buildingEnum, int? tab = null, Coordinates coords = null) { - var building = vill.Build.Buildings.FirstOrDefault(x => x.Type == buildingEnum); + var building = vill?.Build.Buildings.FirstOrDefault(x => x.Type == buildingEnum); if (building == null) { acc.Logger.Warning($"Tried to enter {buildingEnum} but couldn't find it in village {vill.Name}!"); diff --git a/TbsCore/Tasks/Farm/AddFarm.cs b/TbsCore/Tasks/Farm/AddFarm.cs index 82e6b4403..f9dab9fc1 100644 --- a/TbsCore/Tasks/Farm/AddFarm.cs +++ b/TbsCore/Tasks/Farm/AddFarm.cs @@ -12,6 +12,12 @@ public class AddFarm : BotTask public override async Task Execute(Account acc) { + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } await NavigationHelper.ToRallyPoint(acc, Vill, NavigationHelper.RallyPointTab.Farmlist); diff --git a/TbsCore/Tasks/Farm/ImproveTroop.cs b/TbsCore/Tasks/Farm/ImproveTroop.cs index f9b64abea..5a7e56b02 100644 --- a/TbsCore/Tasks/Farm/ImproveTroop.cs +++ b/TbsCore/Tasks/Farm/ImproveTroop.cs @@ -14,7 +14,12 @@ public class ImproveTroop : BotTask { public override async Task Execute(Account acc) { - if (Vill == null) Vill = acc.Villages.First(x => x.Active); + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } if (!await NavigationHelper.EnterBuilding(acc, Vill, Classificator.BuildingEnum.Smithy)) return TaskRes.Executed; diff --git a/TbsCore/Tasks/Farm/ResearchTroop.cs b/TbsCore/Tasks/Farm/ResearchTroop.cs index 225257ce8..f439b494c 100644 --- a/TbsCore/Tasks/Farm/ResearchTroop.cs +++ b/TbsCore/Tasks/Farm/ResearchTroop.cs @@ -16,6 +16,12 @@ public class ResearchTroop : BotTask //If Troop == null, just update the troop levels public override async Task Execute(Account acc) { + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } if (!await NavigationHelper.EnterBuilding(acc, Vill, BuildingEnum.Academy)) return TaskRes.Executed; diff --git a/TbsCore/Tasks/Farm/SendDeff.cs b/TbsCore/Tasks/Farm/SendDeff.cs index a5c26598d..ecba421f9 100644 --- a/TbsCore/Tasks/Farm/SendDeff.cs +++ b/TbsCore/Tasks/Farm/SendDeff.cs @@ -15,6 +15,13 @@ public class SendDeff : SendTroops public override async Task Execute(Account acc) { + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + // Can't send deff to home village or to 0/0 if (TargetVillage == null || TargetVillage.Equals(Vill.Coordinates) || diff --git a/TbsCore/Tasks/Farm/SendFarmlist.cs b/TbsCore/Tasks/Farm/SendFarmlist.cs index a59222103..eadf98c3a 100644 --- a/TbsCore/Tasks/Farm/SendFarmlist.cs +++ b/TbsCore/Tasks/Farm/SendFarmlist.cs @@ -18,6 +18,12 @@ public class SendFarmlist : BotTask public override async Task Execute(Account acc) { + { + var result = await NavigationHelper.SwitchVillage(acc, acc.Villages.First()); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + await NavigationHelper.ToRallyPoint(acc, Vill, NavigationHelper.RallyPointTab.Farmlist); var flNode = GetFlNode(acc.Wb.Html, acc.AccInfo.ServerVersion); diff --git a/TbsCore/Tasks/Farm/SendTroops.cs b/TbsCore/Tasks/Farm/SendTroops.cs index 323f7ddcd..fd34d80c2 100644 --- a/TbsCore/Tasks/Farm/SendTroops.cs +++ b/TbsCore/Tasks/Farm/SendTroops.cs @@ -30,6 +30,7 @@ public class SendTroops : BotTask /// If false, bot will skip this task. /// public bool SendPartialAttack { get; set; } = false; + /// /// Whether we want to embed coordinates into the url. This saves ~1 sec and it used when searching from the map / send troops clicked /// @@ -38,6 +39,12 @@ public class SendTroops : BotTask public override async Task Execute(Account acc) { //if (acc.AccInfo.ServerVersion == Classificator.ServerVersionEnum.TTwars) SetCoordsInUrl = true; + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } await NavigationHelper.ToRallyPoint(acc, Vill, NavigationHelper.RallyPointTab.SendTroops, TroopsMovement.TargetCoordinates diff --git a/TbsCore/Tasks/Farm/SendWaves.cs b/TbsCore/Tasks/Farm/SendWaves.cs index 8db56969f..b4bdadf5d 100644 --- a/TbsCore/Tasks/Farm/SendWaves.cs +++ b/TbsCore/Tasks/Farm/SendWaves.cs @@ -23,6 +23,12 @@ public class SendWaves : BotTask public override async Task Execute(Account acc) { + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } await NavigationHelper.ToRallyPoint(acc, Vill, NavigationHelper.RallyPointTab.SendTroops); var wavesReady = new List(); diff --git a/TbsCore/Tasks/Farm/TrainExchangeRes.cs b/TbsCore/Tasks/Farm/TrainExchangeRes.cs index 3272183fa..2a5b82aff 100644 --- a/TbsCore/Tasks/Farm/TrainExchangeRes.cs +++ b/TbsCore/Tasks/Farm/TrainExchangeRes.cs @@ -14,7 +14,12 @@ public class TrainExchangeRes : BotTask public override async Task Execute(Account acc) { if (Vill == null) Vill = AccountHelper.GetMainVillage(acc); - + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } var building = TroopsData.GetTroopBuilding(troop, Great); if (!await NavigationHelper.EnterBuilding(acc, Vill, building)) return TaskRes.Executed; diff --git a/TbsCore/Tasks/Farm/TrainTroops.cs b/TbsCore/Tasks/Farm/TrainTroops.cs index 6310a802e..d39da2adc 100644 --- a/TbsCore/Tasks/Farm/TrainTroops.cs +++ b/TbsCore/Tasks/Farm/TrainTroops.cs @@ -42,6 +42,13 @@ public class TrainTroops : BotTask public override async Task Execute(Account acc) { + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + building = TroopsData.GetTroopBuilding(Troop, Great); // Switch hero helmet. If hero will be switched, this TrainTroops task diff --git a/TbsCore/Tasks/Farm/UpdateFarmLists.cs b/TbsCore/Tasks/Farm/UpdateFarmLists.cs index 2612618ff..980a2c82d 100644 --- a/TbsCore/Tasks/Farm/UpdateFarmLists.cs +++ b/TbsCore/Tasks/Farm/UpdateFarmLists.cs @@ -15,6 +15,13 @@ public class UpdateFarmLists : BotTask { public override async Task Execute(Account acc) { + Vill = acc.Villages.First(); + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } await NavigationHelper.ToRallyPoint(acc, this.Vill, NavigationHelper.RallyPointTab.Farmlist); var foundFLs = FarmlistParser.ParseFL(acc.Wb.Html, acc.AccInfo.ServerVersion); From 8b0846e6637d57d0fa7e0b4437786e1d1dba1ac5 Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 20:30:48 +0700 Subject: [PATCH 14/16] add switch village to Task.Sim --- TbsCore/Tasks/Sim/DemolishBuilding.cs | 7 +++++++ TbsCore/Tasks/Sim/ExtendProtection.cs | 9 +++++++++ TbsCore/Tasks/Sim/InstaUpgrade.cs | 8 ++++++++ TbsCore/Tasks/Sim/NPC.cs | 8 ++++++++ TbsCore/Tasks/Sim/SendSettlers.cs | 8 ++++++++ TbsCore/Tasks/Sim/TrainSettlers.cs | 5 +++++ 6 files changed, 45 insertions(+) diff --git a/TbsCore/Tasks/Sim/DemolishBuilding.cs b/TbsCore/Tasks/Sim/DemolishBuilding.cs index 448453cf7..deaa22c8d 100644 --- a/TbsCore/Tasks/Sim/DemolishBuilding.cs +++ b/TbsCore/Tasks/Sim/DemolishBuilding.cs @@ -13,6 +13,13 @@ public class DemolishBuilding : BotTask { public override async Task Execute(Account acc) { + StopFlag = false; + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } // First navigate to dorf2 and then to the main building, to make sure the currently demolish list is refreshed if (!await NavigationHelper.EnterBuilding(acc, Vill, Classificator.BuildingEnum.MainBuilding)) return TaskRes.Executed; diff --git a/TbsCore/Tasks/Sim/ExtendProtection.cs b/TbsCore/Tasks/Sim/ExtendProtection.cs index 5d3e9a181..97aa17eb5 100644 --- a/TbsCore/Tasks/Sim/ExtendProtection.cs +++ b/TbsCore/Tasks/Sim/ExtendProtection.cs @@ -1,4 +1,5 @@ using System.Threading.Tasks; +using TbsCore.Helpers; using TbsCore.Models.AccModels; namespace TbsCore.Tasks.Sim @@ -10,6 +11,14 @@ public class ExtendProtection : BotTask { public override async Task Execute(Account acc) { + StopFlag = false; + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + await acc.Wb.Navigate($"{acc.AccInfo.ServerUrl}/options/game?extendBeginnersProtection"); return TaskRes.Executed; } diff --git a/TbsCore/Tasks/Sim/InstaUpgrade.cs b/TbsCore/Tasks/Sim/InstaUpgrade.cs index 28911c623..321f90df9 100644 --- a/TbsCore/Tasks/Sim/InstaUpgrade.cs +++ b/TbsCore/Tasks/Sim/InstaUpgrade.cs @@ -13,6 +13,14 @@ public class InstaUpgrade : BotTask { public override async Task Execute(Account acc) { + StopFlag = false; + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + await NavigationHelper.ToDorf1(acc); var finishClass = acc.Wb.Html.DocumentNode diff --git a/TbsCore/Tasks/Sim/NPC.cs b/TbsCore/Tasks/Sim/NPC.cs index 19a207885..0236e44ac 100644 --- a/TbsCore/Tasks/Sim/NPC.cs +++ b/TbsCore/Tasks/Sim/NPC.cs @@ -12,6 +12,14 @@ public class NPC : BotTask { public override async Task Execute(Account acc) { + StopFlag = false; + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + if (!await NavigationHelper.ToMarketplace(acc, Vill, NavigationHelper.MarketplaceTab.Managenment)) return TaskRes.Executed; diff --git a/TbsCore/Tasks/Sim/SendSettlers.cs b/TbsCore/Tasks/Sim/SendSettlers.cs index 9b7379086..dd2089cd0 100644 --- a/TbsCore/Tasks/Sim/SendSettlers.cs +++ b/TbsCore/Tasks/Sim/SendSettlers.cs @@ -11,6 +11,14 @@ public class SendSettlers : BotTask { public override async Task Execute(Account acc) { + StopFlag = false; + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (StopFlag) return TaskRes.Executed; + if (!result) return TaskRes.Executed; + } + // Check if the account has enough culture points if (acc.AccInfo.CulturePoints.MaxVillages <= acc.AccInfo.CulturePoints.VillageCount) { diff --git a/TbsCore/Tasks/Sim/TrainSettlers.cs b/TbsCore/Tasks/Sim/TrainSettlers.cs index 2aafecfa0..25a042488 100644 --- a/TbsCore/Tasks/Sim/TrainSettlers.cs +++ b/TbsCore/Tasks/Sim/TrainSettlers.cs @@ -161,6 +161,11 @@ private async Task BuildingRequired(Account acc) private async Task EnterBuilding(Account acc) { + { + acc.Logger.Information($"Checking current village ..."); + var result = await NavigationHelper.SwitchVillage(acc, Vill); + if (!result) return false; + } return await NavigationHelper.ToGovernmentBuilding(acc, Vill, NavigationHelper.ResidenceTab.Train); } From 3164bc69d6aba536e859c9062bd052fd1c7b1850 Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 21:11:54 +0700 Subject: [PATCH 15/16] fix namespace --- TbsCore/Core/PostLoadHelper.cs | 2 +- TbsCore/Core/TaskExecutor.cs | 2 +- TbsCore/Core/TaskTimer.cs | 2 +- TbsCore/Helpers/AccountHelper.cs | 3 +-- TbsCore/Helpers/HeroHelper.cs | 3 ++- TbsCore/Helpers/MarketHelper.cs | 4 ++-- TbsCore/Helpers/ResSpendingHelper.cs | 2 +- TbsCore/Helpers/ResourcesHelper.cs | 2 +- TbsCore/Helpers/TroopsHelper.cs | 2 +- TbsCore/Helpers/UpdateAccountObject.cs | 2 +- TbsCore/Tasks/BotTaskTemplate.cs | 2 +- TbsCore/Tasks/{Farm => Farming}/AddFarm.cs | 2 +- TbsCore/Tasks/{Farm => Farming}/AttackOasis.cs | 2 +- TbsCore/Tasks/{Farm => Farming}/ImproveTroop.cs | 2 +- TbsCore/Tasks/{Farm => Farming}/ReadFarmScoutReport.cs | 3 ++- TbsCore/Tasks/{Farm => Farming}/ResearchTroop.cs | 2 +- TbsCore/Tasks/{Farm => Farming}/ScoutPlayer.cs | 3 +-- TbsCore/Tasks/{Farm => Farming}/SendDeff.cs | 2 +- TbsCore/Tasks/{Farm => Farming}/SendFLs.cs | 3 +-- TbsCore/Tasks/{Farm => Farming}/SendFarmlist.cs | 2 +- TbsCore/Tasks/{Farm => Farming}/SendRaid.cs | 3 ++- TbsCore/Tasks/{Farm => Farming}/SendReinforcementScouts.cs | 4 ++-- TbsCore/Tasks/{Farm => Farming}/SendTroops.cs | 2 +- TbsCore/Tasks/{Farm => Farming}/SendWaves.cs | 2 +- TbsCore/Tasks/{Farm => Farming}/TTWarsAddNatarsToFL.cs | 3 +-- .../Tasks/{Farm => Farming}/TTWarsAddNatarsToNonGoldFL.cs | 3 +-- TbsCore/Tasks/{Farm => Farming}/TrainExchangeRes.cs | 2 +- TbsCore/Tasks/{Farm => Farming}/TrainTroops.cs | 3 ++- TbsCore/Tasks/{Farm => Farming}/TransitToMainAcc.cs | 3 ++- TbsCore/Tasks/{Farm => Farming}/UpdateFarmLists.cs | 2 +- TbsCore/Tasks/Others/ChangeVillageName.cs | 2 +- TbsCore/Tasks/Others/DonateAllyBonus.cs | 2 +- TbsCore/Tasks/Others/EditPreferences.cs | 2 +- TbsCore/Tasks/Others/HeroEquip.cs | 2 +- TbsCore/Tasks/Others/HeroSetPoints.cs | 2 +- TbsCore/Tasks/Others/LoginTask.cs | 2 +- TbsCore/Tasks/Others/RandomTask.cs | 2 +- TbsCore/Tasks/Others/ReviveHero.cs | 2 +- TbsCore/Tasks/Others/SellOnAuctions.cs | 2 +- TbsCore/Tasks/Others/SendResFillTroops.cs | 3 ++- TbsCore/Tasks/Others/SendResToMain.cs | 2 +- TbsCore/Tasks/Others/SendResources.cs | 2 +- TbsCore/Tasks/Others/SetCapital.cs | 2 +- TbsCore/Tasks/Others/StartAdventure.cs | 2 +- TbsCore/Tasks/Others/TTWarsBuyAdventure.cs | 2 +- TbsCore/Tasks/Others/TTWarsExpandStorage.cs | 2 +- TbsCore/Tasks/Others/TTWarsGetAnimals.cs | 2 +- TbsCore/Tasks/Others/TTWarsGetRes.cs | 3 ++- TbsCore/Tasks/Others/TTWarsPlusAndBoost.cs | 2 +- TbsCore/Tasks/Update/CheckAttacks.cs | 2 +- TbsCore/Tasks/Update/HeroUpdateInfo.cs | 2 +- TbsCoreTest/ResSpendingTest.cs | 2 +- TravBotSharp/Views/DeffendingUc.cs | 4 ++-- TravBotSharp/Views/FarmingUc.cs | 3 +-- TravBotSharp/Views/GeneralUc.cs | 5 +++-- TravBotSharp/Views/HeroUc.cs | 4 ++-- TravBotSharp/Views/OverviewTroopsUc.cs | 2 +- TravBotSharp/Views/OverviewUc.cs | 2 +- TravBotSharp/Views/VillageViews/AttackUc.cs | 4 +--- TravBotSharp/Views/VillageViews/BuildUc.cs | 1 - TravBotSharp/Views/VillageViews/FarmingNonGoldUc.cs | 3 +-- TravBotSharp/Views/VillageViews/TroopsUc.cs | 2 +- TravBotSharp/Views/VillagesUc.cs | 1 - 63 files changed, 74 insertions(+), 77 deletions(-) rename TbsCore/Tasks/{Farm => Farming}/AddFarm.cs (98%) rename TbsCore/Tasks/{Farm => Farming}/AttackOasis.cs (99%) rename TbsCore/Tasks/{Farm => Farming}/ImproveTroop.cs (99%) rename TbsCore/Tasks/{Farm => Farming}/ReadFarmScoutReport.cs (98%) rename TbsCore/Tasks/{Farm => Farming}/ResearchTroop.cs (98%) rename TbsCore/Tasks/{Farm => Farming}/ScoutPlayer.cs (96%) rename TbsCore/Tasks/{Farm => Farming}/SendDeff.cs (98%) rename TbsCore/Tasks/{Farm => Farming}/SendFLs.cs (96%) rename TbsCore/Tasks/{Farm => Farming}/SendFarmlist.cs (99%) rename TbsCore/Tasks/{Farm => Farming}/SendRaid.cs (98%) rename TbsCore/Tasks/{Farm => Farming}/SendReinforcementScouts.cs (96%) rename TbsCore/Tasks/{Farm => Farming}/SendTroops.cs (99%) rename TbsCore/Tasks/{Farm => Farming}/SendWaves.cs (99%) rename TbsCore/Tasks/{Farm => Farming}/TTWarsAddNatarsToFL.cs (96%) rename TbsCore/Tasks/{Farm => Farming}/TTWarsAddNatarsToNonGoldFL.cs (94%) rename TbsCore/Tasks/{Farm => Farming}/TrainExchangeRes.cs (98%) rename TbsCore/Tasks/{Farm => Farming}/TrainTroops.cs (99%) rename TbsCore/Tasks/{Farm => Farming}/TransitToMainAcc.cs (94%) rename TbsCore/Tasks/{Farm => Farming}/UpdateFarmLists.cs (99%) diff --git a/TbsCore/Core/PostLoadHelper.cs b/TbsCore/Core/PostLoadHelper.cs index 2caae124d..3403763a8 100644 --- a/TbsCore/Core/PostLoadHelper.cs +++ b/TbsCore/Core/PostLoadHelper.cs @@ -6,7 +6,7 @@ using TbsCore.Models.JsObjects; using TbsCore.Models.VillageModels; using TbsCore.Parsers; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Others; using TbsCore.Tasks.Sim; using TbsCore.Tasks.Update; using static TbsCore.Tasks.BotTask; diff --git a/TbsCore/Core/TaskExecutor.cs b/TbsCore/Core/TaskExecutor.cs index aa9ff9d65..155d4048f 100644 --- a/TbsCore/Core/TaskExecutor.cs +++ b/TbsCore/Core/TaskExecutor.cs @@ -8,7 +8,7 @@ using TbsCore.Parsers; using TbsCore.Tasks; using TbsCore.Tasks.Browser; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Others; using TbsCore.Tasks.Update; using static TbsCore.Tasks.BotTask; diff --git a/TbsCore/Core/TaskTimer.cs b/TbsCore/Core/TaskTimer.cs index dfb454ec1..7d737d32f 100644 --- a/TbsCore/Core/TaskTimer.cs +++ b/TbsCore/Core/TaskTimer.cs @@ -4,7 +4,7 @@ using System.Timers; using TbsCore.Helpers; using TbsCore.Tasks.Browser; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Others; using static TbsCore.Tasks.BotTask; namespace TbsCore.Models.AccModels diff --git a/TbsCore/Helpers/AccountHelper.cs b/TbsCore/Helpers/AccountHelper.cs index 8c4b6b781..70c996fa5 100644 --- a/TbsCore/Helpers/AccountHelper.cs +++ b/TbsCore/Helpers/AccountHelper.cs @@ -4,8 +4,7 @@ using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; using TbsCore.Tasks.Browser; -using TbsCore.Tasks.LowLevel; -using TbsCore.Tasks.SecondLevel; +using TbsCore.Tasks.Farming; using TbsCore.Tasks.Sim; using TbsCore.Tasks.Update; diff --git a/TbsCore/Helpers/HeroHelper.cs b/TbsCore/Helpers/HeroHelper.cs index c5e232dfb..716474e3b 100644 --- a/TbsCore/Helpers/HeroHelper.cs +++ b/TbsCore/Helpers/HeroHelper.cs @@ -5,7 +5,8 @@ using TbsCore.Models.MapModels; using TbsCore.Models.VillageModels; using TbsCore.Parsers; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Farming; +using TbsCore.Tasks.Others; using TbsCore.TravianData; using static TbsCore.Helpers.Classificator; diff --git a/TbsCore/Helpers/MarketHelper.cs b/TbsCore/Helpers/MarketHelper.cs index f06b3a31d..30ce653ba 100644 --- a/TbsCore/Helpers/MarketHelper.cs +++ b/TbsCore/Helpers/MarketHelper.cs @@ -10,7 +10,7 @@ using TbsCore.Parsers; using TbsCore.Tasks; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Others; namespace TbsCore.Helpers { @@ -183,7 +183,7 @@ public static async Task MarketSendResource(Account acc, long[] resour // Error "Abuse! You have not enough resources." is displayed. } //get duration of transit - // Class destination when ok. + // Class destination when ok. var dur = durNode.Descendants("td").ToList()[3].InnerText.Replace("\t", "").Replace("\n", ""); diff --git a/TbsCore/Helpers/ResSpendingHelper.cs b/TbsCore/Helpers/ResSpendingHelper.cs index 618cc9f5a..45e20704a 100644 --- a/TbsCore/Helpers/ResSpendingHelper.cs +++ b/TbsCore/Helpers/ResSpendingHelper.cs @@ -6,7 +6,7 @@ using TbsCore.Models.Settings; using TbsCore.Models.VillageModels; using TbsCore.Tasks; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Farming; using TbsCore.Tasks.Sim; namespace TbsCore.Helpers diff --git a/TbsCore/Helpers/ResourcesHelper.cs b/TbsCore/Helpers/ResourcesHelper.cs index cb874e840..5a490628f 100644 --- a/TbsCore/Helpers/ResourcesHelper.cs +++ b/TbsCore/Helpers/ResourcesHelper.cs @@ -7,7 +7,7 @@ using TbsCore.Models.ResourceModels; using TbsCore.Models.VillageModels; using TbsCore.Tasks; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Others; using static TbsCore.Helpers.Classificator; namespace TbsCore.Helpers diff --git a/TbsCore/Helpers/TroopsHelper.cs b/TbsCore/Helpers/TroopsHelper.cs index 74f77f5d9..c31a05b27 100644 --- a/TbsCore/Helpers/TroopsHelper.cs +++ b/TbsCore/Helpers/TroopsHelper.cs @@ -5,7 +5,7 @@ using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; using TbsCore.Parsers; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Farming; using TbsCore.TravianData; using static TbsCore.Helpers.Classificator; diff --git a/TbsCore/Helpers/UpdateAccountObject.cs b/TbsCore/Helpers/UpdateAccountObject.cs index 339f09175..c776b3332 100644 --- a/TbsCore/Helpers/UpdateAccountObject.cs +++ b/TbsCore/Helpers/UpdateAccountObject.cs @@ -5,7 +5,7 @@ using TbsCore.Models.SideBarModels; using TbsCore.Models.VillageModels; using TbsCore.Parsers; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Others; using TbsCore.Tasks.Update; namespace TbsCore.Helpers diff --git a/TbsCore/Tasks/BotTaskTemplate.cs b/TbsCore/Tasks/BotTaskTemplate.cs index 2fe9bc382..8b8c48845 100644 --- a/TbsCore/Tasks/BotTaskTemplate.cs +++ b/TbsCore/Tasks/BotTaskTemplate.cs @@ -1,7 +1,7 @@ using System.Threading.Tasks; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks { public class BotTaskTemplate : BotTask { diff --git a/TbsCore/Tasks/Farm/AddFarm.cs b/TbsCore/Tasks/Farming/AddFarm.cs similarity index 98% rename from TbsCore/Tasks/Farm/AddFarm.cs rename to TbsCore/Tasks/Farming/AddFarm.cs index f9dab9fc1..dfe609cc0 100644 --- a/TbsCore/Tasks/Farm/AddFarm.cs +++ b/TbsCore/Tasks/Farming/AddFarm.cs @@ -3,7 +3,7 @@ using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Farming { public class AddFarm : BotTask { diff --git a/TbsCore/Tasks/Farm/AttackOasis.cs b/TbsCore/Tasks/Farming/AttackOasis.cs similarity index 99% rename from TbsCore/Tasks/Farm/AttackOasis.cs rename to TbsCore/Tasks/Farming/AttackOasis.cs index e2d53bcbd..cbe6bc196 100644 --- a/TbsCore/Tasks/Farm/AttackOasis.cs +++ b/TbsCore/Tasks/Farming/AttackOasis.cs @@ -10,7 +10,7 @@ using TbsCore.Models.VillageModels; using TbsCore.TravianData; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Farming { public class AttackOasis : SendTroops { diff --git a/TbsCore/Tasks/Farm/ImproveTroop.cs b/TbsCore/Tasks/Farming/ImproveTroop.cs similarity index 99% rename from TbsCore/Tasks/Farm/ImproveTroop.cs rename to TbsCore/Tasks/Farming/ImproveTroop.cs index 5a7e56b02..acef87639 100644 --- a/TbsCore/Tasks/Farm/ImproveTroop.cs +++ b/TbsCore/Tasks/Farming/ImproveTroop.cs @@ -8,7 +8,7 @@ using TbsCore.Models.VillageModels; using TbsCore.Parsers; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Farming { public class ImproveTroop : BotTask { diff --git a/TbsCore/Tasks/Farm/ReadFarmScoutReport.cs b/TbsCore/Tasks/Farming/ReadFarmScoutReport.cs similarity index 98% rename from TbsCore/Tasks/Farm/ReadFarmScoutReport.cs rename to TbsCore/Tasks/Farming/ReadFarmScoutReport.cs index b0074c8a7..5ef63288f 100644 --- a/TbsCore/Tasks/Farm/ReadFarmScoutReport.cs +++ b/TbsCore/Tasks/Farming/ReadFarmScoutReport.cs @@ -6,7 +6,7 @@ using TbsCore.Parsers; using static TbsCore.Helpers.Classificator; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Farming { /// /// Use in combination with ScoutPlayer.cs. It will first scout villages, read the reports and then potentially send raid attack @@ -17,6 +17,7 @@ public class ReadFarmScoutReport : BotTask /// Coordinates to read the scout report /// public Coordinates Coordinates { get; set; } + /// /// Minimal resources that have to be available to send raid /// diff --git a/TbsCore/Tasks/Farm/ResearchTroop.cs b/TbsCore/Tasks/Farming/ResearchTroop.cs similarity index 98% rename from TbsCore/Tasks/Farm/ResearchTroop.cs rename to TbsCore/Tasks/Farming/ResearchTroop.cs index f439b494c..db474c278 100644 --- a/TbsCore/Tasks/Farm/ResearchTroop.cs +++ b/TbsCore/Tasks/Farming/ResearchTroop.cs @@ -9,7 +9,7 @@ using static TbsCore.Helpers.Classificator; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Farming { public class ResearchTroop : BotTask { diff --git a/TbsCore/Tasks/Farm/ScoutPlayer.cs b/TbsCore/Tasks/Farming/ScoutPlayer.cs similarity index 96% rename from TbsCore/Tasks/Farm/ScoutPlayer.cs rename to TbsCore/Tasks/Farming/ScoutPlayer.cs index 785acbe3b..d617338bb 100644 --- a/TbsCore/Tasks/Farm/ScoutPlayer.cs +++ b/TbsCore/Tasks/Farming/ScoutPlayer.cs @@ -2,11 +2,10 @@ using System.Threading.Tasks; using TbsCore.Helpers; using TbsCore.Models.AccModels; -using TbsCore.Tasks.LowLevel; using TbsCore.Tasks.Update; using TbsCore.TravianData; -namespace TbsCore.Tasks.SecondLevel +namespace TbsCore.Tasks.Farming { public class ScoutPlayer : CheckProfile { diff --git a/TbsCore/Tasks/Farm/SendDeff.cs b/TbsCore/Tasks/Farming/SendDeff.cs similarity index 98% rename from TbsCore/Tasks/Farm/SendDeff.cs rename to TbsCore/Tasks/Farming/SendDeff.cs index ecba421f9..99a10606a 100644 --- a/TbsCore/Tasks/Farm/SendDeff.cs +++ b/TbsCore/Tasks/Farming/SendDeff.cs @@ -6,7 +6,7 @@ using TbsCore.Models.TroopsModels; using TbsCore.TravianData; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Farming { public class SendDeff : SendTroops { diff --git a/TbsCore/Tasks/Farm/SendFLs.cs b/TbsCore/Tasks/Farming/SendFLs.cs similarity index 96% rename from TbsCore/Tasks/Farm/SendFLs.cs rename to TbsCore/Tasks/Farming/SendFLs.cs index 676e6ef6d..81141e2d3 100644 --- a/TbsCore/Tasks/Farm/SendFLs.cs +++ b/TbsCore/Tasks/Farming/SendFLs.cs @@ -2,9 +2,8 @@ using System.Threading.Tasks; using TbsCore.Helpers; using TbsCore.Models.AccModels; -using TbsCore.Tasks.LowLevel; -namespace TbsCore.Tasks.SecondLevel +namespace TbsCore.Tasks.Farming { public class SendFLs : BotTask { diff --git a/TbsCore/Tasks/Farm/SendFarmlist.cs b/TbsCore/Tasks/Farming/SendFarmlist.cs similarity index 99% rename from TbsCore/Tasks/Farm/SendFarmlist.cs rename to TbsCore/Tasks/Farming/SendFarmlist.cs index eadf98c3a..11c02f507 100644 --- a/TbsCore/Tasks/Farm/SendFarmlist.cs +++ b/TbsCore/Tasks/Farming/SendFarmlist.cs @@ -10,7 +10,7 @@ using TbsCore.Parsers; using static TbsCore.Helpers.Classificator; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Farming { public class SendFarmlist : BotTask { diff --git a/TbsCore/Tasks/Farm/SendRaid.cs b/TbsCore/Tasks/Farming/SendRaid.cs similarity index 98% rename from TbsCore/Tasks/Farm/SendRaid.cs rename to TbsCore/Tasks/Farming/SendRaid.cs index d0f6c3dab..b983879e1 100644 --- a/TbsCore/Tasks/Farm/SendRaid.cs +++ b/TbsCore/Tasks/Farming/SendRaid.cs @@ -6,7 +6,7 @@ using TbsCore.Models.TroopsModels; using TbsCore.TravianData; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Farming { public class SendRaid : SendTroops { @@ -14,6 +14,7 @@ public class SendRaid : SendTroops /// Bot will only send enough troops to raid all resources availabe /// public long ResourcesAvailable { get; set; } + public Coordinates TargetVillage { get; set; } public override async Task Execute(Account acc) diff --git a/TbsCore/Tasks/Farm/SendReinforcementScouts.cs b/TbsCore/Tasks/Farming/SendReinforcementScouts.cs similarity index 96% rename from TbsCore/Tasks/Farm/SendReinforcementScouts.cs rename to TbsCore/Tasks/Farming/SendReinforcementScouts.cs index 95710c29e..130ccc18d 100644 --- a/TbsCore/Tasks/Farm/SendReinforcementScouts.cs +++ b/TbsCore/Tasks/Farming/SendReinforcementScouts.cs @@ -3,10 +3,9 @@ using TbsCore.Models.AccModels; using TbsCore.Models.SendTroopsModels; using TbsCore.Models.TroopsModels; -using TbsCore.Tasks.LowLevel; using TbsCore.TravianData; -namespace TbsCore.Tasks.SecondLevel +namespace TbsCore.Tasks.Farming { /// /// Send scouts to all your villages @@ -14,6 +13,7 @@ namespace TbsCore.Tasks.SecondLevel public class SendReinforcementScouts : SendTroops { public int Scouts { get; set; } + public override async Task Execute(Account acc) { if (Scouts == 0) return TaskRes.Executed; diff --git a/TbsCore/Tasks/Farm/SendTroops.cs b/TbsCore/Tasks/Farming/SendTroops.cs similarity index 99% rename from TbsCore/Tasks/Farm/SendTroops.cs rename to TbsCore/Tasks/Farming/SendTroops.cs index fd34d80c2..fbc8f698d 100644 --- a/TbsCore/Tasks/Farm/SendTroops.cs +++ b/TbsCore/Tasks/Farming/SendTroops.cs @@ -7,7 +7,7 @@ using TbsCore.Models.TroopsModels; using TbsCore.Parsers; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Farming { public class SendTroops : BotTask { diff --git a/TbsCore/Tasks/Farm/SendWaves.cs b/TbsCore/Tasks/Farming/SendWaves.cs similarity index 99% rename from TbsCore/Tasks/Farm/SendWaves.cs rename to TbsCore/Tasks/Farming/SendWaves.cs index b4bdadf5d..f93fec362 100644 --- a/TbsCore/Tasks/Farm/SendWaves.cs +++ b/TbsCore/Tasks/Farming/SendWaves.cs @@ -9,7 +9,7 @@ using TbsCore.Models.SendTroopsModels; using TbsCore.Parsers; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Farming { public class SendWaves : BotTask { diff --git a/TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs b/TbsCore/Tasks/Farming/TTWarsAddNatarsToFL.cs similarity index 96% rename from TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs rename to TbsCore/Tasks/Farming/TTWarsAddNatarsToFL.cs index f25e40587..f2a9032d3 100644 --- a/TbsCore/Tasks/Farm/TTWarsAddNatarsToFL.cs +++ b/TbsCore/Tasks/Farming/TTWarsAddNatarsToFL.cs @@ -3,10 +3,9 @@ using System.Threading.Tasks; using TbsCore.Models.AccModels; using TbsCore.Models.TroopsModels; -using TbsCore.Tasks.LowLevel; using TbsCore.Tasks.Update; -namespace TbsCore.Tasks.SecondLevel +namespace TbsCore.Tasks.Farming { public class TTWarsAddNatarsToFL : CheckProfile { diff --git a/TbsCore/Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs b/TbsCore/Tasks/Farming/TTWarsAddNatarsToNonGoldFL.cs similarity index 94% rename from TbsCore/Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs rename to TbsCore/Tasks/Farming/TTWarsAddNatarsToNonGoldFL.cs index bc77ea9db..43bae1039 100644 --- a/TbsCore/Tasks/Farm/TTWarsAddNatarsToNonGoldFL.cs +++ b/TbsCore/Tasks/Farming/TTWarsAddNatarsToNonGoldFL.cs @@ -1,10 +1,9 @@ using System.Linq; using System.Threading.Tasks; using TbsCore.Models.AccModels; -using TbsCore.Tasks.LowLevel; using TbsCore.Tasks.Update; -namespace TbsCore.Tasks.SecondLevel +namespace TbsCore.Tasks.Farming { public class TTWarsAddNatarsToNonGoldFL : CheckProfile { diff --git a/TbsCore/Tasks/Farm/TrainExchangeRes.cs b/TbsCore/Tasks/Farming/TrainExchangeRes.cs similarity index 98% rename from TbsCore/Tasks/Farm/TrainExchangeRes.cs rename to TbsCore/Tasks/Farming/TrainExchangeRes.cs index 2a5b82aff..8c37f9ba6 100644 --- a/TbsCore/Tasks/Farm/TrainExchangeRes.cs +++ b/TbsCore/Tasks/Farming/TrainExchangeRes.cs @@ -4,7 +4,7 @@ using TbsCore.Models.AccModels; using TbsCore.TravianData; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Farming { public class TrainExchangeRes : BotTask { diff --git a/TbsCore/Tasks/Farm/TrainTroops.cs b/TbsCore/Tasks/Farming/TrainTroops.cs similarity index 99% rename from TbsCore/Tasks/Farm/TrainTroops.cs rename to TbsCore/Tasks/Farming/TrainTroops.cs index d39da2adc..462e327db 100644 --- a/TbsCore/Tasks/Farm/TrainTroops.cs +++ b/TbsCore/Tasks/Farming/TrainTroops.cs @@ -6,12 +6,13 @@ using TbsCore.Models.AccModels; using TbsCore.Models.ResourceModels; using TbsCore.Parsers; +using TbsCore.Tasks.Others; using TbsCore.Tasks.Update; using TbsCore.TravianData; using static TbsCore.Helpers.Classificator; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Farming { /// /// Old train troops task, only here because of high speed TTWars servers. diff --git a/TbsCore/Tasks/Farm/TransitToMainAcc.cs b/TbsCore/Tasks/Farming/TransitToMainAcc.cs similarity index 94% rename from TbsCore/Tasks/Farm/TransitToMainAcc.cs rename to TbsCore/Tasks/Farming/TransitToMainAcc.cs index e36453253..63f540f84 100644 --- a/TbsCore/Tasks/Farm/TransitToMainAcc.cs +++ b/TbsCore/Tasks/Farming/TransitToMainAcc.cs @@ -3,8 +3,9 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.MapModels; +using TbsCore.Tasks.Others; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Farming { /// /// Used on TTWars to constantly send resources to your main account diff --git a/TbsCore/Tasks/Farm/UpdateFarmLists.cs b/TbsCore/Tasks/Farming/UpdateFarmLists.cs similarity index 99% rename from TbsCore/Tasks/Farm/UpdateFarmLists.cs rename to TbsCore/Tasks/Farming/UpdateFarmLists.cs index 980a2c82d..d468bd7a6 100644 --- a/TbsCore/Tasks/Farm/UpdateFarmLists.cs +++ b/TbsCore/Tasks/Farming/UpdateFarmLists.cs @@ -9,7 +9,7 @@ using TbsCore.Parsers; using static TbsCore.Helpers.Classificator; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Farming { public class UpdateFarmLists : BotTask { diff --git a/TbsCore/Tasks/Others/ChangeVillageName.cs b/TbsCore/Tasks/Others/ChangeVillageName.cs index da54990c2..5867cbf55 100644 --- a/TbsCore/Tasks/Others/ChangeVillageName.cs +++ b/TbsCore/Tasks/Others/ChangeVillageName.cs @@ -5,7 +5,7 @@ using TbsCore.Models.AccModels; using static TbsCore.Helpers.Classificator; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class ChangeVillageName : BotTask { diff --git a/TbsCore/Tasks/Others/DonateAllyBonus.cs b/TbsCore/Tasks/Others/DonateAllyBonus.cs index 7e2dc88c7..947dfe2c2 100644 --- a/TbsCore/Tasks/Others/DonateAllyBonus.cs +++ b/TbsCore/Tasks/Others/DonateAllyBonus.cs @@ -3,7 +3,7 @@ using TbsCore.Models.AccModels; using TbsCore.Models.ResourceModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class DonateAllyBonus : BotTask { diff --git a/TbsCore/Tasks/Others/EditPreferences.cs b/TbsCore/Tasks/Others/EditPreferences.cs index 5f0b190c8..7a4772c4c 100644 --- a/TbsCore/Tasks/Others/EditPreferences.cs +++ b/TbsCore/Tasks/Others/EditPreferences.cs @@ -3,7 +3,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class EditPreferences : BotTask { diff --git a/TbsCore/Tasks/Others/HeroEquip.cs b/TbsCore/Tasks/Others/HeroEquip.cs index 89aa92f72..25747b71a 100644 --- a/TbsCore/Tasks/Others/HeroEquip.cs +++ b/TbsCore/Tasks/Others/HeroEquip.cs @@ -8,7 +8,7 @@ using static TbsCore.Helpers.Classificator; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class HeroEquip : BotTask { diff --git a/TbsCore/Tasks/Others/HeroSetPoints.cs b/TbsCore/Tasks/Others/HeroSetPoints.cs index b03e3bae1..09d200bf1 100644 --- a/TbsCore/Tasks/Others/HeroSetPoints.cs +++ b/TbsCore/Tasks/Others/HeroSetPoints.cs @@ -3,7 +3,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class HeroSetPoints : BotTask { diff --git a/TbsCore/Tasks/Others/LoginTask.cs b/TbsCore/Tasks/Others/LoginTask.cs index d2fd1ebbb..12d709647 100644 --- a/TbsCore/Tasks/Others/LoginTask.cs +++ b/TbsCore/Tasks/Others/LoginTask.cs @@ -5,7 +5,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class LoginTask : BotTask { diff --git a/TbsCore/Tasks/Others/RandomTask.cs b/TbsCore/Tasks/Others/RandomTask.cs index 3903a7e6e..850146443 100644 --- a/TbsCore/Tasks/Others/RandomTask.cs +++ b/TbsCore/Tasks/Others/RandomTask.cs @@ -2,7 +2,7 @@ using System.Threading.Tasks; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { /// /// Just a random navigation event - to make bot less suspicious to Travian. diff --git a/TbsCore/Tasks/Others/ReviveHero.cs b/TbsCore/Tasks/Others/ReviveHero.cs index b4f9514e0..51a8bcea2 100644 --- a/TbsCore/Tasks/Others/ReviveHero.cs +++ b/TbsCore/Tasks/Others/ReviveHero.cs @@ -4,7 +4,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class ReviveHero : BotTask { diff --git a/TbsCore/Tasks/Others/SellOnAuctions.cs b/TbsCore/Tasks/Others/SellOnAuctions.cs index a3ded93e7..6946f44ca 100644 --- a/TbsCore/Tasks/Others/SellOnAuctions.cs +++ b/TbsCore/Tasks/Others/SellOnAuctions.cs @@ -7,7 +7,7 @@ using TbsCore.Parsers; using static TbsCore.Helpers.Classificator; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class SellOnAuctions : BotTask { diff --git a/TbsCore/Tasks/Others/SendResFillTroops.cs b/TbsCore/Tasks/Others/SendResFillTroops.cs index 82c8bb0b9..c3278b2c2 100644 --- a/TbsCore/Tasks/Others/SendResFillTroops.cs +++ b/TbsCore/Tasks/Others/SendResFillTroops.cs @@ -4,9 +4,10 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; +using TbsCore.Tasks.Farming; using TbsCore.TravianData; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { /// /// Sends resources from main village to target village so it can fill up the troops to above X hours diff --git a/TbsCore/Tasks/Others/SendResToMain.cs b/TbsCore/Tasks/Others/SendResToMain.cs index 3f9711d53..8534a04aa 100644 --- a/TbsCore/Tasks/Others/SendResToMain.cs +++ b/TbsCore/Tasks/Others/SendResToMain.cs @@ -4,7 +4,7 @@ using TbsCore.Models.AccModels; using TbsCore.Models.Settings; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { /// /// Send all resources above X% to main village. diff --git a/TbsCore/Tasks/Others/SendResources.cs b/TbsCore/Tasks/Others/SendResources.cs index 3533f5221..9c74ef264 100644 --- a/TbsCore/Tasks/Others/SendResources.cs +++ b/TbsCore/Tasks/Others/SendResources.cs @@ -6,7 +6,7 @@ using TbsCore.Models.MapModels; using TbsCore.Models.ResourceModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class SendResources : BotTask { diff --git a/TbsCore/Tasks/Others/SetCapital.cs b/TbsCore/Tasks/Others/SetCapital.cs index b4758845a..406a02939 100644 --- a/TbsCore/Tasks/Others/SetCapital.cs +++ b/TbsCore/Tasks/Others/SetCapital.cs @@ -3,7 +3,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class SetCapital : BotTask { diff --git a/TbsCore/Tasks/Others/StartAdventure.cs b/TbsCore/Tasks/Others/StartAdventure.cs index 85dea16a6..cfdc96fab 100644 --- a/TbsCore/Tasks/Others/StartAdventure.cs +++ b/TbsCore/Tasks/Others/StartAdventure.cs @@ -5,7 +5,7 @@ using TbsCore.Models.AccModels; using TbsCore.Parsers; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class StartAdventure : BotTask { diff --git a/TbsCore/Tasks/Others/TTWarsBuyAdventure.cs b/TbsCore/Tasks/Others/TTWarsBuyAdventure.cs index f1640da24..d0cb913e0 100644 --- a/TbsCore/Tasks/Others/TTWarsBuyAdventure.cs +++ b/TbsCore/Tasks/Others/TTWarsBuyAdventure.cs @@ -2,7 +2,7 @@ using System.Threading.Tasks; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class TTWarsBuyAdventure : BotTask { diff --git a/TbsCore/Tasks/Others/TTWarsExpandStorage.cs b/TbsCore/Tasks/Others/TTWarsExpandStorage.cs index 44a7d4401..c52c5c51b 100644 --- a/TbsCore/Tasks/Others/TTWarsExpandStorage.cs +++ b/TbsCore/Tasks/Others/TTWarsExpandStorage.cs @@ -4,7 +4,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class TTWarsExpandStorage : BotTask { diff --git a/TbsCore/Tasks/Others/TTWarsGetAnimals.cs b/TbsCore/Tasks/Others/TTWarsGetAnimals.cs index 766028db2..687cdca5b 100644 --- a/TbsCore/Tasks/Others/TTWarsGetAnimals.cs +++ b/TbsCore/Tasks/Others/TTWarsGetAnimals.cs @@ -4,7 +4,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class TTWarsGetAnimals : BotTask { diff --git a/TbsCore/Tasks/Others/TTWarsGetRes.cs b/TbsCore/Tasks/Others/TTWarsGetRes.cs index 51f4a2332..cd759f64b 100644 --- a/TbsCore/Tasks/Others/TTWarsGetRes.cs +++ b/TbsCore/Tasks/Others/TTWarsGetRes.cs @@ -3,8 +3,9 @@ using System.Threading.Tasks; using TbsCore.Helpers; using TbsCore.Models.AccModels; +using TbsCore.Tasks.Farming; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { public class TTWarsGetRes : BotTask { diff --git a/TbsCore/Tasks/Others/TTWarsPlusAndBoost.cs b/TbsCore/Tasks/Others/TTWarsPlusAndBoost.cs index 62b4704d3..4cf33d51b 100644 --- a/TbsCore/Tasks/Others/TTWarsPlusAndBoost.cs +++ b/TbsCore/Tasks/Others/TTWarsPlusAndBoost.cs @@ -3,7 +3,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; -namespace TbsCore.Tasks.LowLevel +namespace TbsCore.Tasks.Others { //since "extend automatically" doesn't work on TTWars, this task will automatically prolong plus account / +25% resource boost public class TTWarsPlusAndBoost : BotTask diff --git a/TbsCore/Tasks/Update/CheckAttacks.cs b/TbsCore/Tasks/Update/CheckAttacks.cs index 3aee3623f..198aa043e 100644 --- a/TbsCore/Tasks/Update/CheckAttacks.cs +++ b/TbsCore/Tasks/Update/CheckAttacks.cs @@ -8,7 +8,7 @@ using TbsCore.Models.SendTroopsModels; using TbsCore.Models.VillageModels; using TbsCore.Parsers; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Others; namespace TbsCore.Tasks.Update { diff --git a/TbsCore/Tasks/Update/HeroUpdateInfo.cs b/TbsCore/Tasks/Update/HeroUpdateInfo.cs index f52a854d5..1e1bb0162 100644 --- a/TbsCore/Tasks/Update/HeroUpdateInfo.cs +++ b/TbsCore/Tasks/Update/HeroUpdateInfo.cs @@ -2,7 +2,7 @@ using System.Threading.Tasks; using TbsCore.Helpers; using TbsCore.Models.AccModels; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Others; using static TbsCore.Helpers.Classificator; namespace TbsCore.Tasks.Update diff --git a/TbsCoreTest/ResSpendingTest.cs b/TbsCoreTest/ResSpendingTest.cs index f824d51fd..290160a02 100644 --- a/TbsCoreTest/ResSpendingTest.cs +++ b/TbsCoreTest/ResSpendingTest.cs @@ -2,7 +2,7 @@ using TbsCore.Models.ResourceModels; using TbsCore.Models.Settings; using TbsCore.Models.VillageModels; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Farming; using TbsCore.Tasks.Sim; using TbsCoreTest.Factories; using Xunit; diff --git a/TravBotSharp/Views/DeffendingUc.cs b/TravBotSharp/Views/DeffendingUc.cs index 37bc6c414..678f4ca62 100644 --- a/TravBotSharp/Views/DeffendingUc.cs +++ b/TravBotSharp/Views/DeffendingUc.cs @@ -4,8 +4,8 @@ using System.Windows.Forms; using TbsCore.Models.SendTroopsModels; using TbsCore.Models.VillageModels; - -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Farming; +using TbsCore.Tasks.Others; using TravBotSharp.Interfaces; using XPTable.Editors; using XPTable.Models; diff --git a/TravBotSharp/Views/FarmingUc.cs b/TravBotSharp/Views/FarmingUc.cs index e6a21de20..1bef8454d 100644 --- a/TravBotSharp/Views/FarmingUc.cs +++ b/TravBotSharp/Views/FarmingUc.cs @@ -5,8 +5,7 @@ using TbsCore.Helpers; using TbsCore.Models.MapModels; using TbsCore.Models.TroopsModels; -using TbsCore.Tasks.LowLevel; -using TbsCore.Tasks.SecondLevel; +using TbsCore.Tasks.Farming; using TravBotSharp.Interfaces; namespace TravBotSharp.Views diff --git a/TravBotSharp/Views/GeneralUc.cs b/TravBotSharp/Views/GeneralUc.cs index a86f14894..6a4aa067c 100644 --- a/TravBotSharp/Views/GeneralUc.cs +++ b/TravBotSharp/Views/GeneralUc.cs @@ -8,7 +8,8 @@ using TbsCore.Models.AccModels; using TbsCore.Models.Settings; using TbsCore.Tasks.Browser; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Farming; +using TbsCore.Tasks.Others; using TravBotSharp.Forms; using TravBotSharp.Interfaces; @@ -192,7 +193,7 @@ private void button2_Click(object sender, EventArgs e) numericUpDown5.Value = 0; if (expandTimes != 0) { - acc.Tasks.Add(new TTWarsExpandStorage() { ExecuteAt = DateTime.Now, Times = expandTimes }, true); + acc.Tasks.Add(task: new TTWarsExpandStorage() { ExecuteAt = DateTime.Now, Times = expandTimes }, true); } else if (seconds != 0) { diff --git a/TravBotSharp/Views/HeroUc.cs b/TravBotSharp/Views/HeroUc.cs index 98f3ab329..29253bc51 100644 --- a/TravBotSharp/Views/HeroUc.cs +++ b/TravBotSharp/Views/HeroUc.cs @@ -3,7 +3,7 @@ using System.Windows.Forms; using TbsCore.Helpers; using TbsCore.Models.AccModels; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Others; using TbsCore.Tasks.Update; using TravBotSharp.Forms.Hero; using TravBotSharp.Interfaces; @@ -278,7 +278,7 @@ private void autoAuction_CheckedChanged(object sender, EventArgs e) { var acc = GetSelectedAcc(); acc.Hero.Settings.AutoAuction = autoAuction.Checked; - var task = acc.Tasks.FindTask(typeof(SellOnAuctions)); + TbsCore.Tasks.BotTask task = acc.Tasks.FindTask(typeof(SellOnAuctions)); if (autoAuction.Checked) { if (task == null) diff --git a/TravBotSharp/Views/OverviewTroopsUc.cs b/TravBotSharp/Views/OverviewTroopsUc.cs index 6fae9d2ae..14493b1e2 100644 --- a/TravBotSharp/Views/OverviewTroopsUc.cs +++ b/TravBotSharp/Views/OverviewTroopsUc.cs @@ -4,7 +4,7 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Others; using TbsCore.TravianData; using TravBotSharp.Interfaces; using XPTable.Editors; diff --git a/TravBotSharp/Views/OverviewUc.cs b/TravBotSharp/Views/OverviewUc.cs index c7992a3b7..62de2417f 100644 --- a/TravBotSharp/Views/OverviewUc.cs +++ b/TravBotSharp/Views/OverviewUc.cs @@ -4,7 +4,7 @@ using TbsCore.Helpers; using TbsCore.Models.Settings; using TbsCore.Models.VillageModels; -using TbsCore.Tasks.LowLevel; +using TbsCore.Tasks.Others; using TravBotSharp.Interfaces; using XPTable.Editors; using XPTable.Models; diff --git a/TravBotSharp/Views/VillageViews/AttackUc.cs b/TravBotSharp/Views/VillageViews/AttackUc.cs index bf842b7a1..b8450565a 100644 --- a/TravBotSharp/Views/VillageViews/AttackUc.cs +++ b/TravBotSharp/Views/VillageViews/AttackUc.cs @@ -5,8 +5,7 @@ using TbsCore.Helpers; using TbsCore.Models.SendTroopsModels; using TbsCore.Models.VillageModels; -using TbsCore.Tasks.LowLevel; -using TbsCore.Tasks.SecondLevel; +using TbsCore.Tasks.Farming; using TbsCore.TravianData; using TravBotSharp.Interfaces; @@ -227,7 +226,6 @@ private void oasisMinTroops_ValueChanged(object sender, EventArgs e) => #endregion Oasis farming callbacks - // Scout player private void button3_Click_1(object sender, EventArgs e) { diff --git a/TravBotSharp/Views/VillageViews/BuildUc.cs b/TravBotSharp/Views/VillageViews/BuildUc.cs index 0c4e443db..fcf6f2ddf 100644 --- a/TravBotSharp/Views/VillageViews/BuildUc.cs +++ b/TravBotSharp/Views/VillageViews/BuildUc.cs @@ -8,7 +8,6 @@ using TbsCore.Models.BuildingModels; using TbsCore.Models.VillageModels; using TbsCore.Tasks; -using TbsCore.Tasks.LowLevel; using TbsCore.Tasks.Sim; using TbsCore.Tasks.Update; using TravBotSharp.Interfaces; diff --git a/TravBotSharp/Views/VillageViews/FarmingNonGoldUc.cs b/TravBotSharp/Views/VillageViews/FarmingNonGoldUc.cs index 847be546a..ad14d8190 100644 --- a/TravBotSharp/Views/VillageViews/FarmingNonGoldUc.cs +++ b/TravBotSharp/Views/VillageViews/FarmingNonGoldUc.cs @@ -7,8 +7,7 @@ using TbsCore.Models.MapModels; using TbsCore.Models.SendTroopsModels; using TbsCore.Models.VillageModels; -using TbsCore.Tasks.LowLevel; -using TbsCore.Tasks.SecondLevel; +using TbsCore.Tasks.Farming; using TravBotSharp.Forms; using TravBotSharp.Interfaces; diff --git a/TravBotSharp/Views/VillageViews/TroopsUc.cs b/TravBotSharp/Views/VillageViews/TroopsUc.cs index 7f8a23ac5..f4d3b28a6 100644 --- a/TravBotSharp/Views/VillageViews/TroopsUc.cs +++ b/TravBotSharp/Views/VillageViews/TroopsUc.cs @@ -1,7 +1,7 @@ using System; using System.Collections.Generic; using TbsCore.Helpers; -using TbsCore.Tasks.SecondLevel; +using TbsCore.Tasks.Farming; using TravBotSharp.Interfaces; namespace TravBotSharp.Views diff --git a/TravBotSharp/Views/VillagesUc.cs b/TravBotSharp/Views/VillagesUc.cs index 9f4639178..c11211bae 100644 --- a/TravBotSharp/Views/VillagesUc.cs +++ b/TravBotSharp/Views/VillagesUc.cs @@ -6,7 +6,6 @@ using TbsCore.Helpers; using TbsCore.Models.AccModels; using TbsCore.Models.VillageModels; -using TbsCore.Tasks.LowLevel; using TbsCore.Tasks.Update; using TravBotSharp.Interfaces; From a0d326f24741c821a97a27df72fac7ab6f34d9d4 Mon Sep 17 00:00:00 2001 From: VINAGHOST Date: Fri, 29 Apr 2022 21:53:50 +0700 Subject: [PATCH 16/16] fix after start adventure click on switch village cause method not allowed --- TbsCore/Tasks/Others/StartAdventure.cs | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/TbsCore/Tasks/Others/StartAdventure.cs b/TbsCore/Tasks/Others/StartAdventure.cs index cfdc96fab..c046ddf44 100644 --- a/TbsCore/Tasks/Others/StartAdventure.cs +++ b/TbsCore/Tasks/Others/StartAdventure.cs @@ -64,6 +64,15 @@ public override async Task Execute(Account acc) break; } + if (DateTime.Now.Millisecond % 2 == 0) + { + await NavigationHelper.ToDorf1(acc); + } + else + { + await NavigationHelper.ToDorf2(acc); + } + return TaskRes.Executed; } }