示例#1
0
        /* Extract to IFarmingStrategy
         * private IEnumerable<Planet> GetFarmsToScanForFleet()
         * {
         *
         * }
         */

        private void SendProbes(IEnumerable <Planet> farms)
        {
            Progress = "Sending probes";
            HttpRequestMessage req  = RequestBuilder.GetPage(PageType.Galaxy, PlanetId);
            ResponseContainer  resp = Client.IssueRequest(req);

            Coordinate self       = resp.GetParsedSingle <OgamePageInfo>().PlanetCoord;
            Coordinate selfPlanet = Coordinate.Create(self, CoordinateType.Planet);
            Coordinate selfMoon   = Coordinate.Create(self, CoordinateType.Moon);

            var farmList = farms.OrderBy(f => f.LocationId).ToList();

            int count        = farmList.Count;
            int retry        = 0;
            int failedInARow = 0;

            foreach (Planet farm in farmList)
            {
                if (farm.Coordinate == selfPlanet || farm.Coordinate == selfMoon)
                {
                    continue;
                }

                MinifleetResponse minifleet;
                retry = 0;
                do
                {
                    req       = RequestBuilder.GetMiniFleetSendMessage(MissionType.Espionage, farm.Coordinate, Strategy.ProbeCount, _token);
                    resp      = Client.IssueRequest(req);
                    minifleet = resp.GetParsedSingle <MinifleetResponse>();
                    _token    = minifleet.NewToken;

                    // If there are no probes (or error), wait for 5s, otherwise 1s
                    Thread.Sleep((minifleet.Response.Probes > 0 ? 1000 : 5000) + _sleepTime.Next(1000));
                    retry++;
                }while (!minifleet.Response.IsSuccess && retry < 5);

                if (minifleet.Response.IsSuccess)
                {
                    failedInARow = 0;
                }
                else
                {
                    Logger.Instance.Log(LogLevel.Error, $"Sending probes to {farm.Coordinate} failed, last error: {minifleet.Response.Message}");
                    if (++failedInARow == 3)
                    {
                        Logger.Instance.Log(LogLevel.Error, $"Failed to send probe {failedInARow} times in a row, aborting further scan");
                        break;
                    }
                }

                if (--count % 10 == 0 && count > 0)
                {
                    Logger.Instance.Log(LogLevel.Info, $"{count} remaining to scan...");
                }
            }
        }
示例#2
0
        private Resources Attack(IEnumerable <EspionageReport> messages)
        {
            Progress = "Attacking";
            //Check if the planet wasn't changed in the meantime (ie. by user action), we'd be sending cargos for a long trip
            ResponseContainer resp = Client.IssueRequest(RequestBuilder.GetPage(PageType.Fleet, PlanetId));
            OgamePageInfo     info = resp.GetParsedSingle <OgamePageInfo>();

            Resources totalPlunder = new Resources();

            foreach (var farm in Strategy.GetTargets(messages))
            {
                Thread.Sleep(3000 + _sleepTime.Next(2000));
                totalPlunder += farm.ExpectedPlunder;
                Logger.Instance.Log(LogLevel.Info, $"Attacking planet {farm.Destination} to plunder {farm.ExpectedPlunder}");

                SendFleetCommand attack = new SendFleetCommand()
                {
                    Mission     = farm.Mission,
                    Destination = farm.Destination,
                    PlanetId    = PlanetId,
                    Fleet       = farm.Fleet
                };
                attack.Run();
            }

            return(totalPlunder);
        }
示例#3
0
        protected override CommandQueueElement RunInternal()
        {
            using (Client.EnterPlanetExclusive(this))
            {
                // Make the initial request to get a token
                HttpRequestMessage req = Client.RequestBuilder.GetPage(PageType.Resources, PlanetId);
                ResponseContainer  res = AssistedIssue(req);

                OgamePageInfo info  = res.GetParsedSingle <OgamePageInfo>();
                string        token = info.OrderToken;

                // validate resources
                int currentBuildingLevel = res.GetParsed <DetectedBuilding>()
                                           .Where(b => b.Building == BuildingToBuild)
                                           .Select(b => b.Level)
                                           .FirstOrDefault();

                PlanetResources resources = res.GetParsedSingle <PlanetResources>();

                Resources cost = Building.Get(BuildingToBuild).Cost.ForLevel(currentBuildingLevel + 1);
                DetectedOngoingConstruction underConstruction = res.GetParsedSingle <DetectedOngoingConstruction>(false);

                if (underConstruction != null)
                {
                    Logger.Instance.Log(LogLevel.Debug, $"Building {underConstruction.Building} already under construction on planet {info.PlanetName}, will finish at {underConstruction.FinishingAt}");
                    return(Reschedule(underConstruction.FinishingAt));
                }
                else if (cost.Metal > resources.Resources.Metal || cost.Crystal > resources.Resources.Crystal || cost.Deuterium > resources.Resources.Deuterium)
                {
                    double maxTimeToGetEnoughResources = new double[] {
                        (cost.Metal - resources.Resources.Metal) / (resources.ProductionPerHour.Metal / 3600.0),
                        (cost.Crystal - resources.Resources.Crystal) / (resources.ProductionPerHour.Deuterium / 3600.0),
                        (cost.Deuterium - resources.Resources.Deuterium) / (resources.ProductionPerHour.Deuterium / 3600.0)
                    }.Max();
                    Logger.Instance.Log(LogLevel.Debug, $"Not enough resources! It would cost {cost} to build {BuildingToBuild} level {currentBuildingLevel + 1}, planet {info.PlanetName} only has {resources.Resources}; will have enough in {maxTimeToGetEnoughResources} seconds");
                    return(Reschedule(DateTimeOffset.Now.AddSeconds(maxTimeToGetEnoughResources)));
                }


                HttpRequestMessage buildReq = Client.RequestBuilder.GetBuildBuildingRequest(BuildingToBuild, token);
                AssistedIssue(buildReq);

                return(null);
            }
        }
