Пример #1
0
        public int GetInboundsResult(PlayerRating pg, PlayerRating sg, PlayerRating sf, PlayerRating pf, PlayerRating c, int j)
        {
            int result = j;

            if (result < pg.UsageRating)
            {
                return(1);
            }
            else if (result >= pg.UsageRating && result < pg.UsageRating + sg.UsageRating)
            {
                return(2);
            }
            else if (result >= pg.UsageRating + sg.UsageRating && result < pg.UsageRating + sg.UsageRating + sf.UsageRating)
            {
                return(3);
            }
            else if (result >= pg.UsageRating + sg.UsageRating + sf.UsageRating && result < pg.UsageRating + sg.UsageRating + sf.UsageRating + pf.UsageRating)
            {
                return(4);
            }
            else
            {
                return(5);
            }
        }
        public async Task <List <Player> > LoadPlayerRatingsForAlgorithm(List <Player> players, string type)
        {
            var playerRatings = await _playerRatingRepository.GetAll();

            foreach (var player in players)
            {
                if (playerRatings.ContainsKey(player.Id))
                {
                    player.Stats = playerRatings[player.Id];
                    // remove them so they aren't reset
                    playerRatings.Remove(player.Id);
                }
                else
                {
                    // in case playerrating entry doesn't exist, create one now
                    var newPlayerRating = new PlayerRating {
                        PlayerId = player.Id, PlayerGender = player.Gender
                    };
                    await _playerRatingRepository.Insert(newPlayerRating);

                    player.Stats = newPlayerRating;
                }
            }
            // anybody left over should be reset (inactive)
            if (type.Equals("singles", StringComparison.OrdinalIgnoreCase))
            {
                await ResetSinglesPlayerRatings(playerRatings.Values.ToList());
            }
            else if (type.Equals("doubles", StringComparison.OrdinalIgnoreCase))
            {
                await ResetDoublesPlayerRatings(playerRatings.Values.ToList());
            }
            return(players);
        }
Пример #3
0
 public static void AddRating(PlayerRating rating)
 {
     using (var db = new EloDbContext())
     {
         db.Ratings.Add(rating);
         db.SaveChanges();
     }
 }
Пример #4
0
 public void UpdateFromRatingSystem(PlayerRating rating)
 {
     this.Percentile  = rating.Percentile;
     this.Rank        = rating.Rank;
     this.RealElo     = rating.RealElo;
     this.Uncertainty = rating.Uncertainty;
     this.Elo         = rating.Elo;
 }
        public async Task <PlayerRating> Insert(PlayerRating playerRating)
        {
            await _context.PlayerRatings.AddAsync(playerRating);

            await _context.SaveChangesAsync();

            return(playerRating);
        }
        public ActionResult DeleteConfirmed(int id)
        {
            PlayerRating playerRating = db.PlayerRatings.Find(id);

            db.PlayerRatings.Remove(playerRating);
            db.SaveChanges();
            return(RedirectToAction("Index"));
        }
 public ActionResult Edit([Bind(Include = "RatingID,PlayerID,GMID,Comment,Rating,RatingTime")] PlayerRating playerRating)
 {
     if (ModelState.IsValid)
     {
         db.Entry(playerRating).State = EntityState.Modified;
         db.SaveChanges();
         return(RedirectToAction("Index"));
     }
     ViewBag.GMID     = new SelectList(db.GMs, "GMID", "Username", playerRating.GMID);
     ViewBag.PlayerID = new SelectList(db.Players, "PlayerID", "Username", playerRating.PlayerID);
     return(View(playerRating));
 }
        // GET: PlayerRatings/Details/5
        public ActionResult Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            PlayerRating playerRating = db.PlayerRatings.Find(id);

            if (playerRating == null)
            {
                return(HttpNotFound());
            }
            return(View(playerRating));
        }
        // GET: PlayerRatings/Edit/5
        public ActionResult Edit(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            PlayerRating playerRating = db.PlayerRatings.Find(id);

            if (playerRating == null)
            {
                return(HttpNotFound());
            }
            ViewBag.GMID     = new SelectList(db.GMs, "GMID", "Username", playerRating.GMID);
            ViewBag.PlayerID = new SelectList(db.Players, "PlayerID", "Username", playerRating.PlayerID);
            return(View(playerRating));
        }
