Пример #1
0
        public async void RetrieveStaticChampionsTest()
        {
            ChampionListStatic champions = await creepScore.RetrieveChampionsData(CreepScore.Region.NA, StaticDataConstants.ChampData.All);

            ChampionStatic karma    = null;
            int            karmaKey = -1;

            foreach (KeyValuePair <string, string> champion in champions.keys)
            {
                if (champion.Value == "Karma")
                {
                    karmaKey = int.Parse(champion.Key);
                }
            }

            foreach (KeyValuePair <string, ChampionStatic> champion in champions.data)
            {
                if (champion.Key == "Karma")
                {
                    karma = champion.Value;
                    break;
                }
            }

            Assert.NotNull(karma);
            Assert.NotEqual(-1, karmaKey);
            Assert.Equal("Mage", karma.tags[0]);
            Assert.Equal(525, karma.stats.attackRange);
            Assert.Equal(7, karma.info.defense);
            Assert.Equal(43, karma.id);
        }
Пример #2
0
        private bool StoreRiotChampionData(ChampionListStatic champions)
        {
            bool success = false;

            try
            {
                string file = string.Format(@"{0}\Data\Champions\getChampions.{1}.bin", PublicStaticVariables.thisAppDataDir, champions.Version);
                string dir  = string.Format(@"{0}\Data\Champions", PublicStaticVariables.thisAppDataDir);

                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                using (FileStream fs = File.Open(file, FileMode.Create))
                    using (StreamWriter sw = new StreamWriter(fs))
                        using (JsonWriter jw = new JsonTextWriter(sw))
                        {
                            jw.Formatting = Formatting.Indented;

                            JsonSerializer serializer = new JsonSerializer();
                            serializer.Serialize(jw, champions);
                        }
                success = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                success = false;
            }
            return(success);
        }