示例#4
0
        private void PageChanged(ResponseContainer resp)
        {
            string minifleetToken = resp.GetParsedSingle <OgamePageInfo>(false)?.MiniFleetToken;

            if (minifleetToken != null)
            {
                _token = minifleetToken;
            }
        }
示例#5
0
        public override string Inject(string body, ResponseContainer response, string host, int port)
        {
            OgamePageInfo info = response.GetParsedSingle <OgamePageInfo>(false);

            foreach (IInject inject in _injects)
            {
                body = inject.Inject(info, body, response, host, port);
            }

            return(base.Inject(body, response, host, port));
        }
        public string Inject(OgamePageInfo info, string body, ResponseContainer response, string host, int port)
        {
            if (info?.Page != PageType.Fleet)
            {
                return(body);
            }

            int cargosNecessary = FleetComposition.ToTransport(response.GetParsedSingle <PlanetResources>().Resources).Ships[ShipType.LargeCargo];

            return(largeCargo.Replace(body, $@"$1<span onclick=""toggleMaxShips('#shipsChosen', 203,{cargosNecessary}); checkIntInput('#ship_203', 0, {cargosNecessary}); checkShips('shipsChosen'); event.stopPropagation(); return false;"" style='color: #aaa'>[{cargosNecessary}]</span> $2"));
        }
示例#7
0
        private void ClientOnOnResponseReceived(ResponseContainer responseContainer)
        {
            MessageCountObject count = responseContainer.GetParsedSingle <MessageCountObject>(false);

            if (count == null)
            {
                return;
            }

            _lastCount     = count;
            _lastCountTime = DateTime.UtcNow;
        }
示例#8
0
        private void ParseResponse(ResponseContainer response)
        {
            AuctionStatus status = response.GetParsedSingle <AuctionStatus>(false);

            switch (status?.MinutesRemaining ?? 10)
            {
            case 0:
                ExecutionInterval = status.NextIn.Add(TimeSpan.FromMinutes(1));
                break;

            case 5:
                ExecutionInterval = TimeSpan.FromMinutes(1);
                break;

            default:
                ExecutionInterval = TimeSpan.FromMinutes(2);
                break;
            }
            if (status != null)
            {
                Auction = status;
            }
            Restart();
        }
        public override IEnumerable <DataObject> ProcessInternal(ClientBase client, ResponseContainer container)
        {
            HtmlDocument doc     = container.ResponseHtml.Value;
            HtmlNode     infoBox = doc.DocumentNode.SelectSingleNode("//div[@id='info']");

            if (infoBox == null)
            {
                // Requirement for this parser
                yield break;
            }

            Coordinate coord = container.GetParsedSingle <OgamePageInfo>().PlanetCoord;

            string metBoxHtml = infoBox.SelectSingleNode(".//li[@id='metal_box']").GetAttributeValue("title", null).Split('|').Last();
            string cryBoxHtml = infoBox.SelectSingleNode(".//li[@id='crystal_box']").GetAttributeValue("title", null).Split('|').Last();
            string deuBoxHtml = infoBox.SelectSingleNode(".//li[@id='deuterium_box']").GetAttributeValue("title", null).Split('|').Last();
            string eneBoxHtml = infoBox.SelectSingleNode(".//li[@id='energy_box']").GetAttributeValue("title", null).Split('|').Last();

            HtmlDocument metBox = new HtmlDocument();

            metBox.LoadHtml(WebUtility.HtmlDecode(metBoxHtml));
            HtmlDocument cryBox = new HtmlDocument();

            cryBox.LoadHtml(WebUtility.HtmlDecode(cryBoxHtml));
            HtmlDocument deuBox = new HtmlDocument();

            deuBox.LoadHtml(WebUtility.HtmlDecode(deuBoxHtml));
            HtmlDocument eneBox = new HtmlDocument();

            eneBox.LoadHtml(WebUtility.HtmlDecode(eneBoxHtml));

            HtmlNodeCollection metTds = metBox.DocumentNode.SelectNodes("//td");
            HtmlNodeCollection cryTds = cryBox.DocumentNode.SelectNodes("//td");
            HtmlNodeCollection deuTds = deuBox.DocumentNode.SelectNodes("//td");
            HtmlNodeCollection eneTds = eneBox.DocumentNode.SelectNodes("//td");

            PlanetResources result = new PlanetResources();

            result.Coordinate = coord;
            result.Resources  = new Resources
            {
                Metal     = int.Parse(metTds[0].InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture),
                Crystal   = int.Parse(cryTds[0].InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture),
                Deuterium = int.Parse(deuTds[0].InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture),
                Energy    = int.Parse(eneTds[0].InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture)
            };

            result.Capacities = new Resources
            {
                Metal     = int.Parse(metTds[1].InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture),
                Crystal   = int.Parse(cryTds[1].InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture),
                Deuterium = int.Parse(deuTds[1].InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture),
                Energy    = int.Parse(eneTds[1].InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture)
            };

            result.ProductionPerHour = new Resources
            {
                Metal     = int.Parse(metTds[2].InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture),
                Crystal   = int.Parse(cryTds[2].InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture),
                Deuterium = int.Parse(deuTds[2].InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture),
                Energy    = int.Parse(eneTds[2].InnerText, NumberStyles.AllowThousands | NumberStyles.Integer, client.ServerCulture)
            };

            yield return(result);
        }