Пример #10
0
 public void UpdateFromRatingSystem(PlayerRating rating)
 {
     this.Percentile = rating.Percentile;
     this.IsRanked   = rating.Rank < int.MaxValue;
     this.RealElo    = rating.RealElo;
     this.EloStdev   = rating.EloStdev;
     this.Elo        = rating.Elo;
     if (float.IsNaN(rating.LadderElo))
     {
         Trace.TraceWarning("Tried to set LadderElo for " + AccountID + " to NaN");
     }
     else
     {
         LadderElo = rating.LadderElo;
     }
 }
        /// <summary>
        /// Посторение рейтинговой системы и расчет рейтинга
        /// </summary>
        public static void BuildRatingSystem(int gameTypeId, PlayersRatingList players, CompetitionsList competitions, DateTime date)
        {
            // Загрузить список игроков с начальным рейтингом
            TA.DB.Manager.DatabaseManager.CurrentDb.ReadPlayerRatingList(gameTypeId, players);
#if FEDITION
            // Загрузить результаты по порядку возрастания даты
            TA.DB.Manager.DatabaseManager.CurrentDb.ReadRatingCompetitionList(gameTypeId, competitions, date);
            // Пересчитать рейтинги для каждого турнира по мере возрастания даты
            foreach (CompetitionInfo comp in competitions)
            {
                if (comp.IsRating)
                {
                    int avg_rating = 0;
                    foreach (PlayersCompetitionResult result in comp.Results.Values)
                    {
                        PlayerRating player = players[result.PlayerId];
                        // 1 - Посчитать штрафы за пропуск в зависимости от даты турнира и даты из списка игроков
                        if (player.LastRatingDate != DateTime.MinValue)
                        {
                            result.Penalty = (RatingSystem.GetMonthCount(player.LastRatingDate, comp.Date) / 3) * 25;
                        }
                        // 2 - Расчитать начальный рейтинг (Рейтинг из списка - штраф)
                        result.RatingBegin = player.Rating - result.Penalty;
                        avg_rating        += result.RatingBegin;
                    }
                    foreach (PlayersCompetitionResult result in comp.Results.Values)
                    {
                        PlayerRating player = players[result.PlayerId];
                        // 4 - Расчитать дельту для кажого игрока
                        result.Delta = Convert.ToInt32(Math.Round(10.0 * (result.Points - result.OpponentsCount * RatingSystem.Pexp(result.RatingBegin - result.AvgOppRating(comp.Results)))));
                        // 5 - Обновить рейтинг и дату в списке игроков
                        player.Rating         = result.RatingBegin + result.Delta;
                        player.LastRatingDate = comp.Date;
                    }
                }
            }
#endif
        }
Пример #12
0
 public RatingDto(PlayerRating r)
 {
     this.PlayerId = r.PlayerId;
     this.Rating   = r.Rating;
 }