Пример #3
0
        public void CrawlStaticData(Region region)
        {
            ChooseApiKey();
            ChampionListStatic champions = Task.Run(async() => { return(await api.StaticData.Champions.GetAllAsync("8.15.1")); }).Result;

            foreach (string k in champions.Champions.Keys)
            {
                ChampionStatic champ;
                champions.Champions.TryGetValue(k, out champ);
                MyChampion championToAdd = new MyChampion(champ);
                Champions.Add(championToAdd);
                Console.WriteLine(champ.Name + " added");
            }
            //ChooseApiKey();
            //ItemListStatic items = Task.Run(async () => { return await api.StaticData.Items.GetAllAsync("8.15.1"); }).Result;
            //foreach(int k in items.Items.Keys)
            //{
            //    ItemStatic item;
            //    items.Items.TryGetValue(k, out item);
            //    MyItem itemToAdd = new MyItem(item);
            //    itemToAdd.ItemId = k;
            //    Items.Add(itemToAdd);
            //    Console.WriteLine(item.Name +" added");
            //}
        }
        public void UpdateChampions()
        {
            UpdateStatus("Updating champions...");
            int    i    = 0;
            double prog = 0;

            using (StreamWriter str = new StreamWriter(ChampionsDirectory + @"\Champions.txt", true))
            {
                ChampionListStatic champs = StaticApi.GetChampions(_basereg, ChampionData.image);
                foreach (KeyValuePair <string, ChampionStatic> cs in champs.Champions)
                {
                    i++;
                    prog = (double)i / champs.Champions.Count;

                    UpdateProgress((int)(prog * 100));

                    if (!File.Exists(ChampionsDirectory + @"\" + cs.Key.ToString() + ".png"))
                    {
                        _wbc.DownloadFile(DataDragonRealm.Cdn + "/" + DataDragonRealm.Dd + "/img/champion/" + cs.Value.Image.Full, ChampionsDirectory + @"\" + cs.Key + ".png");
                        Console.WriteLine(cs.Key);
                        str.WriteLine(cs.Value.Id.ToString() + "," + cs.Key);
                        UpdateStatus("Champion " + cs.Key.ToString() + ".png");
                    }
                }
            }
            UpdateStatus("Champions Updated");
        }
Пример #5
0
        internal bool LoadRiotChampionData(string version)
        {
            bool success = false;

            try
            {
                string file;
                file = string.Format(@"{0}\Data\Champions\getChampions.{1}.bin", PublicStaticVariables.thisAppDataDir, version);


                string dir = string.Format(@"{0}\Data\Champions", PublicStaticVariables.thisAppDataDir);

                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                StreamReader re = new StreamReader(file);
                try
                {
                    JsonTextReader reader = new JsonTextReader(re);

                    JsonSerializer se         = new JsonSerializer();
                    object         parsedData = se.Deserialize(reader);

                    //Todo: this action should be timed
                    string jsonData = ChampionDataCorrections.RunCorrections(parsedData.ToString(), version);

                    champions = JsonConvert.DeserializeObject <ChampionListStatic>(jsonData);

                    champions = ChampionDataCorrections.RunStatCorrections(champions, version);


                    SortRiotChampionData(champions);

                    //TODO: temp test
                    //FindMissingParamsInSpells(champions);
                    //FindMissingBaseAttackSpeeds(champions);

                    success = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    success = false;
                }
                finally
                {
                    re.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                success = false;
            }
            return(success);
        }
Пример #6
0
        internal static ChampionListStatic RunStatCorrections(ChampionListStatic champions, string version)
        {
            //Load xml file with all Champion corrections
            XmlDocument xdcDocument = new XmlDocument();
            string      result      = string.Empty;

            using (Stream stream = typeof(ChampionDataCorrections).Assembly.GetManifestResourceStream("LeagueBuildStats.Classes.Champions" + ".ChampionCorrectionList.xml"))
            {
                using (StreamReader sr = new StreamReader(stream))
                {
                    result = sr.ReadToEnd();
                }
            }
            xdcDocument.LoadXml(result);

            XmlElement  xelRoot  = xdcDocument.DocumentElement;
            XmlNodeList xnlNodes = xelRoot.SelectNodes("/XML/CorrectionList[@Version]");

            //Loop through each Champion Correction List Node
            foreach (XmlNode xndNode in xnlNodes)
            {
                string xmlVersion = xndNode.Attributes["Version"].Value;
                //If the Version Attribute is Greater or Equal than use this Correction List Node
                if (CheckIfVersionIsGreaterEqual(version, xmlVersion))
                {
                    //Loop through each Ability Correction Node
                    foreach (XmlNode champNode in xndNode)
                    {
                        //Execute the updates
                        if (champNode.Name != "#comment")
                        {
                            try
                            {                             //<Ability champion="Thresh" button="e" buttonNum="2" key="f1" coeff="&quot;(num of souls)&quot;" link=""/>
                                string champion  = champNode.Attributes["champion"].Value;
                                string label     = champNode.Attributes["label"].Value;
                                string button    = champNode.Attributes["button"].Value;
                                string buttonNum = champNode.Attributes["buttonNum"].Value;
                                string key       = champNode.Attributes["key"].Value;
                                string coeff     = champNode.Attributes["coeff"].Value;
                                string link      = champNode.Attributes["link"].Value;

                                if (label == "stats")
                                {
                                    ChampionStatic championStatic = (champions.Champions[champion]);
                                    championStatic.Stats.AttackSpeedOffset = Convert.ToDouble(coeff);                                     //TODO: currently this only works with AttackSpeedOffset
                                }
                            }
                            catch (Exception ex)
                            {
                                MessageBox.Show(ex.ToString());
                            }
                        }
                    }
                }
            }
            return(champions);
        }
Пример #7
0
        private static ChampionStatic getChampion(int championId)
        {
            if (Champions == null)
            {
                Champions = StaticRiotApi.GetInstance(API_KEY).GetChampions(Region.na, ChampionData.all);
            }
            var champion = Champions.Champions.First(x => x.Value.Id == championId);

            return(champion.Value);
        }
Пример #8
0
        private void SortRiotChampionData(ChampionListStatic champions)
        {
            //Sort Champions by name
            championsOrder = new List <KeyValuePair <string, ChampionStatic> >();
            foreach (KeyValuePair <string, ChampionStatic> i in champions.Champions)
            {
                championsOrder.Add(new KeyValuePair <string, ChampionStatic>(i.Key, i.Value));
            }


            championsOrder.Sort((firstPair, nextPair) =>
            {
                return(firstPair.Key.CompareTo(nextPair.Key));
            }
                                );
            version = champions.Version;
        }
Пример #9
0
        public async void RetrieveStaticChampionsNoneTest()
        {
            ChampionListStatic champions = await creepScore.RetrieveChampionsData(CreepScore.Region.NA, StaticDataConstants.ChampData.None);

            ChampionStatic karma = null;

            foreach (KeyValuePair <string, ChampionStatic> champion in champions.data)
            {
                if (champion.Key == "Karma")
                {
                    karma = champion.Value;
                    break;
                }
            }

            Assert.Equal("the Enlightened One", karma.title);
        }
Пример #10
0
        public PartidaViewModel(Partida partida, ChampionListStatic campeoes, string ultimaVersao, string contaJogadorPrincipal, ItemListStatic itens, SummonerSpellListStatic spells)
        {
            var idTimeAliado = partida.Participants.First(y => y.ParticipantId == partida.ParticipantIdentities.First(k => k.Player.CurrentAccountId == contaJogadorPrincipal).ParticipantId).TeamId;

            var timeAliado = partida.Teams.First(x => x.TeamId == idTimeAliado);

            TimeAliado = new TimeViewModel(timeAliado);

            TimeAliado.Participantes = partida.Participants.Where(x => x.TeamId == idTimeAliado).Select(participante => new ParticipanteViewModel(partida, campeoes, ultimaVersao, "", itens, participante, spells, true)).ToList();


            var timeInimigo = partida.Teams.First(x => x.TeamId != idTimeAliado);

            TimeInimigo = new TimeViewModel(timeInimigo);

            TimeInimigo.Participantes = partida.Participants.Where(x => x.TeamId != idTimeAliado).Select(participante => new ParticipanteViewModel(partida, campeoes, ultimaVersao, "", itens, participante, spells, true)).ToList();
        }
Пример #11
0
        /// <summary>
        /// Gets a champion by champion id.
        /// </summary>
        public static ChampionStatic GetChampionById(this ChampionListStatic list, int id)
        {
            string key;

            if (!list.Keys.TryGetValue(id, out key))
            {
                return(null);
            }

            ChampionStatic champion;

            if (!list.Champions.TryGetValue(key, out champion))
            {
                return(null);
            }

            return(champion);
        }
Пример #12
0
        public bool DownloadListOfChampions(string inputVersion = null)
        {
            bool success = false;

            try
            {
                // Setup RiotApi
                var staticApi = StaticRiotApi.GetInstance(Resources.App.ApiKey);

                //Get all Items
                if (inputVersion == null)
                {
                    champions = staticApi.GetChampions(RiotSharp.Region.na, ChampionData.all);
                }
                else
                {
                    champions = staticApi.GetChampions(RiotSharp.Region.na, inputVersion, ChampionData.all);
                }

                StoreRiotChampionData(champions);

                //This action happens almost isntantly
                //SortRiotChampionData(champions); //Todo: this is disabled because LoadRiotChampionData() calls this.


                //TODO: for now i am loading the data in order to cause ChampionDataCorrections
                LoadRiotChampionData(champions.Version);


                success = true;
            }
            catch (Exception ex)
            {
                //TODO: correctly handle errors rather than this
                XtraMessageBox.Show(
                    string.Format(@"pvp.net/api/lol {1}
Note: This error may happen when selecting versions below 3.7.1", ex.Message), "League Build Stats - Notice");
                success = false;
            }


            return(success);
        }
Пример #13
0
 public void CollectBans(MatchSubmissionView view, Match riotMatch, ChampionListStatic champions,
                         SeasonInfoEntity seasonInfo, Guid divisionId, List <ChampionStatsEntity> championDetails)
 {
     foreach (var ban in riotMatch.Teams.SelectMany(x => x.Bans))
     {
         var riotChampion = champions.Keys[ban.ChampionId].ToLowerInvariant();
         try
         {
             var ourChampion        = GlobalVariables.ChampionDictionary[riotChampion];
             var bannedChampionStat =
                 CreateChampionStat(seasonInfo, divisionId, ourChampion.Id, view.ScheduleId);
             championDetails.Add(bannedChampionStat);
         }
         catch (Exception e)
         {
             _logger.LogError(e, $"Error getting banned champion: {riotChampion}");
         }
     }
 }
Пример #14
0
        private void FindMissingBaseAttackSpeeds(ChampionListStatic champions)
        {
            List <string> tempChampsMissingBaseAS = new List <string>();

            foreach (ChampionStatic thisChamp in champions.Champions.Values)
            {
                if (thisChamp.Stats.AttackSpeedOffset == 0.0)
                {
                    tempChampsMissingBaseAS.Add(thisChamp.Name);
                }
            }
            tempChampsMissingBaseAS.Add("done");
            string all = "";

            foreach (string s in tempChampsMissingBaseAS)
            {
                all += s + ",";
            }
            all += "done";
        }
Пример #15
0
        public async Task <IEnumerable <CompleteMatch> > GetCompleteHistoricalGamesAsync(DateTime?from, DateTime?to, Region region, string name)
        {
            if (ChampionList == default(ChampionListStatic))
            {
                ChampionList = await((StaticEndpointProvider)StaticEndpointProvider).GetEndpoint <IStaticChampionEndpoint>().GetAllAsync("10.8.1", Language.es_MX);
            }

            var matches         = (await GetHistoricalMatchListAsync(from, to, region, name)).Matches;
            var completeMatches = new List <CompleteMatch>();

            foreach (var match in matches)
            {
                completeMatches.Add(new CompleteMatch
                {
                    MatchReference = match,
                    Match          = await GetHistoricalMatchAsync(match.Region, match.GameId),
                    MatchTimeline  = await GetHistoricalMatchTimelineAsync(match.Region, match.GameId)
                });
            }

            return(completeMatches);
        }
Пример #16
0
        public JsonResult GetMatchInformation(int hours, int minutes, string date)
        {
            SummonerModel model = new SummonerModel();

            API riotApi = new API();


            DateTime parsedDate = DateTime.Parse(date);

            parsedDate = parsedDate.AddHours(hours);
            parsedDate = parsedDate.AddMinutes(minutes);

            List <long> gameIds = riotApi.GetUrfGames(parsedDate);

            if (gameIds.Count > 0)
            {
                var api       = RiotApi.GetInstance(riotApi.KeyOnly);
                var staticApi = StaticRiotApi.GetInstance(riotApi.KeyOnly);

                List <MatchDetail> matchDetails = new List <MatchDetail>();


                for (int i = 0; i < gameIds.Count; i++)
                {
                    matchDetails.Add(api.GetMatch(Region.euw, gameIds[i]));
                }

                ChampionListStatic championList = staticApi.GetChampions(Region.euw);


                ScoreCardCalculator scoreCalculator = new ScoreCardCalculator();

                model.ChampionScoreCards = scoreCalculator.CalculateChampionScores(matchDetails, riotApi.GetChampions());
            }

            return(Json(model, JsonRequestBehavior.AllowGet));
        }
Пример #17
0
        /// <summary>
        /// Constroi um participante
        /// </summary>
        /// <param name="partida">Partida atual</param>
        /// <param name="campeoes">Lista de campeoes</param>
        /// <param name="versao">Versao do jogo</param>
        /// <param name="contaId">AccoutId do participante, somente é utilizado se o participante for nulo</param>
        /// <param name="itens">Lista de itens do jogo</param>
        /// <param name="participant">Participante que vem da api</param>
        public ParticipanteViewModel(Partida partida, ChampionListStatic campeoes, string versao, string contaId, ItemListStatic itens, Participant participant, SummonerSpellListStatic feiticos, bool detalhado = false)
        {
            var participante = participant ?? partida.Participants.First(y => y.ParticipantId == partida.ParticipantIdentities.First(k => k.Player.CurrentAccountId == contaId).ParticipantId);

            var campeao =
                campeoes
                .Champions
                .FirstOrDefault(c => c.Value.Id == participante.ChampionId).Value;

            NomeCampeao = campeao.Name;

            UrlIconeCampeao = Util.RetornarIconeCampeao(versao, campeao);

            OuroAcumulado = participante.Stats.GoldEarned > 100 ? participante.Stats.GoldEarned.ToString("0,.#K") : participante.Stats.GoldEarned.ToString();

            KDA = $"{participante.Stats.Kills}/{participante.Stats.Deaths}/{participante.Stats.Assists}";

            Lane = Util.RetornarLaneFinalJogador(participante.Timeline.Lane, participante.Timeline.Role);

            NivelMaximoAtingido = participante.Stats.ChampLevel;

            Vitoria = participante.Stats.Winner;

            Data = partida.GameCreation.ToString("dd/MM/yyyy");

            ItensFinais = new List <Item>();

            ItensFinais.AdicionarItem(participante.Stats.Item0, itens, versao);
            ItensFinais.AdicionarItem(participante.Stats.Item1, itens, versao);
            ItensFinais.AdicionarItem(participante.Stats.Item2, itens, versao);
            ItensFinais.AdicionarItem(participante.Stats.Item3, itens, versao);
            ItensFinais.AdicionarItem(participante.Stats.Item4, itens, versao);
            ItensFinais.AdicionarItem(participante.Stats.Item5, itens, versao);
            var ward = Util.ObterItem(participante.Stats.Item6, itens, versao);

            if (ward != null)
            {
                Ward = ward;
            }

            GameId = partida.GameId;
            var jogador = partida.ParticipantIdentities.First(x => x.ParticipantId == participante.ParticipantId).Player;

            AccountId  = jogador.CurrentAccountId;
            SummonerId = jogador.SummonerId;

            if (detalhado)
            {
                NomeJogador = jogador.SummonerName;
                double ouroPorMinuto;

                try
                {
                    ouroPorMinuto = participante.Stats.GoldEarned / partida.GameDuration.TotalMinutes;
                }
                catch (Exception)
                {
                    ouroPorMinuto = 0;
                }

                OuroPorMinuto = ouroPorMinuto.ToString("0.#");

                Farm = participante.Stats.TotalMinionsKilled + participante.Stats.NeutralMinionsKilled;

                double farmPorMinuto;

                try
                {
                    farmPorMinuto = Convert.ToDouble(Farm) / partida.GameDuration.TotalMinutes;
                }
                catch (Exception)
                {
                    farmPorMinuto = 0;
                }

                FarmPorMinuto = farmPorMinuto.ToString("0.#");

                if (feiticos != null)
                {
                    Feitico1 = AdicionarFeitico(participante.Spell1Id, feiticos, versao);
                    Feitico2 = AdicionarFeitico(participante.Spell2Id, feiticos, versao);
                }
            }
        }
 public ChampionListStaticWrapper(ChampionListStatic champions, Language language, ChampionData championData)
 {
     ChampionListStatic = champions;
     Language           = language;
     ChampionData       = championData;
 }
Пример #19
0
 public void GetChampions()
 {
     Champions = Api.StaticData.Champions.GetAllAsync(LatestVersionString).Result;
 }
Пример #20
0
 public DataService(RiotApi api)
 {
     _riotApi = api;
     _champs  = _riotApi.StaticData.Champions.GetAllAsync("11.12.1").Result;
 }
Пример #21
0
        private async Task CollectStaticData(IServiceProvider serviceProvider)
        {
            var staticDataEndpoints     = serviceProvider.GetService <IStaticDataEndpoints>();
            var championRepository      = serviceProvider.GetService <IChampionStaticDataRepository>();
            var summonerSpellRepository = serviceProvider.GetService <ISummonerSpellStaticDataRepository>();
            var itemRepository          = serviceProvider.GetService <IItemStaticDataRepository>();
            var runeRepository          = serviceProvider.GetService <IRunesStaticDataRepository>();

            //Champions
            IEnumerable <Db_LccChampion> championsInDatabase = championRepository.GetAllChampions();

            if (championsInDatabase.Count() == 0)
            {
                ChampionListStatic championsListFromRiot = await staticDataEndpoints.Champion.GetChampionsAsync(Region.euw);

                foreach (ChampionStatic champion in championsListFromRiot.Champions.Values)
                {
                    championRepository.InsertChampionInformation(new Db_LccChampion()
                    {
                        ChampionId   = champion.Id,
                        ChampionName = champion.Name,
                        ImageFull    = champion.Image.Full
                    });
                }

                championRepository.Save();
            }

            //Items
            IEnumerable <Db_LccItem> itemsInDatabase = itemRepository.GetAllItems();

            if (itemsInDatabase.Count() == 0)
            {
                ItemListStatic itemsListFromRiot = await staticDataEndpoints.Item.GetItemsAsync(Region.euw);

                foreach (ItemStatic item in itemsListFromRiot.Items.Values)
                {
                    itemRepository.InsertItem(new Db_LccItem()
                    {
                        ItemId    = item.Id,
                        ItemName  = item.Name,
                        ImageFull = item.Image.Full
                    });
                }

                itemRepository.Save();
            }

            //SummonerSpells
            IEnumerable <Db_LccSummonerSpell> lccSummonerSpellInformation = summonerSpellRepository.GetAllSummonerSpells();

            if (lccSummonerSpellInformation.Count() == 0)
            {
                SummonerSpellListStatic summonerSpellListFromRiot = await staticDataEndpoints.SummonerSpell.GetSummonerSpellsAsync(Region.euw);

                foreach (SummonerSpellStatic summoner in summonerSpellListFromRiot.SummonerSpells.Values)
                {
                    summonerSpellRepository.InsertSummonerSpell(new Db_LccSummonerSpell()
                    {
                        SummonerSpellId   = summoner.Id,
                        SummonerSpellName = summoner.Name,
                        ImageFull         = summoner.Image.Full
                    });
                }

                summonerSpellRepository.Save();
            }

            //Runes
            IEnumerable <Db_LccRune> lccRuneInformation = runeRepository.GetAllRunes();

            if (lccRuneInformation.Count() == 0)
            {
                IList <RuneReforged> runeListFromRiot = await staticDataEndpoints.Rune.GetRunesReforgedAsync(Region.euw);

                foreach (RuneReforged rune in runeListFromRiot)
                {
                    runeRepository.InsertRune(new Db_LccRune()
                    {
                        RuneId       = rune.Id,
                        RuneName     = rune.Name,
                        RunePathName = rune.RunePathName,
                        Key          = rune.Key,
                        ShortDesc    = rune.ShortDesc,
                        LongDesc     = rune.LongDesc,
                        Icon         = rune.Icon
                    });
                }

                runeRepository.Save();
            }
        }
Пример #22
0
        private bool NeedUpdate()
        {
            if (!isoStorage.DirectoryExists(IMGCHAMPPATH) || !isoStorage.DirectoryExists(IMGSUMMSPELLPATH) || !isoStorage.DirectoryExists(IMGSUMMICON))
            {
                return true;
            }
            else
            {
                try
                {
                    // Get the list of all champions actualy in the live version of the game
                    this.listOfLiveChamp = staticApi.GetChampions(RiotSharp.Region.na, RiotSharp.StaticDataEndpoint.ChampionData.image);

                    // Get the list of all summoner spell actualy in the live version of the game
                    this.listOfLiveSummSpells = staticApi.GetSummonerSpells(RiotSharp.Region.na, SummonerSpellData.image);

                    if (listOfLiveChamp != null && listOfLiveSummSpells != null)
                    {
                        existingChampImg = isoStorage.DirectoryGetFiles(IMGCHAMPPATH + "*");

                        existingSummSpellImg = isoStorage.DirectoryGetFiles(IMGSUMMSPELLPATH + "*");

                        existingSummIconImg = isoStorage.DirectoryGetFiles(IMGSUMMICON + "*");

                        if ((existingChampImg.Count() + existingSummSpellImg.Count()) != (listOfLiveChamp.Champions.Count() + listOfLiveSummSpells.SummonerSpells.Count()))
                        {
                            return true;
                        }
                        else
                        {
                            if (existingSummIconImg.Count() == 0)
                            {
                                return true;
                            }
                            else
                            {
                                int id = Singleton.Instance.CurrentUser.SummonerIconID;

                                if (isoStorage.FileExists(IMGSUMMICON + ImageNameCreation(id.ToString())))
                                {
                                    return false;
                                }
                                else
                                {
                                    return true;
                                }
                            }
                        }
                    }
                    else
                    {
                        return true;
                    }
                }
                catch (Exception)
                {
                    return true;
                }
            }
        }
Пример #23
0
 public ChampionListStaticWrapper(ChampionListStatic champions, Language language, ChampionData championData)
 {
     ChampionListStatic = champions;
     Language = language;
     ChampionData = championData;
 }
Пример #24
0
 public ChampionListStaticWrapper(ChampionListStatic champions, Language language, string version)
 {
     ChampionListStatic = champions;
     Language           = language;
     Version            = version;
 }
Пример #25
0
 private static ChampionStatic getChampion(int championId)
 {
     if (Champions == null)
     {
         Champions = StaticRiotApi.GetInstance(API_KEY).GetChampions(Region.na, ChampionData.all);
     }
     var champion = Champions.Champions.First(x => x.Value.Id == championId);
     return champion.Value;
 }
Пример #26
0
        public async Task CollectPlayerMatchDetailsAsync(MatchSubmissionView view, Match riotMatch, ChampionListStatic champions, GameInfo gameInfo,
                                                         Dictionary <string, SummonerInfoEntity> registeredPlayers, TimeSpan gameDuration, SeasonInfoEntity seasonInfo,
                                                         Dictionary <MatchDetailKey, MatchDetailEntity> matchDictionary, List <MatchDetailContract> matchList, Guid divisionId,
                                                         List <ChampionStatsEntity> championDetails)
        {
            var blueTotalKills = riotMatch.Participants.Where(x => x.TeamId == 100).Sum(y => y.Stats.Kills);
            var redTotalKills  = riotMatch.Participants.Where(x => x.TeamId == 200).Sum(y => y.Stats.Kills);

            foreach (var participant in riotMatch.Participants)
            {
                //Get champion by Riot Api
                var riotChampion = champions.Keys[participant.ChampionId].ToLowerInvariant();
                //Get who played said champion and if they were blue side or not
                var gameInfoPlayer = gameInfo.PlayerName(riotChampion);

                //If the player listed doesn't match a champion, then we ignore it for purposes of stat tracking
                if (gameInfoPlayer == null)
                {
                    continue;
                }

                //Check to make sure the player is officially registered, if not, this will send a red flag
                registeredPlayers.TryGetValue(gameInfoPlayer.PlayerName.ToLowerInvariant(), out var registeredPlayer);
                if (registeredPlayer == null)
                {
                    var message = $"This player is not legal for a match as a player: {gameInfoPlayer.PlayerName}";
                    _logger.LogCritical(message);
                    const string to = "*****@*****.**";
                    await _emailService.SendEmailAsync(to, message,
                                                       $"Illegal player in match: {view.HomeTeamName} vs {view.AwayTeamName}");

                    throw new Exception(message);
                }

                var matchStat = CreatePlayerMatchStat(registeredPlayer, participant, gameDuration, seasonInfo);
                switch (participant.TeamId)
                {
                case 100:
                    matchStat.TotalTeamKills = (int)blueTotalKills;
                    break;

                case 200:
                    matchStat.TotalTeamKills = (int)redTotalKills;
                    break;
                }

                //will always create a new match detail
                var matchDetail = new MatchDetailEntity
                {
                    Id             = Guid.NewGuid(),
                    Game           = gameInfo.GameNum,
                    PlayerId       = registeredPlayer.Id,
                    PlayerStatsId  = matchStat.Id,
                    SeasonInfoId   = seasonInfo.Id,
                    TeamScheduleId = view.ScheduleId,
                    Winner         = participant.Stats.Winner
                };

                //per player
                var win         = participant.Stats.Winner;
                var loss        = !win;
                var ourChampion = GlobalVariables.ChampionDictionary[riotChampion];

                var pickedChampionStat = CreateChampionStat(matchStat, seasonInfo, divisionId, win, loss, ourChampion.Id, matchDetail.Id, view.ScheduleId);
                championDetails.Add(pickedChampionStat);

                //Add special achievements here
                var achievements = await AddSpecialAchievements(participant, ourChampion, registeredPlayer, seasonInfo.Id, riotMatch, view, gameInfo.GameNum);

                matchList.Add(new MatchDetailContract(gameInfoPlayer.IsBlue, matchDetail, matchStat, achievements));
            }
        }
Пример #27
0
        /// <summary>
        /// TEMP TESTER FUNCTION
        /// </summary>
        /// <param name="champions"></param>
        private void FindMissingParamsInSpells(ChampionListStatic champions)
        {
            List <string> tempMissingResource = new List <string>();
            List <string> links = new System.Collections.Generic.List <string>();

            foreach (ChampionStatic thisChamp in champions.Champions.Values)
            {
                foreach (ChampionSpellStatic champSpell in thisChamp.Spells)
                {
                    //Store unique Links
                    if (champSpell.Vars != null)
                    {
                        foreach (var coeff in champSpell.Vars)
                        {
                            if (coeff.Link != null)
                            {
                                if (!links.Contains(coeff.Link))
                                {
                                    links.Add(coeff.Link);
                                }
                            }
                        }
                    }



                    //Prepare Desc//
                    string sDescPrep = champSpell.Tooltip;


                    //Replace Ceoff markers
                    if (champSpell.Vars != null)
                    {
                        foreach (SpellVarsStatic spellVars in champSpell.Vars)
                        {
                            string sTarget      = "{{ " + spellVars.Key + " }}";
                            string sReplacement = "";
                            if (spellVars.Coeff != null)
                            {
                                var varsCoeff = (Newtonsoft.Json.Linq.JArray)spellVars.Coeff;
                                int index     = 0;
                                int icount    = varsCoeff.Count;
                                foreach (string sVar in varsCoeff)
                                {
                                    sReplacement += sVar;
                                    if ((index + 1) != icount)
                                    {
                                        sReplacement += "/";
                                    }
                                    index++;
                                }
                            }
                            sDescPrep = sDescPrep.Replace(sTarget, sReplacement);
                        }
                    }

                    //Replace effect markers
                    if (champSpell.EffectBurns != null)
                    {
                        int i = 0;
                        foreach (string sReplacement in champSpell.EffectBurns)
                        {
                            if (sReplacement != "")
                            {
                                string sTarget = "{{ e" + i + " }}";
                                sDescPrep = sDescPrep.Replace(sTarget, sReplacement);
                            }
                            i++;
                        }
                    }


                    //TODO: Check for missing params Uncomment lines below to reactivate
                    List <string> tempMissingParams = new List <string>();
                    if (sDescPrep.Contains("{{"))
                    {
                        MatchCollection matchList = Regex.Matches(sDescPrep, "{{ [^}}]+ }}");
                        var             list      = matchList.Cast <Match>().Select(match => match.Value).ToList();

                        foreach (string sMatch in list)
                        {
                            if (!tempMissingParams.Contains(sMatch))
                            {
                                tempMissingParams.Add(sMatch);
                            }
                        }


                        //MessageBox.Show("Champion is missing params!");
                        //using (System.IO.StreamWriter fileWrite = new System.IO.StreamWriter(string.Format(@"{0}\WriteLines3.txt", "E:\\VisualStudioProjects2013-Latest\\RiotSharp-LoLStats-Web\\RiotSharp-LoLStats-WinForm\\bin\\Debug"), true))
                        //{
                        //	fileWrite.WriteLine(string.Format(@" * Champion Name: {0} (ID: {1})", thisChamp.Name, thisChamp.Id));
                        //	string missingParams = "";
                        //	foreach (string sMissing in tempMissingParams)
                        //	{
                        //		missingParams += sMissing + " ";
                        //	}
                        //	fileWrite.WriteLine(string.Format(@"  * Ability Name: {0}", champSpell.Name));
                        //	fileWrite.WriteLine(string.Format(@"  * Ability Key: {0}", champSpell.Key));
                        //	fileWrite.WriteLine(string.Format(@"  * Params Missing from Tooltip: {0}", missingParams));
                        //	fileWrite.WriteLine(string.Format(@""));
                        //	fileWrite.WriteLine(string.Format(@""));
                        //}
                    }
                }
            }

            //using (System.IO.StreamWriter fileWrite = new System.IO.StreamWriter(string.Format(@"{0}\WriteLines3.txt", "E:\\VisualStudioProjects2013-Latest\\RiotSharp-LoLStats-Web\\RiotSharp-LoLStats-WinForm\\bin\\Debug"), true))
            //{
            //	foreach (string st in links)
            //	{
            //		fileWrite.WriteLine(st);
            //	}
            //}
            int d = 2;

            d++;
        }
Пример #28
0
        public JogadorPartidaAtual(EstatisticasJogador estatisticasJogador, CurrentGameParticipant participante, bool aliado, ChampionListStatic campeoes, string versao, bool jogadorPrincipal = false)
        {
            var campeao = campeoes
                          .Champions
                          .FirstOrDefault(c => c.Value.Id == participante.ChampionId).Value;

            decimal taxaVitoria = estatisticasJogador.CampeoesXTaxaVitoria?.FirstOrDefault(x => x.ID == participante.ChampionId)?.TaxaVitoria ?? 0;

            IconeCampeao  = Util.RetornarIconeCampeao(versao, campeao);
            Nome          = estatisticasJogador.Nome;
            Campeao       = campeao.Name;
            Divisao       = estatisticasJogador.Elo;
            ChanceVitoria = taxaVitoria;
            LanePrincipal = estatisticasJogador.Lanes?.OrderByDescending(x => x.PercentualUtilizacao).FirstOrDefault()?.Descricao ?? "Sem lane principal";
            ConfiabilidadePericulosidade = CalculaConfiabilidadePericulosidade(taxaVitoria, aliado);

            var idCampeaoPrincipal = estatisticasJogador.CampeoesXTaxaVitoria.OrderByDescending(x => x.PartidasTotais).FirstOrDefault()?.ID;

            if (idCampeaoPrincipal.HasValue)
            {
                CampeaoPrincipal = campeoes
                                   .Champions
                                   .FirstOrDefault(c => c.Value.Id == idCampeaoPrincipal).Value?.Name ?? "Sem campeão principal";
            }
            else
            {
                CampeaoPrincipal = "Sem campeão principal";
            }

            JogadorPrincipal = jogadorPrincipal;

            Participante = participante;

            TaxaPrimeiroBarao = estatisticasJogador.TaxaPrimeiroBarao;
            TaxaFirstBlood    = estatisticasJogador.TaxaFirstBlood;
        }