public DrawableTournamentRound(TournamentRound round, bool losers = false) { OsuSpriteText textName; OsuSpriteText textDescription; AutoSizeAxes = Axes.Both; InternalChild = new FillFlowContainer { Direction = FillDirection.Vertical, AutoSizeAxes = Axes.Both, Children = new Drawable[] { textDescription = new OsuSpriteText { Colour = Color4.Black, Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre }, textName = new OsuSpriteText { Font = OsuFont.GetFont(weight: FontWeight.Bold), Colour = Color4.Black, Origin = Anchor.TopCentre, Anchor = Anchor.TopCentre }, } }; name = round.Name.GetBoundCopy(); name.BindValueChanged(n => textName.Text = ((losers ? "Losers " : "") + round.Name).ToUpper(), true); description = round.Description.GetBoundCopy(); description.BindValueChanged(n => textDescription.Text = round.Description.Value?.ToUpper(), true); }
public override CompetitorRanks GenerateResult(TournamentSimulation.MatchStrategies.MatchStrategy matchStrategy, List<Competitor> competitors) { TournamentRoundStrategy tournamentRoundStrategy = new KoTRS(_winsToClinchMatch); List<TournamentRound> tournamentRounds = new List<TournamentRound>(); TournamentRound tournamentRound; tournamentRound = new TournamentRound(tournamentRoundStrategy, matchStrategy); tournamentRound.Run(competitors); tournamentRounds.Add(tournamentRound); while (tournamentRound.Matches.Count > 1) { List<Competitor> winners = tournamentRound.Matches .Select(x => x.Winner) .ToList<Competitor>(); tournamentRound = new TournamentRound(tournamentRoundStrategy, matchStrategy); tournamentRound.Run(winners); tournamentRounds.Add(tournamentRound); } List<Match> matches = new List<Match>(); foreach (TournamentRound round in tournamentRounds) { matches.AddRange(round.Matches); } Matches = matches; CompetitorPoints competitorPoints = AccumulateMatchPoints(matches); return competitorPoints.GetCompetitorRanks(); }
/// <summary> /// Creates a new instance of the frmTournamentRound form. /// </summary> /// <param name="round">The TournamentRound to display on this form.</param> /// <param name="roundNumber">The round number to display on this form.</param> /// <param name="revisionMode">If true, the round is in Revision Mode.</param> public frmTournamentRound(TournamentRound round, int roundNumber, bool revisionMode = false) { InitializeComponent(); ThisRound = round; RoundNumber = roundNumber; RevisionMode = revisionMode; Text = round.TournamentName + " -- Round " + roundNumber; int matchNumber = Config.Settings.GetTournament(round.TournamentName).TableNumbering == TableNumbering.Even ? 2 : 1; int openMatches = 0; foreach (TournamentMatch match in ThisRound.Matches) { var matchControl = new ctlTournamentMatch(match, matchNumber); matchNumber += Config.Settings.GetTournament(round.TournamentName).TableNumbering == TableNumbering.Normal ? 1 : 2; matchControl.MatchLockChanged += MatchControl_MatchLockChanged; if (match.Results.Count > 0) matchControl.LockScores(); if (!matchControl.ScoresLocked) openMatches++; pnlMatches.Controls.Add(matchControl); } if (RevisionMode) { lblMatches.Text = "Viewing and Editing Round " + roundNumber; mnuOptions.Visible = false; } else lblMatchesLeft.Text = openMatches.ToString(); }
public GameInstance(Game game, Competition comp, TournamentRound round, TournamentPairing pair) { Game = game; Competition = comp; CurrentRound = round; Pairing = pair; }
public void SingleEliminationLastPersonNeverGetsABye() { IPairingsGenerator pg = new EliminationTournament(1); for (int i = 2; i <= 33; i++) { List <TournamentTeam> teams = new List <TournamentTeam>(CreateTeams(i)); List <TournamentRound> rounds = new List <TournamentRound>(); pg.LoadState(teams, rounds); TournamentTeam targetTeam = teams[teams.Count - 1]; TournamentRound round = pg.CreateNextRound(null); var targetTeamPairings = from p in round.Pairings where p.TeamScores.Where(ts => ts.Team.TeamId == targetTeam.TeamId).Any() select p; var pairingsThatAreByes = from ttp in targetTeamPairings where ttp.TeamScores.Count() == 1 select ttp; if (pairingsThatAreByes.Any()) { Assert.Fail(); } } }
public override CompetitorRanks GenerateResult(int tournamentRunSequence, TournamentSimulation.MatchStrategies.MatchStrategy matchStrategy, List<Competitor> competitors) { // round robin to seed the semifinals TournamentRound roundRobinTR = new TournamentRound(new RrTRS(_numberOfRoundRobinRounds), matchStrategy); CompetitorRanks rrRanks = roundRobinTR.Run(competitors); List<Competitor> rrRankedCompetitors = rrRanks .OrderBy(x => x.Value) .Select(x => x.Key) .ToList<Competitor>(); List<Competitor> top4 = rrRankedCompetitors .Take(4) .ToList<Competitor>(); // semifinals round TournamentRound semifinalsTR = new TournamentRound(new KoSfPfFiTRS(_winsToClinchKnockoutSemifinalsMatch, _winsToClinchKnockoutFinalsMatch, _winsToClinchKnockoutPetitFinalsMatch), matchStrategy); CompetitorRanks semiRanks = semifinalsTR.Run(top4); List<Competitor> bottom4 = rrRankedCompetitors .Skip(4) .Take(4) .ToList<Competitor>(); // give everyone else 5th foreach (Competitor competitor in bottom4) { semiRanks.Add(competitor, 5); } return semiRanks; }
public void BoilOffThreeTeamsIsOneRound() { IPairingsGenerator bopg = new BoilOffPairingsGenerator(); List <TournamentTeam> teams = new List <TournamentTeam>(CreateTeams(3)); List <TournamentRound> rounds = new List <TournamentRound>(); try { bopg.LoadState(teams, rounds); TournamentRound round = bopg.CreateNextRound(null); foreach (var pairing in round.Pairings) { foreach (var teamScore in pairing.TeamScores) { teamScore.Score = new HighestPointsScore(r.Next(20)); } } rounds.Add(round); bopg.LoadState(teams, rounds); round = bopg.CreateNextRound(null); Assert.AreEqual(null, round); } catch (ArgumentNullException) { } }
static void Main(string[] args) { var p = new StandardTournamentsPluginEnumerator(); var factories = from f in p.EnumerateFactories() let pf = f as IPairingsGeneratorFactory where pf != null select pf; generator = (EliminationTournament)factories.ToList()[0].Create(); teams.Add(new User(0, 100)); teams.Add(new User(1, 100)); generator.Reset(); generator.LoadState(teams, rounds); // add winner TournamentRound round = generator.CreateNextRound(null); round.Pairings[0].TeamScores[0].Score = new HighestPointsScore(200); round.Pairings[0].TeamScores[1].Score = new HighestPointsScore(100); rounds.Add(round); var standings = generator.GenerateRankings(); generator.Reset(); generator.LoadState(teams, rounds); round = generator.CreateNextRound(null); Console.Read(); }
public TournamentRound GetRandomRound(TournamentRound vanilla, TournamentGame.QualificationMode qualificationMode) { var matches = new List <TournamentRound>(); if (Enable1Match2Teams) { matches.Add(new (ParticipantCount, 1, 2, WinnerCount, qualificationMode)); } if (Enable1Match4Teams) { matches.Add(new (ParticipantCount, 1, 4, WinnerCount, qualificationMode)); } if (Enable2Match2Teams) { matches.Add(new (ParticipantCount, 2, 2, WinnerCount, qualificationMode)); } if (Enable2Match4Teams) { matches.Add(new (ParticipantCount, 2, 4, WinnerCount, qualificationMode)); } if (Enable4Match2Teams) { matches.Add(new (ParticipantCount, 4, 2, WinnerCount, qualificationMode)); } if (EnableVanilla || !matches.Any()) { matches.Add(vanilla); } return(matches.SelectRandom()); }
private Draw InitializeDraw(DrawSize drawSize, TournamentRound startingRound, int matchesCount) { var draw = new Draw(); switch (drawSize) { case DrawSize.draw8: draw.InitialRound = TournamentRound.round4; draw.MatchesCount = 7; break; case DrawSize.draw16: draw.InitialRound = TournamentRound.round3; draw.MatchesCount = 15; break; case DrawSize.draw32: draw.InitialRound = TournamentRound.round2; draw.MatchesCount = 31; break; case DrawSize.draw64: draw.InitialRound = TournamentRound.round1; draw.MatchesCount = 63; break; } ; return(draw); }
private void dopairs(string[] selectedfiles, string strarch, string extension) { allcombats.Clear(); teamNames.Clear(); teamWarriors.Clear(); rounds.Clear(); teams.Clear(); ncombat = 0; fullCombatLog = ""; generator = new RoundRobinPairingsGenerator(); generator.Reset(); int n = 0; foreach (string s in selectedfiles) { var team = new TournamentTeam(n, 0); teams.Add(team); string tmp = Path.GetFileName(selectedfiles[n]); teamNames.Add(n, tmp.Substring(0, tmp.IndexOf(extension))); teamWarriors.Add(n, selectedfiles[n]); n++; } while (true) { TournamentRound round = null; generator.Reset(); generator.LoadState(teams, rounds); round = generator.CreateNextRound(null); if (round != null) { rounds.Add(round); } else { break; } } foreach (TournamentRound round in rounds) { foreach (var pairing in round.Pairings) { allcombats.Add(pairing); } } string memoria = getemptymemory(); string salida = ""; salida = "Tournament arch: " + strarch + "\nTotal Warriors loaded " + selectedfiles.Count().ToString(); if (selectedfiles.Count() < 2) { salida += "\nCannot begin Tournament with only one Warrior!"; } else { salida += "\nPress 'start' button to begin Tournament."; } string envio = "{\"player1\":{\"regs\":\" \",\"code\":\" \",\"name\":\"Player - 1\"},\"player2\":{\"regs\":\" \",\"code\":\" \",\"name\":\"Player - 2\"},\"memory\":[" + memoria + "],\"console\":\"" + salida + "\",\"status\":\"Warriors Loaded.\",\"scores\":\" \"}"; SendDrawEvent(envio.Replace("\n", "\\n").Replace("\r", "")); }
private IEnumerable <TournamentRound> RounRobinBuildAllPairings(IEnumerable <TournamentTeam> teams, IPairingsGenerator rrpg) { List <TournamentRound> rounds = new List <TournamentRound>(); while (true) { rrpg.LoadState(teams, rounds); TournamentRound newRound = rrpg.CreateNextRound(null); if (newRound != null) { rounds.Add(newRound); } else { break; } } foreach (TournamentRound round in rounds) { yield return(round); } yield break; }
public void RunTournament(IPairingsGenerator pg, List <TournamentTeam> teams, List <TournamentRound> rounds, bool allowTies, TournamentNameTable nameTable) { ITournamentVisualizer viz = null; if (nameTable != null) { viz = pg as ITournamentVisualizer; } while (true) { pg.LoadState(teams, rounds); TournamentRound newRound = pg.CreateNextRound(null); if (viz != null) { var gfx = new SystemGraphics(); var q2 = viz.Measure(gfx, nameTable); viz.Render(gfx, nameTable); } if (newRound == null) { pg.LoadState(teams, rounds); newRound = pg.CreateNextRound(null); break; } if (allowTies) { foreach (var pairing in newRound.Pairings) { foreach (var teamScore in pairing.TeamScores) { teamScore.Score = new HighestPointsScore(r.Next(20)); } } } else { foreach (var pairing in newRound.Pairings) { List <double> scoresUsed = new List <double>(); foreach (var teamScore in pairing.TeamScores) { double score; do { score = r.NextDouble(); } while (scoresUsed.Where(s => s == score).Any()); teamScore.Score = new HighestPointsScore(score); } } } rounds.Add(newRound); } }
public RoundInstance(Competition comp, TournamentRound round, Round rd, TournamentInstance ti) { CurrentRound = round; Competition = comp; GameInstances = new List <GameInstance>(); Round = rd; TInstance = ti; }
public override CompetitorRanks GenerateResult(int tournamentRunSequence, MatchStrategy matchStrategy, List<Competitor> competitors) { TournamentRoundStrategy tournamentRoundStrategy = new KoSfFiTRS(_winsToClinchMatch); TournamentRound tournamentRound = new TournamentRound(tournamentRoundStrategy, matchStrategy); return tournamentRound.Run(competitors); }
private void StartNext_Click(object sender, EventArgs e) { TournamentRound round = null; try { this.generator.Reset(); this.generator.LoadState(this.teams, this.rounds); round = this.generator.CreateNextRound(null); } catch (InvalidTournamentStateException ex) { MessageBox.Show(ex.Message, "Error Creating Next Round."); if (Debugger.IsAttached) { Debugger.Break(); } return; } if (round != null) { this.rounds.Add(round); var roundNumber = this.rounds.Count; this.roundGroupsHelper.Add(round, new List <ListViewGroup>()); this.roundItemsHelper.Add(round, new List <ListViewItem>()); var i = 1; foreach (var pairing in round.Pairings) { var group = new ListViewGroup("Round " + roundNumber + ", Pairing " + i); this.RoundsList.Groups.Add(group); this.roundGroupsHelper[round].Add(group); foreach (var teamScore in pairing.TeamScores) { var item = new ListViewItem(new string[] { teamScore.Score == null ? "" : teamScore.Score.ToString(), this.teamNames[teamScore.Team.TeamId] }); item.Tag = teamScore; item.Group = group; this.RoundsList.Items.Add(item); this.roundItemsHelper[round].Add(item); if (!this.teamItemsHelper.ContainsKey(teamScore.Team.TeamId)) { this.teamItemsHelper.Add(teamScore.Team.TeamId, new List <ListViewItem>()); } this.teamItemsHelper[teamScore.Team.TeamId].Add(item); } i++; } this.UpdateState(); } }
public void TounamentRoundRejectsNullParameters() { try { TournamentRound ts = new TournamentRound(null); Assert.Fail(); } catch (ArgumentNullException) { return; } }
public void DoubleEliminationLongTournament() { IPairingsGenerator pg = new EliminationTournament(2); List <TournamentTeam> teams = new List <TournamentTeam>(CreateTeams(5)); List <TournamentRound> rounds = new List <TournamentRound>(); pg.LoadState(teams, rounds); TournamentRound round1 = pg.CreateNextRound(null); round1.Pairings[0].TeamScores[0].Score = new HighestPointsScore(1); round1.Pairings[0].TeamScores[1].Score = new HighestPointsScore(2); round1.Pairings[1].TeamScores[0].Score = new HighestPointsScore(1); round1.Pairings[1].TeamScores[1].Score = new HighestPointsScore(2); rounds.Add(round1); pg.LoadState(teams, rounds); TournamentRound round2 = pg.CreateNextRound(null); round2.Pairings[0].TeamScores[0].Score = new HighestPointsScore(1); round2.Pairings[0].TeamScores[1].Score = new HighestPointsScore(2); rounds.Add(round2); pg.LoadState(teams, rounds); TournamentRound round3 = pg.CreateNextRound(null); round3.Pairings[0].TeamScores[0].Score = new HighestPointsScore(2); round3.Pairings[0].TeamScores[1].Score = new HighestPointsScore(1); round3.Pairings[1].TeamScores[0].Score = new HighestPointsScore(2); round3.Pairings[1].TeamScores[1].Score = new HighestPointsScore(1); rounds.Add(round3); pg.LoadState(teams, rounds); TournamentRound round4 = pg.CreateNextRound(null); round4.Pairings[0].TeamScores[0].Score = new HighestPointsScore(2); round4.Pairings[0].TeamScores[1].Score = new HighestPointsScore(1); rounds.Add(round4); pg.LoadState(teams, rounds); TournamentRound round5 = pg.CreateNextRound(null); round5.Pairings[0].TeamScores[0].Score = new HighestPointsScore(1); round5.Pairings[0].TeamScores[1].Score = new HighestPointsScore(2); rounds.Add(round5); pg.LoadState(teams, rounds); TournamentRound round6 = pg.CreateNextRound(null); round6.Pairings[0].TeamScores[0].Score = new HighestPointsScore(2); round6.Pairings[0].TeamScores[1].Score = new HighestPointsScore(1); rounds.Add(round6); RunTournament(pg, teams, rounds, false, null); DisplayTournamentRounds(rounds); DisplayTournamentRankings(pg.GenerateRankings()); }
public List <TournamentRound> RetrieveData() { List <TournamentRound> tournamentRoundCollection = new List <TournamentRound>(); NameValueCollection parametros = new NameValueCollection(); HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); this.MrRobotWebClient._allowAutoRedirect = false; for (int i = 0; i <= 38; i++) { var ret = this.HttpGet($@"http://globoesporte.globo.com/servico/esportes_campeonato/responsivo/widget-uuid/bc112c6b-2a2e-4620-8f01-1f31cfa6af5c/fases/fase-unica-seriea-2016/rodada/{i}/jogos.html"); var results = ret.DocumentNode.Descendants("li").Where(d => (d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("lista-de-jogos-item"))); List <SoccerMatchResult> soccerMatchResultCollection = new List <SoccerMatchResult>(); foreach (var item in results) { SoccerMatchResult soccerMatchResult = new SoccerMatchResult(); //Carregando o Html de cada artigo. doc.LoadHtml(item.InnerHtml); //Estou utilizando o HtmlAgilityPack.HtmlEntity.DeEntitize para fazer o HtmlDecode dos textos capturados de cada artigo. // Utilizo também o UTF8 para limpar o restante dos Encodes que estiverem na página. var matchData = doc.DocumentNode.Descendants("div").Where(d => (d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("placar-jogo-equipes"))).FirstOrDefault(); var homeTeamData = matchData.Descendants("span").Where(d => (d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("placar-jogo-equipes-mandante"))); var awayTeamData = matchData.Descendants("span").Where(d => (d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("placar-jogo-equipes-visitante"))); var scoreData = matchData.Descendants("span").Where(d => (d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("placar-jogo-equipes-placar"))); soccerMatchResult.HomeTeam = HtmlAgilityPack.HtmlEntity.DeEntitize(ConvertUTF(homeTeamData.FirstOrDefault().Descendants("span").Where(d => (d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("placar-jogo-equipes-nome"))).FirstOrDefault().InnerText)); soccerMatchResult.AwayTeam = HtmlAgilityPack.HtmlEntity.DeEntitize(ConvertUTF(awayTeamData.FirstOrDefault().Descendants("span").Where(d => (d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("placar-jogo-equipes-nome"))).FirstOrDefault().InnerText)); soccerMatchResult.HomeScore = HtmlAgilityPack.HtmlEntity.DeEntitize(ConvertUTF(scoreData.FirstOrDefault().Descendants("span").Where(d => (d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("placar-jogo-equipes-placar-mandante"))).FirstOrDefault().InnerText)); soccerMatchResult.AwayScore = HtmlAgilityPack.HtmlEntity.DeEntitize(ConvertUTF(scoreData.FirstOrDefault().Descendants("span").Where(d => (d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("placar-jogo-equipes-placar-visitante"))).FirstOrDefault().InnerText)); if (string.IsNullOrWhiteSpace(soccerMatchResult.HomeScore)) { continue; } soccerMatchResultCollection.Add(soccerMatchResult); } TournamentRound tournamentRound = new TournamentRound(); tournamentRound.Round = i; tournamentRound.SoccerMatchResultCollection = soccerMatchResultCollection; tournamentRoundCollection.Add(tournamentRound); } return(tournamentRoundCollection); }
public void init(TournamentRound serverRound, RoundType type) { this.serverRound = serverRound; this.type = type; id = serverRound.getGameID(); players = serverRound.getPlayers(); state = serverRound.getState(); preGameRoomID = serverRound.preGameRoomID; initPlayerSlotTypes(); setPlayerSlots(); initClicks(); initPlayerSlots(); }
private List <Match> GetMatchesForNewDraw(TournamentRound startingRound, int matchesCount, int tournamentId) { var matches = new List <Match>(); var round = startingRound; for (int i = 1; i <= matchesCount; i++) { if (i == matchesCount) // 15 { round = TournamentRound.round6; } else if (i >= matchesCount - 2) // 13,14 matchesCount - 2 { round = TournamentRound.round5; } else if (i >= matchesCount - 6) // 1,2,3,4 matchesCount - 6 { round = TournamentRound.round4; } else if (i >= matchesCount - 14) // 14 { round = TournamentRound.round3; } else if (i >= matchesCount - 30) // 30 { round = TournamentRound.round2; } else { round = TournamentRound.round1; } var match = new Match() { Id = 0, Round = round, TournamentId = tournamentId, MatchEntries = new List <MatchEntry>() { new MatchEntry { }, new MatchEntry { } } }; matches.Add(match); } return(matches); }
public RoundBeatmapEditor(TournamentRound round) { this.round = round; RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; InternalChild = flow = new FillFlowContainer { RelativeSizeAxes = Axes.X, AutoSizeAxes = Axes.Y, Direction = FillDirection.Vertical, ChildrenEnumerable = round.Beatmaps.Select(p => new RoundBeatmapRow(round, p)) }; }
public override CompetitorRanks GenerateResult(int tournamentRunSequence, MatchStrategies.MatchStrategy matchStrategy, List<Competitor> competitors) { // round robin to seed the semifinals TournamentRound roundRobinTR = new TournamentRound(new RrTRS(_numberOfRoundRobinRounds), matchStrategy); CompetitorRanks rrRanks = roundRobinTR.Run(competitors); List<Competitor> rrRankedCompetitors = rrRanks .OrderBy(x => x.Value) .Select(x => x.Key) .ToList<Competitor>(); // semifinals round TournamentRound semifinals5TR = new TournamentRound(new KoSf5PfFiTRS(_winsToClinchKnockoutSemifinalsMatch, _winsToClinchKnockoutFinalsMatch, _winsToClinchKnockoutPetitFinalsMatch), matchStrategy); return semifinals5TR.Run(rrRankedCompetitors); }
private void DisplayTournamentRound(TournamentRound round) { if (round == null) { return; } foreach (TournamentPairing pairing in round.Pairings) { Console.Write(" "); foreach (TournamentTeamScore teamScore in pairing.TeamScores) { Console.Write(" " + teamScore.Team.TeamId.ToString().PadLeft(2)); } Console.Write("\n"); } Console.WriteLine(); }
public override CompetitorRanks GenerateResult(TournamentSimulation.MatchStrategies.MatchStrategy matchStrategy, List<Competitor> competitors) { if (competitors.Count != 4) throw new ArgumentException("Collection count must be 4.", "competitors"); List<TournamentRound> tournamentRounds = new List<TournamentRound>(); // semifinal round TournamentRoundStrategy semifinalTRS = new KoTRS(_winsToClinchSemifinalMatch); TournamentRound semifinalRound = new TournamentRound(semifinalTRS, matchStrategy); semifinalRound.Run(competitors); tournamentRounds.Add(semifinalRound); // petit final round List<Competitor> losers = semifinalRound.Matches .Select(x => x.Loser) .ToList<Competitor>(); TournamentRoundStrategy petitFinalTRS = new KoTRS(_winsToClinchPetitMatch); TournamentRound petitFinalRound = new TournamentRound(petitFinalTRS, matchStrategy); petitFinalRound.Run(losers); tournamentRounds.Add(petitFinalRound); // final round List<Competitor> winners = semifinalRound.Matches .Select(x => x.Winner) .ToList<Competitor>(); TournamentRoundStrategy finalTRS = new KoTRS(_winsToClinchFinalsMatch); TournamentRound finalRound = new TournamentRound(finalTRS, matchStrategy); finalRound.Run(winners); tournamentRounds.Add(finalRound); // return the matches that were run // return the matches that were run List<Match> matches = tournamentRounds .SelectMany(x => x.Matches) .Select(x => x) .ToList<Match>(); Matches = matches; return GetTournamentRoundRanks(); }
private IEnumerable <BORank> GetRoundRankings(TournamentRound round, int roundNumber) { if (round.Pairings.Count != 1) { throw new InvalidTournamentStateException("At least one round has more than one pairing set."); } TournamentPairing pairing = round.Pairings[0]; foreach (var teamScore in pairing.TeamScores) { if (teamScore.Score == null) { yield break; } } int r = 1, lastRank = 1; Score lastScore = null; var ranks = from team in pairing.TeamScores orderby team.Score descending select new BORank() { Team = team.Team, Rank = r++, Score = team.Score, RoundNumber = roundNumber }; foreach (var rank in ranks) { if (lastScore == rank.Score) { rank.Rank = lastRank; } lastScore = rank.Score; lastRank = rank.Rank; yield return(rank); } }
private void CreateRound(TournamentRound rnd, ref Round round) { Platform.Synchronize(); Platform.LogEvent("Creating round ", ConsoleColor.DarkCyan); round = new Round(); round.CompetitionId = Competition.Id; round.Competition = Competition; round.Number = Competition.Rounds.Count; DateTime game_start = Competition.Start.AddDays(Competition.Rounds.Count); Platform.DBManager.Rounds.Add(round); // create games foreach (TournamentPairing pair in rnd.Pairings) { Game game = new Game(); game.Duration = PlatformSettings.GameDuration; game.Start = game_start; game_start = game_start.AddMinutes(5); game.RoundId = round.Id; game.Round = round; game.WinnerId = 1; game.Status = GameStatus.Pending; game.ChatHistoryFile = ""; game.PlayerSleepTime = PlatformSettings.PlayerPause; Platform.DBManager.Games.Add(game); // Create players foreach (TournamentTeamScore team in pair.TeamScores) { Player player = new Player(); player.BotId = team.Team.TeamId; player.GameId = game.Id; player.Game = game; Platform.DBManager.Players.Add(player); } } Platform.DBManager.SaveChanges(); }
private bool CreateNextRound() { if (CurrentRound != null) { CurrentRound.CheckResults(); } if (Teams.Count == 0 && Competition.ParticipantNumber == Competition.Participations.Count) { foreach (Participation part in Competition.Participations) { AddPlayer(part.Bot); } } Manager.Reset(); Manager.LoadState(Teams, Rounds); TournamentRound rd = Manager.CreateNextRound(null); // Finals if (rd == null || rd.Pairings[0].TeamScores.Count == 1) { CurrentRound = null; return(false); } else { Round round = null; CreateRound(rd, ref round); RoundInstance ri = new RoundInstance(Competition, rd, round, this); ExecutedRounds.Add(CurrentRound); CurrentRound = ri; Rounds.Add(CurrentRound.CurrentRound); return(true); } }
public override CompetitorRanks GenerateResult(int tournamentRunSequence, TournamentSimulation.MatchStrategies.MatchStrategy matchStrategy, List<Competitor> competitors) { // round robin to seed the quarterfinals TournamentRound roundRobinTR = new TournamentRound(new RrTRS(_numberOfRoundRobinRounds), matchStrategy); CompetitorRanks rrRanks = roundRobinTR.Run(competitors); List<Competitor> rr1RankedCompetitors = rrRanks .OrderBy(x => x.Value) .Select(x => x.Key) .ToList<Competitor>(); // TODO: move all this complexity to a new TournamentRoundStrategy that includes multiple stages of the knockout round quarterfinals through finals // knockout through finals TournamentRoundStrategy knockoutTRS = new KoTRS(_winsToClinchKnockoutMatch); TournamentRound knockoutTR = new TournamentRound(knockoutTRS, matchStrategy); knockoutTR.Run(rr1RankedCompetitors); List<TournamentRound> knockoutRounds = new List<TournamentRound>(); knockoutRounds.Add(knockoutTR); while (knockoutTR.Matches.Count > 1) { List<Competitor> winningCompetitorsToMoveOn = new List<Competitor>(); foreach (Match match in knockoutTR.Matches) { winningCompetitorsToMoveOn.Add(match.Winner); } knockoutTR = new TournamentRound(knockoutTRS, matchStrategy); knockoutTR.Run(winningCompetitorsToMoveOn); knockoutRounds.Add(knockoutTR); } CompetitorPoints competitorPoints = AccumulatePointsFromTournamentRounds(knockoutRounds); CompetitorRanks ranks = competitorPoints.GetCompetitorRanks(); BreakTiesByRoundRobinRanks(rrRanks, ranks); return ranks; }
protected void ASPxButton1_Click(object sender, EventArgs e) { int numPlayers = 20; int nbrOfTeams = 20 / 2; int rounds = 3; List <Player> players = new List <Player>(); for (int i = 1; i <= numPlayers; i++) { Player player = new Player { Name = "Person " + i.ToString() }; players.Add(player); } Tournament tournament = new Tournament(rounds); ExtensionMethods.Shuffle(players); for (int i = 0; i < rounds; i++) { TournamentRound round = new TournamentRound("Round : " + (i + 1).ToString()); List <Team> teams = TeamGenerator.GenerateTeams(players, nbrOfTeams); round.Teams = teams; round.Matches = MatchGenerator.GenerateMatches(teams, teams.Count / 2); tournament.Rounds.Add(round); } ASPxListBox1.DataSource = tournament.Rounds[0].Matches; ASPxListBox1.TextField = "Name"; ASPxListBox1.DataBind(); ASPxListBox2.DataSource = tournament.Rounds[1].Matches; ASPxListBox2.TextField = "Name"; ASPxListBox2.DataBind(); ASPxListBox3.DataSource = tournament.Rounds[2].Matches; ASPxListBox3.TextField = "Name"; ASPxListBox3.DataBind(); }
public override CompetitorRanks GenerateResult(int tournamentRunSequence, MatchStrategies.MatchStrategy matchStrategy, List<Competitor> competitors) { // round robin to seed the semifinals TournamentRound rrTR = new TournamentRound(new RrTRS(_numberOfRoundRobinRounds), matchStrategy); CompetitorRanks rrRanks = rrTR.Run(competitors); // run single semifinal knockout round TournamentRound koTR = new TournamentRound(new KoTRS(_winsToClinchKnockoutMatch), matchStrategy); CompetitorRanks koRanks = koTR.Run(rrRanks.OrderBy(x => x.Value).Select(x => x.Key).ToList<Competitor>()); // rank the results first by how they did in the semifinals, then by how they did in the round robin var untypedRanks = koRanks.OrderBy(x => x.Value).ThenBy(x => rrRanks[x.Key]); CompetitorRanks ranks = new CompetitorRanks(); int i = 1; foreach (KeyValuePair<Competitor, int> untypedRank in untypedRanks) { ranks.Add(untypedRank.Key, i++); } return ranks; }
private void btnAddGame_Click(object sender, RoutedEventArgs e) { if (itemListView.SelectedIndex == -1) { return; } TournamentRound selectedRound = itemListView.SelectedItem as TournamentRound; brdAddGame.Visibility = Visibility.Visible; // Populate combobox for add games cmbAddGameGames.Items.Clear(); foreach (CKeyValuePair <int, int> plannedGame in selectedRound.PlannedMatches) { Member memberWhite = App.db.Members.Where(x => x.ID == plannedGame.Key).First(); Member memberBlack = App.db.Members.Where(x => x.ID == plannedGame.Val).First(); ComboBoxItem cmbItemNew = new ComboBoxItem(); cmbItemNew.Name = plannedGame.Key + ":" + plannedGame.Val; cmbItemNew.Content = "White " + memberWhite.Name + ", Black " + memberBlack.Name; cmbAddGameGames.Items.Add(cmbItemNew); } }
public override CompetitorRanks GenerateResult(int tournamentRunSequence, MatchStrategies.MatchStrategy matchStrategy, List<Competitor> competitors) { if (competitors.Count % 2 != 0) throw new ArgumentException("Collection count must be even.", "competitors"); // round robin to seed the semifinals TournamentRound rrTR = new TournamentRound(new RrTRS(_numberOfRoundRobinRounds), matchStrategy); CompetitorRanks rrRanks = rrTR.Run(competitors); List<Competitor> rankedCompetitors = rrRanks.OrderBy(x => x.Value).Select(x => x.Key).ToList<Competitor>(); CompetitorRanks ranks = new CompetitorRanks(); // run single knockout round for nearby competitors for (int i = 0; i < competitors.Count / 2; i++) { TournamentRound koTR = new TournamentRound(new KoTRS(_winsToClinchKnockoutMatch), matchStrategy); CompetitorRanks koRanks = koTR.Run(new List<Competitor>() { rankedCompetitors[i * 2], rankedCompetitors[(i * 2) + 1] }); ranks.Add(koRanks.First(x => x.Value == 1).Key, (i * 2) + 1); ranks.Add(koRanks.First(x => x.Value == 2).Key, (i * 2) + 2); } return ranks; }
public void DoubleEliminationTieDisallowed() { IPairingsGenerator pg = new EliminationTournament(2); List <TournamentTeam> teams = new List <TournamentTeam>(CreateTeams(2)); List <TournamentRound> rounds = new List <TournamentRound>(); pg.LoadState(teams, rounds); TournamentRound round = pg.CreateNextRound(null); round.Pairings[0].TeamScores[0].Score = new HighestPointsScore(10); round.Pairings[0].TeamScores[1].Score = new HighestPointsScore(10); rounds.Add(round); try { RunTournament(pg, teams, rounds, false, null); Assert.Fail(); } catch (InvalidTournamentStateException) { return; } }
public void StartTournament(Tournament tournament) { tournament.Contestants.Shuffle(); var paddedNumberOfPlayers = Math.Pow(2, (int)Math.Ceiling((Math.Log(tournament.Contestants.Count) / Math.Log(2)))); var numberOfRounds = (int)(Math.Log(paddedNumberOfPlayers) / Math.Log(2)); var numberOfGamesInARound = paddedNumberOfPlayers / 2; for (int i = 1; i <= numberOfRounds; i++) { TournamentRound tournamentRound = new TournamentRound(i); for (int j = 1; j <= numberOfGamesInARound; j++) { var game = new Game(new GameSetup() { PlayersSetup = PlayersSetup.Individual, RoundsToWin = tournament.TournamentSetup.RoundsToWin, GameType = tournament.TournamentSetup.GameType, BannedCards = tournament.TournamentSetup.BannedCards, DrawFourDrawTwoShouldSkipTurn = tournament.TournamentSetup.DrawFourDrawTwoShouldSkipTurn, MatchingCardStealsTurn = tournament.TournamentSetup.MatchingCardStealsTurn, MaxNumberOfPlayers = 2, Password = tournament.TournamentSetup.Password, ReverseShouldSkipTurnInTwoPlayers = tournament.TournamentSetup.ReverseShouldSkipTurnInTwoPlayers, WildCardCanBePlayedOnlyIfNoOtherOptions = tournament.TournamentSetup.WildCardCanBePlayedOnlyIfNoOtherOptions, CanSeeTeammatesHandInTeamGame = false, DrawAutoPlay = tournament.TournamentSetup.DrawAutoPlay, SpectatorsCanViewHands = tournament.TournamentSetup.SpectatorsCanViewHands, LimitColorChangingCards = tournament.TournamentSetup.LimitColorChangingCards, NumberOfStandardDecks = tournament.TournamentSetup.NumberOfStandardDecks }, tournament.Id); _gameRepository.AddGame(game); var tournamentRoundGame = new TournamentRoundGame(j, game) { Game = { Players = new List <Player>(2) } }; tournamentRound.TournamentRoundGames.Add(tournamentRoundGame); } numberOfGamesInARound /= 2; tournament.TournamentRounds.Add(tournamentRound); } for (int i = 0; i < tournament.TournamentRounds[0].TournamentRoundGames.Count; i++) { tournament.TournamentRounds[0].TournamentRoundGames[i].Game.Players.Add(new Player(tournament.Contestants[i].User, 1) { LeftGame = true }); if (tournament.Contestants.ElementAtOrDefault(tournament.TournamentRounds[0].TournamentRoundGames.Count + i) != null) { tournament.TournamentRounds[0].TournamentRoundGames[i].Game.Players.Add(new Player(tournament.Contestants[tournament.TournamentRounds[0].TournamentRoundGames.Count + i].User, 2) { LeftGame = true }); tournament.TournamentRounds[0].TournamentRoundGames[i].Game.GameLog.Add("Game started. (type /hand in chat for newbie tips)"); tournament.TournamentRounds[0].TournamentRoundGames[i].Game.GameLog.Add("If you need more detailed log info, press the 'Game info' button."); tournament.TournamentRounds[0].TournamentRoundGames[i].Game.GameLog.Add("This is the game log summary. We will display the last 3 entries here."); _gameManager.StartNewGame(tournament.TournamentRounds[0].TournamentRoundGames[i].Game); } else { tournament.TournamentRounds[0].TournamentRoundGames[i].Game.GameEnded = true; tournament.TournamentRounds[0].TournamentRoundGames[i].Game.Players.First().RoundsWonCount = tournament.TournamentSetup.RoundsToWin; UpdateTournament(tournament, tournament.TournamentRounds[0].TournamentRoundGames[i].Game); } } tournament.TournamentStarted = true; }
public void SingleEliminationHandlesOutOfOrderCompetitors() { for (int i = 0; i < 10; i++) { var teamNames = new Dictionary <long, string>(); teamNames[0] = "A"; teamNames[1] = "B"; teamNames[2] = "C"; teamNames[3] = "D"; teamNames[4] = "E"; teamNames[5] = "F"; var teams = (from k in teamNames.Keys orderby k select new TournamentTeam(k, r.Next(1000))).ToList(); var round1 = new TournamentRound( new TournamentPairing( new TournamentTeamScore(teams[0], Score(1)), new TournamentTeamScore(teams[1], Score(2))), new TournamentPairing( new TournamentTeamScore(teams[2], Score(3)), new TournamentTeamScore(teams[3], Score(4)))); var round2 = new TournamentRound( new TournamentPairing( new TournamentTeamScore(teams[1], Score(5)), new TournamentTeamScore(teams[3], Score(6)))); var round3 = new TournamentRound( new TournamentPairing( new TournamentTeamScore(teams[4], Score(7)), new TournamentTeamScore(teams[5], Score(8)))); var round4 = new TournamentRound( new TournamentPairing( new TournamentTeamScore(teams[5], Score(9)), new TournamentTeamScore(teams[3], Score(10)))); var rounds = (new[] { round1, round2, round3, round4 }).ToList(); IPairingsGenerator pg = new EliminationTournament(1); pg.LoadState(teams, rounds); Assert.IsNull(pg.CreateNextRound(null)); DisplayTournamentRankings(pg.GenerateRankings()); } for (int i = 0; i < 10; i++) { var teamNames = new Dictionary <long, string>(); teamNames[0] = "A"; teamNames[1] = "B"; teamNames[2] = "C"; teamNames[3] = "D"; teamNames[4] = "E"; teamNames[5] = "F"; var teams = (from k in teamNames.Keys orderby k select new TournamentTeam(k, r.Next(1000))).ToList(); var round1 = new TournamentRound( new TournamentPairing( new TournamentTeamScore(teams[0], Score(1)), new TournamentTeamScore(teams[1], Score(2))), new TournamentPairing( new TournamentTeamScore(teams[2], Score(3)), new TournamentTeamScore(teams[3], Score(4)))); var round2 = new TournamentRound( new TournamentPairing( new TournamentTeamScore(teams[1], Score(5)), new TournamentTeamScore(teams[4], Score(6)))); var round3 = new TournamentRound( new TournamentPairing( new TournamentTeamScore(teams[3], Score(7)), new TournamentTeamScore(teams[5], Score(8)))); var round4 = new TournamentRound( new TournamentPairing( new TournamentTeamScore(teams[4], Score(9)), new TournamentTeamScore(teams[5], Score(10)))); var rounds = (new[] { round1, round2, round3, round4 }).ToList(); IPairingsGenerator pg = new EliminationTournament(1); pg.LoadState(teams, rounds); Assert.IsNull(pg.CreateNextRound(null)); DisplayTournamentRankings(pg.GenerateRankings()); } }
/// <summary> /// /// </summary> /// <param name="tournamentId"></param> /// <param name="isPerformanceRound">if the round is for seeding, otherwise its for the actual tournament.</param> /// <returns></returns> public static bool StartNextRound(Guid tournamentId, bool isPerformanceRound) { try { var dc = new ManagementContext(); var tourny = GetTournament(tournamentId); TournamentApi.IPairingsGenerator pg = null; TournamentTypeEnum tempType = tourny.TournamentType; if (isPerformanceRound) tempType = tourny.TouramentTypeForSeedingEnum; switch (tempType) { case TournamentTypeEnum.Boil_Off: pg = new BoilOffPairingsGenerator(); break; case TournamentTypeEnum.Round_Robin: pg = new RoundRobinPairingsGenerator(); break; case TournamentTypeEnum.Round_Robin_Pool_Play: pg = new RoundRobinPairingsGenerator(true); break; case TournamentTypeEnum.Double_Elimination: pg = new EliminationTournament(2); break; case TournamentTypeEnum.Single_Elimination: pg = new EliminationTournament(1); break; } if (isPerformanceRound) pg.LoadState(tourny.TeamsForTournamentApi, tourny.TournamentRoundsApiForSeeding); else pg.LoadState(tourny.TeamsForTournamentApi, tourny.TournamentRoundsApi); var tempRound = pg.CreateNextRound(null); bool tournamentFinished = (tempRound == null) && (tourny.TournamentRoundsApi.Count > 1); if (tournamentFinished) return true; var tournament = dc.GameTournaments.Where(x => x.TournamentId == tourny.Id).FirstOrDefault(); TournamentRound newRound = new TournamentRound(); if (isPerformanceRound) newRound.RoundNumber = tourny.TournamentRoundsApiForSeeding.Count + 1; else newRound.RoundNumber = tourny.TournamentRoundsApi.Count + 1; newRound.Tournament = tournament; var teams = tournament.Teams.ToList(); foreach (var pairing in tempRound.Pairings) { var newPairing = new TournamentPairing { Round = newRound, GroupId = pairing.GroupId }; for (int i = 0; i < pairing.TeamScores.Count; i++) { var newTeamPairing = new TournamentPairingTeam { Team = teams.Where(t => t.TeamId == pairing.TeamScores[i].Team.TeamId).FirstOrDefault(), Pairing = newPairing, Score = 0 }; newPairing.Teams.Add(newTeamPairing); //dc.TournamentTeams.Add(newTeamPairing); } newRound.Pairings.Add(newPairing); } //} if (isPerformanceRound) tournament.SeedingRounds.Add(newRound); else tournament.Rounds.Add(newRound); int c = dc.SaveChanges(); return c > 0; } catch (Exception exception) { ErrorDatabaseManager.AddException(exception, exception.GetType()); } return false; }
public RoundBeatmapRow(TournamentRound team, RoundBeatmap beatmap) { Model = beatmap; Margin = new MarginPadding(10); RelativeSizeAxes = Axes.X; AutoSizeAxes = Axes.Y; Masking = true; CornerRadius = 5; InternalChildren = new Drawable[] { new Box { Colour = OsuColour.Gray(0.2f), RelativeSizeAxes = Axes.Both, }, new FillFlowContainer { Margin = new MarginPadding(5), Padding = new MarginPadding { Right = 160 }, Spacing = new Vector2(5), Direction = FillDirection.Horizontal, AutoSizeAxes = Axes.Both, Children = new Drawable[] { new SettingsNumberBox { LabelText = "Beatmap ID", RelativeSizeAxes = Axes.None, Width = 200, Current = beatmapId, }, new SettingsTextBox { LabelText = "Mods", RelativeSizeAxes = Axes.None, Width = 200, Current = mods, }, drawableContainer = new Container { Size = new Vector2(100, 70), }, } }, new DangerousSettingsButton { Anchor = Anchor.CentreRight, Origin = Anchor.CentreRight, RelativeSizeAxes = Axes.None, Width = 150, Text = "Delete Beatmap", Action = () => { Expire(); team.Beatmaps.Remove(beatmap); }, } }; }
public override CompetitorRanks GenerateResult(MatchStrategies.MatchStrategy matchStrategy, List<Competitor> competitors) { if (competitors.Count != 5) throw new ArgumentException("Collection count must be 5.", "competitors"); List<TournamentRound> tournamentRounds = new List<TournamentRound>(); // petit final qualifier round List<Competitor> petitQualifiers = new List<Competitor>(); petitQualifiers.Add(competitors[3]); petitQualifiers.Add(competitors[4]); TournamentRoundStrategy knockoutTRS_petitQualifier = new KoTRS(_winsToClinchSemifinalMatch); TournamentRound petitQualifierRound = new TournamentRound(knockoutTRS_petitQualifier, matchStrategy); petitQualifierRound.Run(petitQualifiers); tournamentRounds.Add(petitQualifierRound); // final qualifier round List<Competitor> finalsQualifiers = new List<Competitor>(); finalsQualifiers.Add(competitors[1]); finalsQualifiers.Add(competitors[2]); TournamentRoundStrategy knockoutTRS_finalQualifier = new KoTRS(_winsToClinchSemifinalMatch); TournamentRound finalQualifierRound = new TournamentRound(knockoutTRS_finalQualifier, matchStrategy); finalQualifierRound.Run(finalsQualifiers); tournamentRounds.Add(finalQualifierRound); // petit final round List<Competitor> petitFinalsCompetitors = petitQualifierRound.Matches .Select(x => x.Winner) .Union(finalQualifierRound.Matches .Select(x => x.Loser)) .ToList<Competitor>(); TournamentRoundStrategy petitFinalTRS = new KoTRS(_winsToClinchPetitMatch); TournamentRound petitFinalRound = new TournamentRound(petitFinalTRS, matchStrategy); petitFinalRound.Run(petitFinalsCompetitors); tournamentRounds.Add(petitFinalRound); // final round List<Competitor> finalsCompetitors = finalQualifierRound.Matches .Select(x => x.Winner) .ToList<Competitor>(); finalsCompetitors.Add(competitors[0]); TournamentRoundStrategy finalTRS = new KoTRS(_winsToClinchFinalsMatch); TournamentRound finalRound = new TournamentRound(finalTRS, matchStrategy); finalRound.Run(finalsCompetitors); tournamentRounds.Add(finalRound); // return the matches that were run List<Match> matches = tournamentRounds .SelectMany(x => x.Matches) .Select(x => x) .ToList<Match>(); Matches = matches; return GetTournamentRoundRanks(); }
public override CompetitorRanks GenerateResult(int tournamentRunSequence, MatchStrategies.MatchStrategy matchStrategy, List<Competitor> competitors) { if (competitors.Count != 8) throw new ArgumentException("Collection count must be 8.", "competitors"); // round robin to seed 2 separate round robins TournamentRound rr1 = new TournamentRound(new RrTRS(_numberOfRr1Rounds), matchStrategy); CompetitorRanks rr1Ranks = rr1.Run(competitors); List<Competitor> rrACompetitors = rr1Ranks .OrderBy(x => x.Value) .Take(4) .Select(x => x.Key) .ToList<Competitor>(); List<Competitor> rrBCompetitors = rr1Ranks .OrderBy(x => x.Value) .Skip(4) .Take(4) .Select(x => x.Key) .ToList<Competitor>(); // round robin to determine 1, 2, 3 TournamentRound rrA = new TournamentRound(new RrTRS(_numberOfRr2Rounds), matchStrategy); CompetitorRanks rrARanks = rrA.Run(rrACompetitors); // round robin to determine 4 TournamentRound rrB = new TournamentRound(new RrTRS(_numberOfRr2Rounds), matchStrategy); CompetitorRanks rrBRanks = rrB.Run(rrBCompetitors); // finals List<Competitor> finalsCompetitors = rrARanks .OrderBy(x => x.Value) .Take(2) .Select(x => x.Key) .ToList<Competitor>(); TournamentRound finals = new TournamentRound(new KoTRS(_winsToClinchFinalMatch), matchStrategy); CompetitorRanks finalsRanks = finals.Run(finalsCompetitors); // petit finals List<Competitor> petitFinalsCompetitors = rrARanks .OrderBy(x => x.Value) .Skip(2) .Take(1) .Select(x => x.Key) .ToList<Competitor>(); Competitor rrBWinner = rrBRanks .OrderBy(x => x.Value) .Take(1) .Select(x => x.Key) .First(); petitFinalsCompetitors.Add(rrBWinner); TournamentRound petitFinals = new TournamentRound(new KoTRS(_winsToClinchPetitFinalMatch), matchStrategy); CompetitorRanks petitFinalsRanks = petitFinals.Run(petitFinalsCompetitors); // consolation round List<Competitor> consolationCompetitors = rrBRanks .OrderBy(x => x.Value) .Skip(1) .Select(x => x.Key) .ToList<Competitor>(); Competitor rrALoser = rrARanks .OrderBy(x => x.Value) .Skip(3) .Take(1) .Select(x => x.Key) .First(); consolationCompetitors.Add(rrALoser); TournamentRound consolationRound = new TournamentRound(new RrTRS(_numberOfRr3Rounds), matchStrategy); CompetitorRanks consolationRanks = consolationRound.Run(consolationCompetitors); CompetitorRanks ranks = new CompetitorRanks(); int i = 1; foreach (var rank in finalsRanks.OrderBy(x => x.Value)) { ranks.Add(rank.Key, i++); } foreach (var rank in petitFinalsRanks.OrderBy(x => x.Value)) { ranks.Add(rank.Key, i++); } foreach (var rank in consolationRanks.OrderBy(x => x.Value)) { ranks.Add(rank.Key, i++); } return ranks; }
private IEnumerable<BORank> GetRoundRankings(TournamentRound round, int roundNumber) { if (round.Pairings.Count != 1) { throw new InvalidTournamentStateException("At least one round has more than one pairing set."); } TournamentPairing pairing = round.Pairings[0]; foreach (var teamScore in pairing.TeamScores) { if (teamScore.Score == null) { yield break; } } int r = 1, lastRank = 1; Score lastScore = null; var ranks = from team in pairing.TeamScores orderby team.Score descending select new BORank() { Team = team.Team, Rank = r++, Score = team.Score, RoundNumber = roundNumber }; foreach (var rank in ranks) { if (lastScore == rank.Score) { rank.Rank = lastRank; } lastScore = rank.Score; lastRank = rank.Rank; yield return rank; } }
public static void Postfix(TournamentRound __instance) { MissionOnTickPatch.Cleanup(); }
public void BreakTiesTest() { var competitors = Helpers.CompetitorListHelper.GetStandardCompetitors(6); var round = new TournamentRound(new RrTRS(), new SimpleRandomMs()); round.Run(competitors); var tournamentRoundRanks = new CompetitorRanks { { competitors[0], 1 }, { competitors[1], 2 }, { competitors[2], 2 }, { competitors[3], 4 }, { competitors[4], 4 }, { competitors[5], 4 } }; RrTRS_Accessor.BreakTies(tournamentRoundRanks, round.Matches); Assert.IsTrue(tournamentRoundRanks[competitors[0]] < tournamentRoundRanks[competitors[1]]); Assert.IsTrue(tournamentRoundRanks[competitors[0]] < tournamentRoundRanks[competitors[2]]); Assert.IsTrue(tournamentRoundRanks[competitors[1]] < tournamentRoundRanks[competitors[3]]); Assert.IsTrue(tournamentRoundRanks[competitors[1]] < tournamentRoundRanks[competitors[4]]); Assert.IsTrue(tournamentRoundRanks[competitors[1]] < tournamentRoundRanks[competitors[5]]); Assert.IsTrue(tournamentRoundRanks[competitors[2]] < tournamentRoundRanks[competitors[3]]); Assert.IsTrue(tournamentRoundRanks[competitors[2]] < tournamentRoundRanks[competitors[4]]); Assert.IsTrue(tournamentRoundRanks[competitors[2]] < tournamentRoundRanks[competitors[5]]); }
void formatTable(ref string data, Tags tag, TournamentRound round, Tournament tournament, int roundNumber) { var matchNumber = 1; foreach (var match in round.Matches) { var player1 = Config.Settings.GetPlayer(match.Players[0]); var player2 = match.Players.Count > 1 ? Config.Settings.GetPlayer(match.Players[1]) : null; data += tag.rowStart + tag.cellStart + roundNumber + tag.cellEnd + tag.cellStart + matchNumber++ + tag.cellEnd + tag.cellStart + player1.Name + tag.cellEnd; if (chkShowFactions.Checked) data += tag.cellStart + tournament.PlayerFaction[player1.ID] + tag.cellEnd; Scores scores; scores.vps = match.Results[player1.ID].VictoryPoints; scores.tps = match.Results[player1.ID].TournamentPoints; scores.diff = match.Results[player1.ID].Differential; formatScores(ref data, ref tag, tournament.Format, scores); if (player2 != null) { data += tag.cellStart + player2.Name + tag.cellEnd; if (chkShowFactions.Checked) data += tag.cellStart + tournament.PlayerFaction[player2.ID] + tag.cellEnd; scores.vps = match.Results[player2.ID].VictoryPoints; scores.tps = match.Results[player2.ID].TournamentPoints; scores.diff = match.Results[player2.ID].Differential; formatScores(ref data, ref tag, tournament.Format, scores); } else data += (tag.cellStart + "BYE ROUND" + tag.cellEnd + tag.cellStart + tag.cellEnd + tag.cellStart + tag.cellEnd + tag.cellStart + tag.cellEnd); data += tag.rowEnd + "\r\n"; } }
private void formatTable(ref string data, MonospacedValues monoValues, TournamentRound round, Tournament tournament, int roundNumber) { var matchNumber = 1; foreach (var match in round.Matches) { var player1 = Config.Settings.GetPlayer(match.Players[0]); var player2 = match.Players.Count > 1 ? Config.Settings.GetPlayer(match.Players[1]) : null; data += roundNumber.ToString().PadRight(monoValues.roundLength) + matchNumber++.ToString().PadRight(monoValues.tableLength) + player1.Name.PadRight(monoValues.playerNameLength); if (chkShowFactions.Checked) data += tournament.PlayerFaction[player1.ID].ToString().PadRight(monoValues.factionLength); Scores scores; scores.vps = match.Results[player1.ID].VictoryPoints; scores.tps = match.Results[player1.ID].TournamentPoints; scores.diff = match.Results[player1.ID].Differential; formatScores(ref data, ref monoValues, tournament.Format, scores); if (player2 != null) { data += player2.Name.PadRight(monoValues.playerNameLength); if (chkShowFactions.Checked) data += tournament.PlayerFaction[player2.ID].ToString().PadRight(monoValues.factionLength); scores.vps = match.Results[player2.ID].VictoryPoints; scores.tps = match.Results[player2.ID].TournamentPoints; scores.diff = match.Results[player2.ID].Differential; formatScores(ref data, ref monoValues, tournament.Format, scores); } else data += ("BYE ROUND"); data += "\r\n"; } }
public override CompetitorRanks GenerateResult(int tournamentRunSequence, MatchStrategy matchStrategy, List<Competitor> competitors) { TournamentRound tournamentRound = new TournamentRound(new RrTRS(_numberOfRounds, _winsToClinchMatch), matchStrategy); return tournamentRound.Run(competitors); }
/// <summary> /// A very complicated method to generate tournament brackets. This is currently limited to PC and tablet builds of the Chess Club Manager due to unknown compatibility issues /// </summary> private void generateTournamentBrackets() { // Get the tournament and clear the grid ready for use Tournament trn = itemListView.SelectedItem as Tournament; Grid grd = grdTournamentBracket; grd.RowDefinitions.Clear(); grd.ColumnDefinitions.Clear(); grd.Children.Clear(); // Create rows and columns // Formula for number of rows is number of members, but you subtract one if it's even (as a bye does not need it's own space) int rowCount; if (trn.ContestantIDs.Count % 2 == 0) { rowCount = trn.ContestantIDs.Count - 1; } else { rowCount = trn.ContestantIDs.Count; } // Formula for number of columns is one less than the double of the rounded up log2 of the number of contestants int colCount = (int)Math.Ceiling(Math.Log(trn.ContestantIDs.Count, 2)) * 2 - 1; // Now create the setup for (int i = 0; i < rowCount; i++) { // Create rowCount row definitions with height 70 and put them in the grid RowDefinition rd = new RowDefinition(); rd.Height = new GridLength(70); grd.RowDefinitions.Add(rd); } for (int i = 0; i < colCount; i++) { // Create colCount col definitions with width 120 and put them in the grid ColumnDefinition cd = new ColumnDefinition(); cd.Width = new GridLength(120); grd.ColumnDefinitions.Add(cd); } // Now we start filling in the grid // Initialize variables for use in the loop TournamentRound lastRound = null; TournamentRound tRound = null; List <Game> lastOrderedGames = null; List <Game> orderedGames = null; List <KeyValuePair <int, int> > lastYPositions = new List <KeyValuePair <int, int> >(); List <KeyValuePair <int, int> > yPositions = new List <KeyValuePair <int, int> >(); if (trn.TournamentRounds.Count < 2) { // We need at least two rounds to generate any useful graphics return; } for (int x = 0; x < colCount; x++) { // For the first round we need a more complicated sorting algorithm to sort out the next round if (x == 0) { tRound = trn.TournamentRounds[0]; orderedGames = new List <Game>(); // Try to order games in pairs corresponding to who plays eachother next round. Debug.WriteLine("SORTING GAMES X: " + x); List <Game> copiedGames = tRound.Games.ToList(); // Add them to these lists depending on whether the game contributed to a game in the next round // where two people from this round participated (Alternatively it might only be this one and the // other person might have received a bye at the start) List <Game> oneAdvance = new List <Game>(); List <Game> twoAdvance = new List <Game>(); foreach (Game game in copiedGames) { // We check if they participate in the next round Member successor; if (game.Winner == "Black") { successor = game.BlackPlayer; } else { successor = game.WhitePlayer; } IEnumerable <Game> successorGames = trn.TournamentRounds[(x / 2) + 1].Games.Where(lx => (lx.WhitePlayerID == successor.ID || lx.BlackPlayerID == successor.ID)); if (!successorGames.Any()) { // No successor games; skip ahead in loop continue; } // Find the other player in the game Game successorGame = successorGames.First(); Member otherPlayer; if (successorGame.BlackPlayerID == successor.ID) { otherPlayer = successorGame.WhitePlayer; } else { otherPlayer = successorGame.BlackPlayer; } // Check if the other player was in this round if (tRound.ContestantIDs.Contains(otherPlayer.ID)) { // This game has a legacy of two successors twoAdvance.Add(game); } else { // This successor is the only successor of this round who played in their game next round oneAdvance.Add(game); } } // Now we order the two successor games so that their order pairs them up List <Game> twoAdvanceSorted = new List <Game>(); foreach (Game game in twoAdvance) { if (twoAdvanceSorted.Contains(game)) { // If we've already sorted this game jump to the next one continue; } // Find winner Member winner; if (game.Winner == "Black") { winner = game.BlackPlayer; } else { winner = game.WhitePlayer; } // Find the game they participated in in the next round Game nextRoundGame = trn.TournamentRounds[x / 2 + 1].Games.Where(lx => (lx.BlackPlayerID == winner.ID || lx.WhitePlayerID == winner.ID)).First(); Member otherWinner; // Find the other player in that game if (nextRoundGame.BlackPlayerID == winner.ID) { otherWinner = nextRoundGame.WhitePlayer; } else { otherWinner = nextRoundGame.BlackPlayer; } // Find the other game they played in Game game2 = tRound.Games.Where(xl => (xl.WhitePlayerID == otherWinner.ID || xl.BlackPlayer.ID == otherWinner.ID)).First(); // Put them in order in the twoAdvanceSorted list to keep double advances together twoAdvanceSorted.Add(game); twoAdvanceSorted.Add(game2); } // Now we put twoAdvanceSorted and oneAdvance into the single orderedGames list // To do this we need to pad the twoAdvanceSorted with oneAdvances so that // all the paired games end up together. int numBefore = oneAdvance.Count / 2; if (Math.Floor((double)numBefore) > 0) { for (int i = 0; i < numBefore; i++) { // Add them to the ordered list and remove them from the oneAdvance list orderedGames.Add(oneAdvance.First()); oneAdvance.Remove(oneAdvance.First()); } } // Dump in all values from the twoAdvance list // We use a foreach loop to preserve order orderedGames.AddRange(twoAdvanceSorted); // And finally throw in any remaining oneAdvance games orderedGames.AddRange(oneAdvance); } else if (x % 2 == 0) { // We must look at the order of the last column's games and determine from that what order we put this column's games in // using lastOrderedGames tRound = trn.TournamentRounds[x / 2]; orderedGames = tRound.Games.ToList(); } else { tRound = null; } for (int y = 0; y < rowCount; y++) { // x, y represent a grid position if (x % 2 == 0) { // If we're on an even row, we put in games (Odd rows are for connecting lines) int round = x / 2; // Check how many rows the games require int numRows = 2 * tRound.GameIDs.Count - 1; // Now interpolate how far spacing we should give int spacing = (rowCount - numRows) / 2; // Now check if we're not in the spacing area if (y >= Math.Floor((double)spacing) && y < Math.Ceiling((double)spacing) + numRows) { // Now check how far into the non-spacing area we are int depth = y - (int)Math.Floor((double)spacing); // Every two cells we want a game if (depth % 2 == 0) { // We can actually get the game details using depth / 2 and checking the game index int gameNumber = depth / 2; Game game = orderedGames[gameNumber]; // Set up a textblock to represent this game TextBlock b = new TextBlock(); b.SetValue(Grid.ColumnProperty, x); b.SetValue(Grid.RowProperty, y); b.TextWrapping = TextWrapping.Wrap; b.HorizontalAlignment = HorizontalAlignment.Center; b.VerticalAlignment = VerticalAlignment.Center; b.TextAlignment = TextAlignment.Center; b.Foreground = new SolidColorBrush(Colors.Black); int winnerID; if (game.Winner == "Black") { winnerID = game.BlackPlayerID; } else { winnerID = game.WhitePlayerID; } // Add the game to the yPositions to keep track of it for future round ordering yPositions.Add(new KeyValuePair <int, int>(winnerID, y)); // Depending on if white or black won we swap the formatting around if (game.Winner == "Black") { b.Text = game.BlackPlayer.Name + " won against " + game.WhitePlayer.Name + "."; } else { b.Text = game.WhitePlayer.Name + " won against " + game.BlackPlayer.Name + "."; } // Form a new rectangle as a sort of background for the game; initialize with basic properties Rectangle rect = new Rectangle(); rect.Fill = new SolidColorBrush(Colors.CornflowerBlue); rect.HorizontalAlignment = HorizontalAlignment.Center; rect.VerticalAlignment = VerticalAlignment.Center; rect.Width = 120; rect.Height = 80; rect.SetValue(Grid.ColumnProperty, x); rect.SetValue(Grid.RowProperty, y); grd.Children.Add(rect); grd.Children.Add(b); // If they played in the last round if (lastRound != null && lastYPositions.Where(xl => xl.Key == game.BlackPlayerID).Count() > 0) { // Find the last game this player was in int yO = lastYPositions.First(xl => xl.Key == game.BlackPlayerID).Value; // Draw a line between the two games Line line = new Line(); line.X1 = 0; line.X2 = 120; line.SetValue(Grid.RowSpanProperty, Math.Abs(y - yO) + 1); line.SetValue(Grid.ColumnProperty, x - 1); line.SetValue(Grid.RowProperty, y); line.Stroke = new SolidColorBrush(Colors.Yellow); // Slightly complicated math to determine the Y positions of the line. // Essentially rowspan must be considered as increasing the height by 70 each row // thus 35 is halfway // and as a result of this the difference between yO and y add 1 is // how many rows difference, and multiply that by 70 to get the pixels difference // then take 35 to make it aligned centrally. // If yO < y, this must be done the other way around since Y1 is going to be above Y2 if (yO > y) { line.Y1 = 70 * (Math.Abs(yO - y) + 1) - 35; line.Y2 = 35; } else { line.SetValue(Grid.RowProperty, yO); line.Y1 = 35; line.Y2 = 70 * (Math.Abs(yO - y) + 1) - 35; } grd.Children.Add(line); } if (lastRound != null && lastYPositions.Where(xl => xl.Key == game.WhitePlayerID).Count() > 0) { // Find the last game this player was in int yO = lastYPositions.Where(xl => xl.Key == game.WhitePlayerID).First().Value; // Draw a line Line line = new Line(); line.X1 = 0; line.X2 = 120; line.SetValue(Grid.RowSpanProperty, Math.Abs(y - yO) + 1); line.SetValue(Grid.ColumnProperty, x - 1); line.SetValue(Grid.RowProperty, y); line.Stroke = new SolidColorBrush(Colors.Yellow); // Slightly complicated math to determine the Y positions of the line. // Essentially rowspan must be considered as increasing the height by 70 each row // thus 35 is halfway // and as a result of this the difference between yO and y add 1 is // how many rows difference, and multiply that by 70 to get the pixels difference // then take 35 to make it aligned centrally. // If yO < y, this must be done the other way around since Y1 is going to be above Y2 if (yO > y) { line.Y1 = 70 * (Math.Abs(yO - y) + 1) - 35; line.Y2 = 35; } else { line.SetValue(Grid.RowProperty, yO); line.Y1 = 35; line.Y2 = 70 * (Math.Abs(yO - y) + 1) - 35; } grd.Children.Add(line); } } } } } // If we're in a game row we update the old yPositions with the new one and clear the new one if (x % 2 == 0) { lastYPositions = yPositions; yPositions = new List <KeyValuePair <int, int> >(); } // Now set the lastRound variable ready for the next round if (tRound != null) { lastRound = tRound; lastOrderedGames = orderedGames; } } }