Пример #13
0
        public void Draw(Image image, int viewRowFrom, int visibleRowCount, int viewColFrom, int visibleColCount)
        {
            Graphics gr = Graphics.FromImage(image);

            gr.FillRectangle(FPlayersBrush, Rect_Players);
            gr.FillRectangle(FResultBkBrush, Rect_Results);
            gr.FillRectangle(FHeaderBkBrush, Rect_Header_C);
            gr.FillRectangle(FRatingBkBrush, Rect_RatingBegin);
            gr.FillRectangle(FRatingBkBrush, Rect_Rating);
            gr.FillRectangle(Brushes.WhiteSmoke, Rect_Footer);
            gr.DrawString(Localizator.Dictionary.GetString("PLAYER_LIST"), Font, FPlayersFontBrush, new Rectangle(0, 0, ColWidth_P, Height_Header), sf_center);
            gr.DrawString(Localizator.Dictionary.GetString("START_RATING"), Font, FPlayersFontBrush, new Rectangle(ColWidth_P, 0, ColWidth_RB, Height_Header), sf_center);
            Rectangle header_caption_rect = new Rectangle(ColWidth_P + ColWidth_RB, 0, Rect_Results.Width, Height_Header / 2);

            gr.DrawRectangle(FLinePen, header_caption_rect);
            gr.DrawString(Localizator.Dictionary.GetString("TOURNAMENT_RESULTS"), Font, FPlayersFontBrush, header_caption_rect, sf_center);
            gr.DrawRectangle(FLinePen, Rect_RatingBegin.Left, Rect_RatingBegin.Top, Rect_RatingBegin.Width, Height_Header);
            gr.DrawRectangle(FLinePen, Rect_Players.Left, Rect_Players.Top, Rect_Players.Width, Height_Header);

            if (RS != null)
            {
                Rectangle player_rect       = new Rectangle(0, Height_Header, ColWidth_P, Height_Row);
                Rectangle rating_begin_rect = new Rectangle(ColWidth_P, Height_Header, ColWidth_RB, Height_Row);
                Rectangle rating_rect       = new Rectangle(image.Width - ColWidth_R, Height_Header, ColWidth_R, Height_Row);
                Rectangle comp_rect         = new Rectangle(new Point(ColWidth_P, Height_Header), new Size(ColWidth_C, Height_Row));

                for (int p = viewRowFrom; p < FPlayers.Length && p < viewRowFrom + visibleRowCount; p++)
                {
                    PlayerRating player = FPlayers[p];
                    gr.DrawRectangle(FLinePen, player_rect);
                    gr.DrawRectangle(FLinePen, new Rectangle(player_rect.Location, new Size(image.Width, Height_Row)));
                    gr.DrawString(player.Name, Font, FPlayersFontBrush, player_rect, sf_left);
                    gr.DrawString(player.Country, Font, FPlayersFontBrush, new Rectangle(player_rect.X + player_rect.Width - ColWidth_Cntry, player_rect.Y, ColWidth_Cntry, player_rect.Height), sf_left);


                    gr.DrawRectangle(FLinePen, rating_begin_rect);
                    //gr.DrawRectangle(FLinePen, new Rectangle(player_rect.Location, new Size(Width, Height_Row)));
                    gr.DrawString(player.RatingBegin.ToString(), Font, FPlayersFontBrush, rating_begin_rect, sf_right);

                    comp_rect.X = ColWidth_P + ColWidth_RB;
                    comp_rect.Y = player_rect.Y;
                    Rectangle header_rect = new Rectangle(comp_rect.X, Height_Header / 2, ColWidth_C, Height_Header / 2);
                    for (int i = viewColFrom; (i < RS.Competitions.Count) && (i - viewColFrom < visibleColCount); i++)
                    {
                        gr.DrawRectangle(FLinePen, header_rect);
                        gr.DrawString(RS.Competitions[i].Date.ToString("dd.MM.yyyy"), Font, FHeaderBrush, header_rect, sf_center);
                        header_rect.Offset(header_rect.Width, 0);
                        gr.DrawRectangle(FLinePen, comp_rect);
                        if (RS.Competitions[i].Results.ContainsKey(player.Id))
                        {
                            PlayersCompetitionResult res = RS.Competitions[i].Results[player.Id];
                            if (res.Penalty != 0)
                            {
                                gr.DrawString((-res.Penalty).ToString(), Font, FPenaltyBrush, comp_rect, sf_left);
                            }
                            string delta = res.Delta.ToString();
                            if (res.Delta > 0)
                            {
                                delta = "+" + delta;
                            }
                            gr.DrawString(delta, Font, FDeltaBrush, comp_rect, sf_right);
                        }
                        comp_rect.Offset(comp_rect.Width, 0);
                    }
                    gr.FillRectangle(FRatingBkBrush, rating_rect);
                    gr.DrawRectangle(FLinePen, rating_rect);
                    gr.DrawString(player.Rating.ToString(), Font, FRatingFontBrush, rating_rect, sf_left);
                    player_rect.Offset(0, player_rect.Height);
                    rating_rect.Offset(0, rating_rect.Height);
                    rating_begin_rect.Offset(0, rating_rect.Height);
                }
            }
            Rectangle rating_header_rect = new Rectangle(image.Width - ColWidth_R, 0, ColWidth_R, Height_Header);

            gr.FillRectangle(FRatingBkBrush, rating_header_rect);
            gr.DrawRectangle(FLinePen, rating_header_rect);
            string date_str = String.Format(Localizator.Dictionary.GetString("RATING_AT"), FRatingDate.ToString("dd.MM.yyyy"));

            gr.DrawString(date_str, Font, FRatingFontBrush, rating_header_rect, sf_center);
            //gr.DrawString(hScrollBar.Value.ToString(), Font, FRatingFontBrush, rating_header_rect, sf_center);
            Point pointA = new Point(0, Height_Header - 8);

            switch (SortedBy)
            {
            case SortBy.Name:
                pointA.X = ColWidth_P / 2;
                break;

            case SortBy.Rating:
                pointA.X = image.Width - ColWidth_R / 2;
                break;
            }
            Point pointB = new Point(pointA.X - 4, pointA.Y + 5);
            Point pointC = new Point(pointA.X + 4, pointA.Y + 5);

            gr.FillPolygon(FHeaderBrush, new Point[] { pointA, pointB, pointC });
        }
Пример #14
0
        public virtual bool Open(string pathToXml)
        {
            try
            {
                XmlTextReader reader = new XmlTextReader(pathToXml);
                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:        // Узел является элементом.
                        if (reader.Name == "CM_XML")
                        {
                            FDate    = DateTime.ParseExact(reader.GetAttribute("date"), "yyyyMMdd", CultureInfo.InvariantCulture);
                            FAppGuid = new Guid(reader.GetAttribute("app_guid"));
                        }
                        if (reader.Name == "MEMBERS")
                        {
                            FPlayers.Clear();
                        }
                        if (reader.Name == "MEMBER")
                        {
                            PlayerInfo player = new PlayerInfo();
                            player.Identifier     = new Guid(reader.GetAttribute("GUID"));
                            player.NickName       = reader.GetAttribute("nick");
                            player.LastName       = reader.GetAttribute("lname");
                            player.FirstName      = reader.GetAttribute("fname");
                            player.PatronymicName = reader.GetAttribute("pname");
                            player.Country        = reader.GetAttribute("country");
                            player.City           = reader.GetAttribute("city");
                            player.Phone          = reader.GetAttribute("phones");
                            player.EMail          = reader.GetAttribute("email");

                            // в trial версии можно экспортировать за раз не более 10 игроков
                            if (EditionManager.Edition != EditionType.Mini)
                            {
                                if (!EditionManager.IsTrial || FPlayers.Count < 10)     // в trial версии можно экспортировать за раз не более 10 игроков
                                {
                                    FPlayers.Add(player);
                                }
                            }
                        }
                        if (reader.Name == "RATINGS")
                        {
                            // Начинаем экспортирование рейтингов
                            FRatings.Clear();
                        }
                        if (reader.Name == "RATING")
                        {
                            rating_node           = new XmlExporter.RatingNode();
                            rating_node.Game      = new TypeOfSport();
                            rating_node.Game.Id   = Convert.ToInt32(reader.GetAttribute("id"));
                            rating_node.Game.Name = reader.GetAttribute("name");
                            // в trial версии можно экспортировать за раз не более 1 рейтинга
                            if (EditionManager.Edition != EditionType.Mini)
                            {
                                if (!EditionManager.IsTrial || FRatings.Count < 1)
                                {
                                    FRatings.Add(rating_node.Game, rating_node);
                                }
                            }
                        }
                        if (reader.Name == "PLAYER_RATING")
                        {
                            if (EditionManager.Edition != EditionType.Mini)
                            {
                                if (rating_node == null)
                                {
                                    throw new Exception("Не задан рейтинговый лист");
                                }
                                PlayerRating rating = new PlayerRating();
                                string       date   = reader.GetAttribute("date");
                                if (date != "")
                                {
                                    rating.LastRatingDate = DateTime.ParseExact(date, "yyyyMMdd", CultureInfo.InvariantCulture);
                                }
                                rating.Guid        = new Guid(reader.GetAttribute("guid"));
                                rating.RatingBegin = Convert.ToInt32(reader.GetAttribute("start"));
                                rating.Rating      = Convert.ToInt32(reader.GetAttribute("current"));
                                rating.Name        = reader.GetAttribute("name");
                                rating_node.Ratings.Add(rating);
                            }
                        }
                        if (reader.Name == "TOURNAMENTS")
                        {
                            FTournaments.Clear();
                        }
                        if (reader.Name == "TOURNAMENT")
                        {
                            tournament = new Tournament();
                            tournament.Info.DateBegin = DateTime.ParseExact(reader.GetAttribute("begin"), "yyyyMMdd", CultureInfo.InvariantCulture);
                            tournament.Info.DateEnd   = DateTime.ParseExact(reader.GetAttribute("end"), "yyyyMMdd", CultureInfo.InvariantCulture);
                            tournament.Info.Name      = reader.GetAttribute("name");
                            tournament.Info.Place     = reader.GetAttribute("place");

                            if (EditionManager.Edition != EditionType.Mini && EditionManager.Edition != EditionType.Standard)
                            {
                                if (!EditionManager.IsTrial || FTournaments.Count < 1)     // в trial версии можно экспортировать за раз не более 1 турнира
                                {
                                    FTournaments.Add(tournament);
                                }
                            }
                        }
                        if (reader.Name == "COMPETITIONS")
                        {
                            if (tournament == null)
                            {
                                throw new Exception("Tournamet is not initialized");
                            }
                            tournament.Competitions.Clear();
                        }
                        if (reader.Name == "COMPETITION")
                        {
                            TA.Corel.CompetitionInfo ci = new TA.Corel.CompetitionInfo();
                            ci.ChangesRating        = Convert.ToBoolean(reader.GetAttribute("rating"));
                            ci.CompetitionType.Id   = Convert.ToInt32(reader.GetAttribute("type"));
                            ci.CompetitionType.Name = reader.GetAttribute("type_name");
                            ci.Date         = DateTime.ParseExact(reader.GetAttribute("date"), "yyyyMMdd", CultureInfo.InvariantCulture);
                            ci.Name         = reader.GetAttribute("name");
                            ci.SportType.Id = Convert.ToInt32(reader.GetAttribute("sport"));
                            ci.Status       = (TA.Corel.CompetitionInfo.CompetitionState)(Enum.Parse(typeof(TA.Corel.CompetitionInfo.CompetitionState), reader.GetAttribute("status")));
                            competition     = TA.Competitions.CompetitionFactory.CreateCompetition(ci);
                            // в trial версии можно экспортировать за раз не более 1 соревнования
                            if (!EditionManager.IsTrial || tournament.Competitions.Count < 1)
                            {
                                tournament.Competitions.Add(tournament.Competitions.Count + 1, competition);
                            }
                        }
                        if (reader.Name == "PARAMS")
                        {
                            if (competition == null)
                            {
                                throw new Exception("Competition is not initialized");
                            }
                            competition.Info.Properties.Clear();
                        }
                        if (reader.Name == "PARAM")
                        {
                            if (competition == null)
                            {
                                throw new Exception("Competition is not initialized");
                            }
                            competition.Info.Properties.Add(reader.GetAttribute("name"), reader.GetAttribute("value"));
                        }
                        if (reader.Name == "PLAYERS")
                        {
                            if (competition == null)
                            {
                                throw new Exception("Competition is not initialized");
                            }
                            competition.Players.Clear();
                        }
                        if (reader.Name == "PLAYER")
                        {
                            if (competition == null)
                            {
                                throw new Exception("Competition is not initialized");
                            }
                            CompetitionPlayerInfo pi = new CompetitionPlayerInfo();
                            pi.Identifier = new Guid(reader.GetAttribute("guid"));
                            pi.Place      = new TA.Utils.StringAlt(reader.GetAttribute("place"));
                            pi.RatingBeforeCompetition = Convert.ToInt32(reader.GetAttribute("rating"));
                            pi.SeedNo      = Convert.ToInt32(reader.GetAttribute("seed"));
                            pi.StartPoints = Convert.ToInt32(reader.GetAttribute("start_points"));
                            pi.RebuyPoints = Convert.ToInt32(reader.GetAttribute("rebuy_points"));
                            competition.Players.Add(competition.Players.Count + 1, pi);
                        }

                        if (reader.Name == "MATCHES")
                        {
                            if (competition == null)
                            {
                                throw new Exception("Competition is not initialized");
                            }
                            competition.Matches.Clear();
                        }
                        if (reader.Name == "MATCH")
                        {
                            if (competition == null)
                            {
                                throw new Exception("Competition is not initialized");
                            }
                            match             = new MatchInfo();
                            match.Label.Label = reader.GetAttribute("label");
                            match.Loosers_MatchLabel.Label = reader.GetAttribute("looser_label");
                            match.Winners_MatchLabel.Label = reader.GetAttribute("winner_label");
                            match.Winner = (MatchLabel.PlayerLetters)Enum.Parse(typeof(MatchLabel.PlayerLetters), reader.GetAttribute("winner"));
                            competition.Matches.Add(competition.Matches.Count + 1, match);
                        }
                        if (reader.Name == "PLAYER_A")
                        {
                            if (match == null)
                            {
                                throw new Exception("Match is not initialized");
                            }
                            match.PlayerA.Id     = Convert.ToInt32(reader.GetAttribute("id"));
                            match.PlayerA.Guid   = new Guid(reader.GetAttribute("guid"));
                            match.PlayerA.Points = Convert.ToInt32(reader.GetAttribute("points"));
                            match.PlayerA.Tag    = Convert.ToInt32(reader.GetAttribute("tag"));
                        }
                        if (reader.Name == "PLAYER_B")
                        {
                            if (match == null)
                            {
                                throw new Exception("Match is not initialized");
                            }
                            match.PlayerB.Id     = Convert.ToInt32(reader.GetAttribute("id"));
                            match.PlayerB.Guid   = new Guid(reader.GetAttribute("guid"));
                            match.PlayerB.Points = Convert.ToInt32(reader.GetAttribute("points"));
                            match.PlayerB.Tag    = Convert.ToInt32(reader.GetAttribute("tag"));
                        }
                        break;
                    }
                }
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Пример #15
0
        public ActionResult PlayerRequests_Read([DataSourceRequest]DataSourceRequest request)
        {
            // loads all member requests to become a player
            PlayerRatingCollection playerRatings = PlayerRatingCollection.LoadAll();

            PlayerRating currentPlayerRating = new PlayerRating();

            IEnumerable<User> members = UserCollection.LoadAll()
                .Where(member => member.DateRegisteredAsPlayer != null)
                .Where(member => member.DateRegisteredAsPlayer != default(DateTime))
                .Where(member => member.PlayerRating == null);

            DataSourceResult result = new DataSourceResult();

            result = members.ToDataSourceResult(request, member => new PlayerRequestViewModel
            {
                Id = member.Id,
                UserName = member.UserName,
                FirstName = member.FirstName,
                LastName = member.LastName,
                Rating = null,
                DateRegisteredAsPlayer = member.DateRegisteredAsPlayer.ToString("dd MMMM yyyy")
            });

            return Json(result);
        }
 public RatingDetailsDto(PlayerRating r)
 {
     this.PlayerName = r.Player.Name;
     this.PlayerId   = r.Player.Id;
     this.Rating     = r.Rating;
 }
 public async Task Delete(PlayerRating playerRating)
 {
     // player history should cascade
     _context.PlayerRatings.Remove(playerRating);
     await _context.SaveChangesAsync();
 }
Пример #18
0
        private static void PostUpdates(IDbConnection connection, IDbTransaction transaction, IEnumerable<Match> suspectMatches,
            PlayerRating playerOne, PlayerRating playerTwo, DateTime now, int forcedMatchId = 0)
        {
            suspectMatches = suspectMatches.OrderBy(m => m.MatchDate);
            var affectedPlayers = new List<PlayerRating> {playerOne, playerTwo};
            var affectedMatches = new List<Match>();

            foreach (var suspectMatch in suspectMatches.Where(suspectMatch => affectedPlayers.Any(p => p.Id == suspectMatch.PlayerOneId || p.Id == suspectMatch.PlayerTwoId)))
            {
                if (affectedPlayers.All(p => p.Id != suspectMatch.PlayerOneId))
                {
                    var player = Global.Players.Single(p => p.Id == suspectMatch.PlayerOneId);
                    var playerRating = FindLastGoodRating(player, suspectMatch.MatchDate);
                    affectedPlayers.Add(playerRating);
                }

                if (affectedPlayers.All(p => p.Id != suspectMatch.PlayerTwoId))
                {
                    var player = Global.Players.Single(p => p.Id == suspectMatch.PlayerTwoId);
                    var playerRating = FindLastGoodRating(player, suspectMatch.MatchDate);
                    affectedPlayers.Add(playerRating);
                }

                var firstPlayer = affectedPlayers.Single(p => p.Id == suspectMatch.PlayerOneId);
                var secondPlayer = affectedPlayers.Single(p => p.Id == suspectMatch.PlayerTwoId);

                CalculateRating(firstPlayer, secondPlayer,
                    suspectMatch.WinningPlayerId == suspectMatch.PlayerOneId ? 1 : 2);

                firstPlayer.MatchDate = suspectMatch.MatchDate;
                secondPlayer.MatchDate = suspectMatch.MatchDate;

                if (suspectMatch.ConfirmationDate == null && suspectMatch.Id != forcedMatchId)
                {
                    firstPlayer.Locked = true;
                    secondPlayer.Locked = true;
                }
                else
                {
                    if (firstPlayer.Locked || secondPlayer.Locked)
                        continue;
                    firstPlayer.FinalMu = firstPlayer.NewMu;
                    firstPlayer.FinalSigma = firstPlayer.NewSigma;
                    secondPlayer.FinalMu = secondPlayer.NewMu;
                    secondPlayer.FinalSigma = secondPlayer.NewSigma;
                }

                affectedMatches.Add(new Match
                {
                    Id = suspectMatch.Id,
                    PostDate = !firstPlayer.Locked && !secondPlayer.Locked ? now : (DateTime?) null,
                    PlayerOneOldMu = firstPlayer.OldMu,
                    PlayerOneNewMu = firstPlayer.NewMu,
                    PlayerOneOldSigma = firstPlayer.OldSigma,
                    PlayerOneNewSigma = firstPlayer.NewSigma,
                    PlayerTwoOldMu = secondPlayer.OldMu,
                    PlayerTwoNewMu = secondPlayer.NewMu,
                    PlayerTwoOldSigma = secondPlayer.OldSigma,
                    PlayerTwoNewSigma = secondPlayer.NewSigma

                });
            }

            MatchData.Update(connection, transaction, affectedMatches);
            PlayerData.UpdateRating(connection, transaction, affectedPlayers);
        }
Пример #19
0
        private static void CalculateRating(PlayerRating playerOne, PlayerRating playerTwo, int winner)
        {
            var gameInfo = GameInfo.DefaultGameInfo;

            var p1 = new Moserware.Skills.Player(playerOne.Id);
            var p2 = new Moserware.Skills.Player(playerTwo.Id);

            var t1 = new Team(p1, new Rating(playerOne.NewMu, playerOne.NewSigma));
            var t2 = new Team(p2, new Rating(playerTwo.NewMu, playerTwo.NewSigma));

            var teams = Teams.Concat(t1, t2);

            IDictionary<Moserware.Skills.Player, Rating> newRatings;
            switch (winner)
            {
                case 1:
                    newRatings = TrueSkillCalculator.CalculateNewRatings(gameInfo, teams, 1, 2);
                    break;
                case 2:
                    newRatings = TrueSkillCalculator.CalculateNewRatings(gameInfo, teams, 2, 1);
                    break;
                default:
                    throw new NotImplementedException();
            }

            playerOne.OldMu = playerOne.NewMu;
            playerOne.OldSigma = playerOne.NewSigma;
            playerTwo.OldMu = playerTwo.NewMu;
            playerTwo.OldSigma = playerTwo.NewSigma;
            playerOne.NewMu = newRatings[p1].Mean;
            playerOne.NewSigma = newRatings[p1].StandardDeviation;
            playerTwo.NewMu = newRatings[p2].Mean;
            playerTwo.NewSigma = newRatings[p2].StandardDeviation;
        }