// [TestMethod] // [TestCategory("Attachment")] public void CreateAttachment() { var name = "TournamentTest" + Utilities.RandomName(); var tournamentParameter = new TournamentCreateParameters { AcceptAttachments = true }; this.tournament = this.target.TournamentCreate(name, TournamentType.DoubleElimination, name, tournamentParameter); Assert.IsTrue(this.tournament.AcceptAttachments); Debug.WriteLine("Created: ({0}){1} Url:{2} subdomain:{3}", this.tournament.Id, this.tournament.Name, this.tournament.Url, this.tournament.Subdomain); var participant1 = this.target.ParticipantCreate(this.tournament, new ParticipantCreateParameters { Name = Utilities.RandomName() }); var participant2 = this.target.ParticipantCreate(this.tournament, new ParticipantCreateParameters { Name = Utilities.RandomName() }); this.tournament = this.target.TournamentStart(this.tournament); var matches = this.target.MatchIndex(this.tournament); var match1 = matches.First(); var parameters = new AttachmentCreateParameters { Description = "This is just another description", Asset = "The quick brown fox jumps over the lazy dog." }; Debug.WriteLine("Attachment Create request"); var attachment = this.target.AttachmentCreate(this.tournament, match1.Id, parameters); Assert.IsNotNull(attachment); }
public static void Tally(Stream inStream, Stream outStream) { var tournament = new Tournament(); var encoding = new System.Text.UTF8Encoding(); var inReader = new StreamReader(inStream, encoding); for (var line = inReader.ReadLine(); line != null; line = inReader.ReadLine()) { var parts = line.Trim().Split(';'); if (parts.Length != 3) continue; Outcome outcome; switch (parts[2].ToLower()) { case "loss": outcome = Outcome.LOSS; break; case "draw": outcome = Outcome.DRAW; break; case "win": outcome = Outcome.WIN; break; default: continue; } tournament.AddResult(parts[0], parts[1], outcome); } var outWriter = new StreamWriter(outStream, encoding); tournament.WriteResults(outWriter); }
public TournamentTimeGump(Mobile from, Tournament tournament) : this() { caller = from; t = tournament; TimeInfo(); }
public TournamentJson(Tournament tournament) { Name = tournament.Name; StartDate = tournament.StartDate; EndDate = tournament.EndDate; StartDateDisplay = tournament.StartDateDisplay; EndDateDisplay = tournament.EndDateDisplay; Id = tournament.Id; TournamentWebsite = tournament.TournamentWebsite; Country = tournament.Country; CountryId = tournament.CountryId; State = tournament.State; Address = tournament.Address; Address2 = tournament.Address2; City = tournament.City; ZipCode = tournament.ZipCode; Games = tournament.Games; Photos = tournament.Photos; TournamentClass = tournament.TournamentClass; TournamentClassType = tournament.TournamentClass.ToString(); AllSkaters = tournament.AllSkaters; TournamentRounds = tournament.TournamentRounds; Rankings = tournament.Rankings; RankingsPerformance = tournament.RankingsForSeededRounds; TournamentRoundsPerformance = tournament.TournamentRoundsForSeedingGameplay; TeamsForTournament = tournament.TeamsForTournament; RenderBracketUrl = tournament.RenderUrl; RenderPerformanceBracketUrl = tournament.RenderPerformanceUrl; TournamentType = tournament.TournamentType.ToString(); TournamentTypePerformance = tournament.TouramentTypeForSeedingEnum.ToString(); }
public frmTournamentOptions(Tournament ToEdit = null, bool isNew = false) { InitializeComponent(); if (ToEdit != null) _tournament = ToEdit; IsNew = isNew; txtName.Text = Tournament.Name; txtLocation.Text = Tournament.Location; txtForumURL.Text = Tournament.ForumURL; dtDate.Value = Tournament.Date; numStones.Value = Tournament.Soulstones; numRounds.Value = Tournament.TotalRounds; numLength.Value = Tournament.RoundTimeLimit; chkAvoidSameRegion.Checked = Tournament.TryToAvoidSameRegionMatches; chkAvoidSameFaction.Checked = Tournament.TryToAvoidSameFactionMatches; cmbType.SelectedItem = Tournament.IsBrawl ? "Brawl" : "Scrap"; // Populate combo boxes. FillComboBoxes(); cmbFormat.SelectedItem = Tournament.Format.ToString(); cmbCrew.SelectedItem = Tournament.Crews.ToString(); cmbStrategy.SelectedItem = Tournament.Strategy.ToString(); cmbSchemes.SelectedItem = Tournament.Schemes.ToString(); cmbNumbering.SelectedIndex = (int)Tournament.TableNumbering; }
public TournamentArenasGump(Mobile from, Tournament tournament, int page) : this() { caller = from; t = tournament; TypeInfo(page); }
public void Initialize() { var username = Properties.Settings.Default.username; var apiKey = Properties.Settings.Default.apiKey; this.randomName = "TommeAPITest" + Utilities.RandomName(); Debug.WriteLine(string.Format("Initializing with name {0}", this.randomName)); this.target = new ChallongeV1(username, apiKey); this.tournamentUnderTest = this.target.TournamentCreate(this.randomName, TournamentType.SingleElimination, this.randomName); }
public ActionResult Create(Tournament tournament) { if (!ModelState.IsValid) return View(tournament); var typeList = new List<CheckBoxListInfo>(); foreach (TournamentType type in TournamentType.All()) { typeList.Add(new CheckBoxListInfo(type.TournamentTypeID.ToString(), type.TournamentTypeName, Tournament_TournamentType.Exists(tournament.EventID, type.TournamentTypeID))); } ViewData["types"] = typeList; tournament.Create(); return RedirectToAction("Index"); }
public void BulkAddParticipants() { var tournamentName = Utilities.RandomName(); this.tournament = this.target.TournamentCreate(tournamentName, TournamentType.SingleElimination, tournamentName); var param = new ParticipantBulkAddParameters(); string name1 = Utilities.RandomName(); string name2 = Utilities.RandomName(); param.Add(new BulkParticipant { Name = name1 }); param.Add(new BulkParticipant { Name = name2 }); var result = this.target.ParticipantBulkAdd(this.tournament, param); Assert.IsTrue(result.Any(p => p.Name == name1)); Assert.IsTrue(result.Any(p => p.Name == name1)); }
private void btnStartTournament_Click(object sender, RoutedEventArgs e) { Tourny = new Tournament(); foreach (string Player in listPlayers.Items) { Tourny.Players.Add(new Player() {Name=Player}); } Tourny.GenerateRoundMatchups(); foreach (Match match in Tourny.CurrentRound.Matches) { //listCurrentRound.Items.Add(match.Player1.Name + " Vs. " + match.Player2.Name); } }
public void AddClubs(Tournament tournament, List<TennisClub> clubs) { var currentLinks = _tournamentClubsRepository.Table.Where(tc => tc.Tournament.Id == tournament.Id); foreach (var club in clubs) { var existClub = currentLinks.FirstOrDefault(c => c.Id == club.Id); if (existClub == null) { _tournamentClubsRepository.Insert(new TournamentClub { Tournament = tournament, Club = club }); } } }
public void FinalizaTournament() { var name = "TournamentTest" + Utilities.RandomName(); this.tournament = this.target.TournamentCreate(name, TournamentType.SingleElimination, name); var participant1 = this.target.ParticipantCreate(this.tournament, new ParticipantCreateParameters { Name = Utilities.RandomName() }); var participant2 = this.target.ParticipantCreate(this.tournament, new ParticipantCreateParameters { Name = Utilities.RandomName() }); this.target.TournamentStart(this.tournament); var matches = this.target.MatchIndex(this.tournament, new MatchIndexParameters { State = MatchIndexParameters.MatchIndexState.open }); var match = matches[0]; this.target.MatchUpdate(this.tournament, match.Id, new MatchUpdateParameters { ScoresCsv = "1-0", WinnerId = participant1.Id }); var finalTournament = this.target.TournamentFinalize(this.tournament); Assert.AreEqual(TournamentState.complete, finalTournament.Tournamentstate); Assert.IsNotNull(finalTournament.CompletedAt); Utilities.AssertDateTimeWithin(DateTime.Now, finalTournament.CompletedAt.Value, new TimeSpan(hours: 0, minutes: 1, seconds: 0)); }
public void CreateOptionalParameters() { var tournamentName = Utilities.RandomName(); this.tournament = this.target.TournamentCreate(tournamentName, TournamentType.SingleElimination, tournamentName); var participant1Parameters = new ParticipantCreateParameters { Seed = 1, Name = Utilities.RandomName() }; var participant1 = this.target.ParticipantCreate(this.tournament, participant1Parameters); var participant2Parameters = new ParticipantCreateParameters { Seed = 2, Name = Utilities.RandomName() }; var participant2 = this.target.ParticipantCreate(this.tournament, participant2Parameters); var participant3Parameters = new ParticipantCreateParameters { Seed = 2, Name = Utilities.RandomName() }; var participant3 = this.target.ParticipantCreate(this.tournament, participant3Parameters); var tourParameters = new TournamentShowParameters { IncludeParticipants = true }; this.tournament = this.target.TournamentShow(this.tournament.Id, tourParameters); Assert.AreEqual(1, this.tournament.Participants.Find(p => p.Participant.Id == participant1.Id).Participant.Seed); Assert.AreEqual(2, this.tournament.Participants.Find(p => p.Participant.Id == participant3.Id).Participant.Seed); Assert.AreEqual(3, this.tournament.Participants.Find(p => p.Participant.Id == participant2.Id).Participant.Seed); }
/* Finds players that play in certain tournament using DataTable and DataAdapter */ public List<Player> FindPlayersByTournament(Tournament tournament) { //return _entities.Players.Where(p => p.Tournaments.Contains(tournament)).ToList(); var players = new List<Player>(); const string connectionString = @"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=Database;Integrated Security=True"; var table = new DataTable("TournamentPlayers"); using (var conn = new SqlConnection(connectionString)) { var command = "SELECT * FROM Players, TournamentPlayer " + $"WHERE TournamentPlayer.Tournaments_Id = {tournament.Id}" + "AND Players.Id = TournamentPlayer.Players_Id"; using (var cmd = new SqlCommand(command, conn)) { var adapter = new SqlDataAdapter(cmd); conn.Open(); adapter.Fill(table); conn.Close(); } } foreach (DataRow row in table.Rows) { players.Add(new Player { Id = int.Parse(row["Id"].ToString()), Name = row["Name"].ToString(), Surname = row["Surname"].ToString(), BirthDate = DateTime.Parse(row["BirthDate"].ToString()), Rating = row["Rating"].ToString().GetValueOrNull<double>() }); } return players; }
public void CreateInOrganization() { var name = "TournamentTest" + Utilities.RandomName(); var parameter = new TournamentCreateParameters { Subdomain = this.subdomain }; this.tournament = this.target.TournamentCreate(name, TournamentType.DoubleElimination, name, parameter); Debug.WriteLine("Created: ({0}){1} Url:{2} subdomain:{3}", this.tournament.Id, this.tournament.Name, this.tournament.Url, this.tournament.Subdomain); var indexParam = new TournamentIndexParameters { Subdomain = this.subdomain }; var tournaments = this.target.TournamentIndex(indexParam); foreach (var t in tournaments) { Debug.WriteLine("({0}){1} Url:{2} subdomain:{3}", t.Id, t.Name, t.Url, t.Subdomain); } Assert.IsTrue(tournaments.Any(t => t.Id == this.tournament.Id)); var showTour = this.target.TournamentShow(this.subdomain, name); Assert.AreEqual(this.tournament.Id, showTour.Id); showTour = this.target.TournamentShow(this.tournament.Id); Assert.AreEqual(this.tournament.Id, showTour.Id); }
public TournamentPrintDocument(Tournament tournament) : this() { Tournament = tournament; }
private Model.GenericPrediction ConvertAPIToGeneric(APIFootballPrediction apiPrediction, Tournament tournament, DateTime date, Uri predictionURL) { var tournamentEvent = this.fixtureRepository.GetTournamentEventFromTournamentAndDate(date, tournament.TournamentName); var footballPrediction = new Model.FootballPrediction() { TournamentName = tournament.TournamentName, TournamentEventName = tournamentEvent.EventName, TeamOrPlayerA = apiPrediction.HomeTeam, TeamOrPlayerB = apiPrediction.AwayTeam, MatchDate = date, MatchIdentifier = string.Format("{0}/vs/{1}/{2}/{3}", apiPrediction.HomeTeam, apiPrediction.AwayTeam, tournamentEvent.EventName, date.ToShortDateString().Replace("/", "-")), PredictionURL = predictionURL }; footballPrediction.OutcomeProbabilities.Add(Model.Outcome.HomeWin, apiPrediction.ExpectedProbabilities.HomeWinProb); footballPrediction.OutcomeProbabilities.Add(Model.Outcome.Draw, apiPrediction.ExpectedProbabilities.DrawProb); footballPrediction.OutcomeProbabilities.Add(Model.Outcome.AwayWin, apiPrediction.ExpectedProbabilities.AwayWinProb); foreach (var scoreLine in apiPrediction.ScoreProbabilities) { var key = string.Format("{0}-{1}", scoreLine.HomeGoals.ToString(), scoreLine.AwayGoals.ToString()); if (!footballPrediction.ScoreLineProbabilities.ContainsKey(key)) { footballPrediction.ScoreLineProbabilities.Add(key, scoreLine.Probability); } } return(footballPrediction); }
private void SetViewData(Tournament tournament) { }
private e.Tournament CreateEntityFromTournament(Tournament t) { if (t == null) { return null; } e.Tournament result = e.Tournament.CreateTournament(t.Id, t.Name, t.CreateDate); //e.Tournament result = new e.Tournament() //{ // CreateDate = t.CreateDate, // Id = t.Id, // Name = t.Name //}; return result; }
public void Delete(Tournament tournament) { _context.Remove(tournament); }
public JsonResult Seed(string json) { var seedObject = JObject.Parse(json); /* * json = { * id: id, <-- int * method: method, <-- int * ranks: rankList, <-- list of strings * groups: allGroups, <-- list of list of strings * competitors: allComp <-- list of strings * }; * System.Diagnostics.Debug.WriteLine("\nJson: {\n" + json + "\n}\n"); */ Tournament found = db.Tournaments.Find((int)seedObject["id"]); if (db.Events.Find(found.EventID).OrganizerID == User.Identity.GetUserId()) { var rankedCompetitors = new List <string>(); foreach (var rank in seedObject["ranks"]) { rankedCompetitors.Add(rank.ToString()); } var leftovers = new List <string>(); foreach (var comp in seedObject["competitors"]) { leftovers.Add(comp.ToString()); } leftovers = leftovers.Except(rankedCompetitors).ToList(); var filteredGroups = new List <List <string> >(); foreach (var group in seedObject["groups"]) { if (group.Any()) { var oldGroup = group.ToList(); var newGroup = new List <string>(); foreach (var element in oldGroup) { newGroup.Add(element.ToString()); } newGroup = newGroup.Except(rankedCompetitors).ToList(); filteredGroups.Add(newGroup); leftovers = leftovers.Except(newGroup).ToList(); } } //var seededCompetitors = rankedCompetitors; var seededCompetitors = new List <string>(); if (seedObject["method"].ToString() == "seq") { seededCompetitors.AddRange(rankedCompetitors); } else { filteredGroups.Add(rankedCompetitors); } foreach (var group in filteredGroups) { int spacing = (int)Math.Floor((double)leftovers.Count() / group.Count()) + 1; for (var i = 0; i < group.Count(); i++) { leftovers.Insert((i * spacing), group[i]); } } seededCompetitors.AddRange(leftovers); var sendingJson = "{\"participants\":["; var count = 1; foreach (var comp in seededCompetitors) { sendingJson += "{\"name\":\"" + comp + "\",\"seed\":" + count + "},"; count++; } sendingJson = sendingJson.Remove(sendingJson.Length - 1); sendingJson += "]}"; var response = sendSeed(sendingJson, found); return(Json(response, JsonRequestBehavior.AllowGet)); } else { return(Json("Access Denied", JsonRequestBehavior.AllowGet)); } }
public PlayerReferenceTests() { tournament = Tournament.Create("GSL 2019"); tournament.AddRoundRobinRound(); }
private void ExportTeamRooster() { var tournament = new Tournament(); int si = 0; try { si = lvwTournaments.SelectedItems[0].Index; } catch { return; } tournament = list[si]; List <Team> team = TeamHelper.GetTeam(tournament); List <Player> player = PlayerHelper.GetPlayer(tournament); List <TeamOfficial> official = TeamOfficialHelper.GetAllOfficial(tournament); ExcelPackage ExcelPkg = new ExcelPackage(); ExcelWorksheet wsSheet1 = ExcelPkg.Workbook.Worksheets.Add("Sheet1"); wsSheet1.Cells.Style.Font.Name = "Arial Narrow"; wsSheet1.Cells.Style.Font.Size = 11; //Title Of tournament wsSheet1.Cells["G" + 3].Value = "Basketball Tournament 2018"; //Date of tournament wsSheet1.Cells["G" + 4].Value = "April 15, 2018 - April 25, 2018"; wsSheet1.Cells["G9"].Value = "Official Team Rooster"; wsSheet1.Cells["G9"].Style.Font.Name = "Times New Roman"; wsSheet1.Cells["G9"].Style.Font.Size = 14; //Header of Tournament wsSheet1.Cells["A11"].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; wsSheet1.Cells["A11"].Value = "NO.1"; wsSheet1.Cells["C11"].Value = "Team name"; wsSheet1.Cells["G11"].Value = "Head Coach"; wsSheet1.Cells["K11"].Value = "Jersey No."; wsSheet1.Cells["N11"].Value = "Players"; int rowIndex = 0; int colIndex = 1; int Height = 220; int Width = 120; Image img = Image.FromFile(@"C:\Users\JOSHUA\Documents\Visual Studio 2015\Projects\BATMAN\Images\seal.jpg"); ExcelPicture pic = wsSheet1.Drawings.AddPicture("Sample", img); pic.SetPosition(rowIndex, 0, colIndex, 0); //pic.SetPosition(PixelTop, PixelLeft); pic.SetSize(Height, Width); string fileName = @"C:\Users\JOSHUA\Documents\Visual Studio 2015\Projects\BATMAN\" + wsSheet1.Cells["G" + 3].Value.ToString() + ".xls"; //INITIALIZING COUNTER FOR CELL int NoCounter = 12; int numberCounter = 1; int ctr = 12; foreach (var t in team) { var playerByTeam = BATMAN.Classes.Player.PlayerByTeam(player, t.teamID); var officialByTeam = TeamOfficial.ShowByTeam(official, t.teamID); wsSheet1.Cells["C" + NoCounter].Value = t.teamName; wsSheet1.Cells["G" + NoCounter].Value = officialByTeam.firstName + " " + officialByTeam.lastName; wsSheet1.Cells["A" + NoCounter].Value = numberCounter++; wsSheet1.Cells["A" + NoCounter].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center; foreach (var p in playerByTeam) { wsSheet1.Cells["K" + ctr].Value = p.jerseyNO.ToString(); wsSheet1.Cells["N" + ctr++].Value = p.firstName + " " + p.lastName; NoCounter++; } ctr++; NoCounter++; } wsSheet1.Protection.IsProtected = false; wsSheet1.Protection.AllowSelectLockedCells = false; ExcelPkg.SaveAs(new FileInfo(fileName)); FileInfo fi = new FileInfo(fileName); if (fi.Exists) { System.Diagnostics.Process.Start(fileName); } else { MessageBox.Show("Theres a problem while opening excel,Go to " + fileName + "Manual Open"); } }
public override Model.GenericPrediction FetchSinglePrediction(TeamPlayer teamPlayerA, TeamPlayer teamPlayerB, Tournament tournament, Model.IValueOptions valueOptions) { var webRepository = this.webRepositoryProvider.CreateWebRepository(valueOptions.CouponDate); var predictionURL = this.predictionRepository.GetTennisPredictionURL(teamPlayerA, teamPlayerB, tournament, valueOptions.CouponDate); var jsonTennisPrediction = (APITennisPrediction)webRepository.ParseJson <APITennisPrediction>( predictionURL, s => ProgressReporterProvider.Current.ReportProgress(s, Model.ReporterImportance.Low, Model.ReporterAudience.Admin)); jsonTennisPrediction.StartTime = valueOptions.CouponDate; return(ConvertAPIToGeneric(jsonTennisPrediction, predictionURL)); }
public MatchServiceTests() { var team1 = new Team() { TeamId = 1, Title = "Spartak" }; var team2 = new Team() { TeamId = 2, Title = "CSKA" }; var match1 = new FootballMatch() { MatchId = 1, HomeTeam = team1, AwayTeam = team2, TourId = 1 }; var match2 = new FootballMatch() { MatchId = 2, HomeTeam = team2, AwayTeam = team1, TourId = 1 }; var match3 = new FootballMatch() { MatchId = 3, HomeTeam = team2, AwayTeam = team1, TourId = 2 }; var tour1 = new Tour() { TourId = 1, Matches = new List <FootballMatch>() { match1, match2 } }; var tour2 = new Tour() { TourId = 2, Matches = new List <FootballMatch>() { match3 } }; var tournament1 = new Tournament() { TournamentId = 1, NewTours = new List <Tour>() { tour1 } }; var tournament2 = new Tournament() { TournamentId = 2, NewTours = new List <Tour>() { tour1, tour2 } }; _teamsTestData = new List <Team>() { team1, team2 }; _mathesTestData = new List <FootballMatch>() { match1, match2, match3 }; _toursTestData = new List <Tour>() { tour1, tour2 }; _tournamentsTestData = new List <Tournament>() { tournament1, tournament2 }; _teamsMockSet = CreateMockSet <Team>(_teamsTestData); _matchesMockSet = CreateMockSet <FootballMatch>(_mathesTestData); _toursMockSet = CreateMockSet <Tour>(_toursTestData); _tournamentsMockSet = CreateMockSet <Tournament>(_tournamentsTestData); _mockContext = CreateMockContext(); }
/// <summary> /// Add tournament to collection. /// </summary> /// <param name="newTournament">Tournament to add.</param> /// <returns>Builder object with collection of tournaments.</returns> public TournamentServiceTestFixture AddTournament(Tournament newTournament) { _tournaments.Add(newTournament); return(this); }
private static Round DrawPowerpairedRound(Tournament tournament, DataContext context, string motion) { SqlHelper helper = new SqlHelper(tournament.Database); Round round = new Round() { Motion = motion, IsRandom = false, RoundNumber = tournament.RoundNumber }; NonQueryResult insert = helper.InsertRound(round); List <Debate> debates = new List <Debate>(); List <Speaker> speakers = new List <Speaker>(); speakers.AddRange(context.Speakers.Where(a => a.Active)); speakers.AsParallel().ForAll(a => a.Draws = helper.GetSpeakerDraws(a.SpeakerId).Result); speakers = speakers.OrderByDescending(a => a.Draws.Sum(d => d.Result.Points())).ThenByDescending(s => s.Draws.Sum(d => d.SpeakerPoints)).ToList(); int numberOfRooms = speakers.Count / 6; int numberOfJudgesPerRoom = context.Judges.Count / numberOfRooms; List <Judge> judges = new List <Judge>(); judges.AddRange(context.Judges.Where(j => j.Active)); judges = judges.OrderByDescending(j => (int)j.Level).ToList(); List <Venue> venues = new List <Venue>(); venues.AddRange(context.Venues); for (int i = 1; i <= numberOfRooms; i++) { Venue v = venues.First(); venues.Remove(v); Debate debate = new Debate() { RoundId = round.RoundId, VenueId = v.VenueId }; debates.Add(debate); insert = helper.InsertDebate(debate); List <Speaker> toInsert = speakers.Take(6).ToList(); SetSpeakersResult result = SetSpeakers(toInsert, debate.DebateId); foreach (SpeakerDraw speakerDraw in result.SpeakerDraws) { helper.InsertSpeakerDraw(speakerDraw); } foreach (Speaker speaker in toInsert) { speakers.Remove(speaker); } Judge judge = judges.First(); JudgeDraw judgeDraw = new JudgeDraw() { DebateId = debate.DebateId, Number = 1, JudgeId = judge.JudgeId }; judges.Remove(judge); insert = helper.InsertJudgeDraw(judgeDraw); } foreach (Debate debate in debates) { for (int i = 2; i <= numberOfJudgesPerRoom; i++) { Judge j = judges.First(); JudgeDraw judgeDraw = new JudgeDraw() { DebateId = debate.DebateId, Number = i, JudgeId = j.JudgeId }; judges.Remove(j); insert = helper.InsertJudgeDraw(judgeDraw); } } while (judges.Any()) { Debate debate = debates.OrderBy(a => a.DebateId).First(); debates.Remove(debate); Judge j = judges.First(); JudgeDraw judgeDraw = new JudgeDraw() { DebateId = debate.DebateId, Number = numberOfJudgesPerRoom + 1, JudgeId = j.JudgeId }; judges.Remove(j); insert = helper.InsertJudgeDraw(judgeDraw); } return(round); }
private static Round DrawNonPowerpairedRound(Tournament tournament, DataContext context, string motion) { SqlHelper helper = new SqlHelper(tournament.Database); Round round = new Round() { Motion = motion, IsRandom = true, RoundNumber = tournament.RoundNumber }; NonQueryResult insert = helper.InsertRound(round); Random r = new Random(); List <Debate> debates = new List <Debate>(); List <Speaker> initialSpeakers = context.Speakers.Where(s => s.Active).OrderBy(a => Guid.NewGuid()).ToList(); Queue <Speaker> speakers = new Queue <Speaker>(context.Speakers.Count(s => s.Active)); int count = context.Speakers.Count(s => s.Active); while (initialSpeakers.Any()) { Speaker s = initialSpeakers.First(); speakers.Enqueue(s); initialSpeakers.Remove(s); } int numberOfRooms = speakers.Count / 6; int numberOfJudgesPerRoom = context.Judges.Count(j => j.Active) / numberOfRooms; List <Judge> judges = new List <Judge>(); judges.AddRange(context.Judges.Where(j => j.Active)); judges = judges.OrderByDescending(j => (int)j.Level).ToList(); List <Venue> venues = new List <Venue>(); venues.AddRange(context.Venues.Where(v => v.Active)); for (int i = 1; i <= numberOfRooms; i++) { Venue v = venues.First(); venues.Remove(v); Debate debate = new Debate() { RoundId = round.RoundId, VenueId = v.VenueId }; debates.Add(debate); insert = helper.InsertDebate(debate); foreach (Position p in Enum.GetValues(typeof(Position))) { if (p == Position.Invalid) { continue; } Speaker s = speakers.Dequeue(); SpeakerDraw speakerDraw = new SpeakerDraw() { DebateId = debate.DebateId, Position = p, SpeakerId = s.SpeakerId }; insert = helper.InsertSpeakerDraw(speakerDraw); } } foreach (Debate debate in debates.OrderBy(a => Guid.NewGuid())) { Judge j = judges.First(); JudgeDraw judgeDraw = new JudgeDraw() { DebateId = debate.DebateId, Number = 1, JudgeId = j.JudgeId }; judges.Remove(j); insert = helper.InsertJudgeDraw(judgeDraw); } foreach (Debate debate in debates.OrderBy(a => Guid.NewGuid())) { for (int i = 2; i <= numberOfJudgesPerRoom; i++) { Judge j = judges.First(); JudgeDraw judgeDraw = new JudgeDraw() { DebateId = debate.DebateId, Number = i, JudgeId = j.JudgeId }; judges.Remove(j); insert = helper.InsertJudgeDraw(judgeDraw); } } while (judges.Any()) { Debate debate = debates.OrderBy(a => a.DebateId).First(); debates.Remove(debate); Judge j = judges.First(); JudgeDraw judgeDraw = new JudgeDraw() { DebateId = debate.DebateId, Number = numberOfJudgesPerRoom + 1, JudgeId = j.JudgeId }; judges.Remove(j); insert = helper.InsertJudgeDraw(judgeDraw); } return(round); }
public ActionResult ConfirmGenerateUsers(List <viewModels.Account> Accounts, int TournamentID, string Generate = null, string Cancel = null) { if (Cancel != null) { return(RedirectToAction("GenerateUsers")); } Tournament tournament = repository.Tournaments.FirstOrDefault(t => t.TournamentID == TournamentID); if (Generate != null) { try { int userID = WebSecurity.CurrentUserId; foreach (var account in Accounts) { WebSecurity.CreateUserAndAccount(account.UserName, account.Password, new { BirthDay = account.BirthDay, Category = account.CategoryListID, CityID = account.CityID, CountryID = account.CountryID, FirstName = account.FirstName, Generated = 1, CreatedByUserID = userID, GradeLevel = account.GradeLevel, InstitutionID = account.InstitutionID, PhoneNumber = account.PhoneNumber, SecondName = account.SecondName, ThirdName = account.ThirdName }); Roles.AddUserToRole(account.UserName, "User"); if (tournament != null) { repository.BindUserToTournament(TournamentID, WebSecurity.GetUserId(account.UserName)); } } using (StreamWriter sw = new StreamWriter(LocalPath.AbsoluteGeneratedAccountsDirectory + DateTime.Now.ToString("dd.MM.yyyy_HH.mm.txt"))) { sw.WriteLine("UserName FullName Password"); foreach (var account in Accounts) { sw.WriteLine(account.UserName + " " + account.SecondName + "_" + account.FirstName + "_" + account.ThirdName + " " + account.Password); } } logger.Info("Genereted " + Accounts.Count() + " accounts"); } catch (Exception ex) { logger.Error("Error occurred on user " + WebSecurity.GetUserId(User.Identity.Name) + " \"" + User.Identity.Name + "\" generating accounts: ", ex); ModelState.AddModelError("", "Произошла ошибка при генерации аккаунтов"); } } var viewModel = new GeneratedUsersListViewModel() { Accounts = Accounts, Generated = true, AccountTemplate = new viewModels.Account(), RegisteredForTournament = tournament != null, TournamentName = tournament != null ? tournament.Name : "", TournamentID = TournamentID }; return(View(viewModel)); }
public abstract Model.GenericPrediction FetchSinglePrediction(TeamPlayer teamPlayerA, TeamPlayer teamPlayerB, Tournament tournament, Model.IValueOptions valueOptions);
/// <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; } } }
public TornamentPlayersHelper(BadmintonContext context, Tournament current) { Context = context; CurrentTournament = current; }
private static bool IsValid(Tournament tournament) { return(!(tournament.StartDate < DateTime.Now | string.IsNullOrEmpty(tournament.Name) | string.IsNullOrEmpty(tournament.Location))); }
public ActionResult Delete(int id) { Tournament tournament = db.Tournaments.Find(id); return(View(tournament)); }
public void RegistrToCupTest() { Tournament _cup = new Tournament(); _cup.Name = "English premier league"; _cup.MaxCountTeams = 18; _cup.TournamentId = 1; _cup.StartDate = "01.10.2017"; _cup.EndDate = "08.08.2018"; _cup.Password = "******"; _cup.Mail = "*****@*****.**"; Team _team = new Team(); _team.Name = "Barcelona"; _team.TeamId = 1; _team.Password = "******"; _team.Mail = "*****@*****.**"; Player player = new Player(); player.Name = "Messi"; player.PlayerId = 1; player.Born = new DateTime(1987, 12, 23); player.Position = "Middle Attacker"; player.Surname = "Lionel"; player.TeamId = 1; Reward reward = new Reward(); reward.Name = "Reward"; reward.Date = "1987-01-23"; reward.TeamId = 1; // Arrange var mockHighService = new Mock <IHighLevelSoccerManagerService>(); var mockLowService = new Mock <ILowLevelSoccerManagmentService>(); mockHighService.Setup(service => service.GetAllTeam()).Returns(new List <Team>() { _team }); mockHighService.Setup(service => service.GetAllTournaments()).Returns(new List <Tournament> { _cup }); mockLowService.Setup(service => service.GetAllPlayers()).Returns(new List <Player>() { player }); mockLowService.Setup(service => service.GetAllRewards()).Returns(new List <Reward>() { reward }); var store = new Mock <IUserStore <User> >(); var mockUserStore = new Mock <IUserStore <User> >(); var mockUserRoleStore = mockUserStore.As <IUserRoleStore <User> >(); var userManager = new Mock <UserManager <User> >(mockUserStore.Object, null, null, null, null, null, null, null, null); userManager.Setup(u => u.GetUserAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync( new User() { UserName = "******", UserId = 1 }); TeamController controller = new TeamController(mockHighService.Object, mockLowService.Object, userManager.Object); controller.ControllerContext = new ControllerContext { HttpContext = new DefaultHttpContext { User = new ClaimsPrincipal(new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, "Test") })) } }; // Act RedirectToActionResult result = (RedirectToActionResult)controller.RegistrToCup(_cup.TournamentId, _team.Password).Result; // Assert var viewResult = Assert.IsType <RedirectToActionResult>(result); }
public ActiveRoundResponse Create(Tournament tournament, int?currentRoundNumber) { return(new ActiveRoundResponse(tournament.Key, currentRoundNumber)); }
public void Add(Tournament tournament) { _context.Add(tournament); }
public static void Main(string[] args) { //Création des joueurs List <Player> Players = new List <Player>(); Players.Add(new Player("Serge", "Labourre", "XxNarutoxX")); Players.Add(new Player("Sarah", "Croche", "EmoGirlDu72")); Players.Add(new Player("Marie", "Tamitsouko", "Joséphine")); Players.Add(new Player("Lorie", "Chirac", "PJ")); //Création des équipes, une par joueur Players[0].AddTeam("Roxxor", "Pas pour les noobs"); Players[1].AddTeam("La communauté de l'anneau", "Au delà des différences"); Players[2].AddTeam("C", "Alphabet à la rescousse"); Players[3].AddTeam("D", "La réponse"); //Création des gladiateurs et ajout à une équipe Gladiator g; g = new Gladiator() { Name = "Eric" }; g.AddEquipement(new Net()); g.AddEquipement(new Helmet()); g.AddEquipement(new Sword()); Players[0].Teams[0].AddGladiator(g); g = new Gladiator() { Name = "Thomas" }; g.AddEquipement(new SmallShield()); g.AddEquipement(new Sword()); Players[0].Teams[0].AddGladiator(g); g = new Gladiator() { Name = "Laure" }; g.AddEquipement(new Dagger()); g.AddEquipement(new RectShield()); Players[0].Teams[0].AddGladiator(g); g = new Gladiator() { Name = "Sarah" }; g.AddEquipement(new Dagger()); g.AddEquipement(new Sword()); Players[0].Teams[0].AddGladiator(g); g = new Gladiator() { Name = "Gimli" }; g.AddEquipement(new Helmet()); g.AddEquipement(new Spear()); Players[1].Teams[0].AddGladiator(g); g = new Gladiator() { Name = "Legolas" }; g.AddEquipement(new Dagger()); g.AddEquipement(new SmallShield()); g.AddEquipement(new Net()); Players[1].Teams[0].AddGladiator(g); g = new Gladiator() { Name = "Soron" }; g.AddEquipement(new SmallShield()); g.AddEquipement(new Sword()); Players[1].Teams[0].AddGladiator(g); g = new Gladiator() { Name = "Gandalf" }; g.AddEquipement(new SmallShield()); g.AddEquipement(new Net()); g.AddEquipement(new Dagger()); Players[1].Teams[0].AddGladiator(g); g = new Gladiator() { Name = "Smaug" }; g.AddEquipement(new Trident()); g.AddEquipement(new Helmet()); Players[2].Teams[0].AddGladiator(g); g = new Gladiator() { Name = "Nessie" }; g.AddEquipement(new Spear()); g.AddEquipement(new Net()); Players[2].Teams[0].AddGladiator(g); g = new Gladiator() { Name = "Graoully" }; g.AddEquipement(new SmallShield()); g.AddEquipement(new Sword()); Players[2].Teams[0].AddGladiator(g); g = new Gladiator() { Name = "A" }; g.AddEquipement(new Dagger()); g.AddEquipement(new Spear()); Players[3].Teams[0].AddGladiator(g); g = new Gladiator() { Name = "B" }; g.AddEquipement(new Trident()); g.AddEquipement(new Net()); Players[3].Teams[0].AddGladiator(g); g = new Gladiator() { Name = "C" }; g.AddEquipement(new SmallShield()); g.AddEquipement(new Sword()); Players[3].Teams[0].AddGladiator(g); // Création du tournoi et ajout des joueurs Tournament myTournament = new Tournament(); myTournament.AddPlayer(Players[0]); myTournament.AddPlayer(Players[1]); myTournament.AddPlayer(Players[2]); myTournament.AddPlayer(Players[3]); //Début du tournoi myTournament.StartTournament(); }
public void Update(Tournament tournament) { _context.Update(tournament); }
private void ChampionshipViewer( HtmlTextWriter writer, Tournament tour ) { writer.WriteLine("<h2>{0}</h2>", CultureModule.getContent("tournament_groups")); Championship champ = (Championship) tour.CurrentPhase; string groupId = Page.Request.QueryString["group"]; if( groupId == null ) { foreach( Group group in champ.Groups ) { WriteGroup(writer, group, true); } WriteRoaster(writer, champ); } else { Group selected = champ.Groups[int.Parse(groupId) - 1]; WriteGroup(writer, selected, false); WriteMatches(writer, selected); } }
/// <summary> /// Initializes row /// </summary> /// <param name="_data"></param> public void Initialize(Tournament _data) { this.data = _data; this.transform.GetChild(0).gameObject.GetComponent <Text>().text = this.data.id; this.transform.GetChild(1).gameObject.GetComponent <Text>().text = this.data.attributes.createdAt; }
private void CheckRemove(Tournament tour) { try { string str = Page.Request.QueryString["remove"]; if( str == null ) { return; } int uid = int.Parse(str); if( Page.User.IsInRole("admin") ) { Ruler toRemove = null; foreach( Ruler ruler in tour.Registered ) { if( ruler.ForeignId == uid ) { toRemove = ruler; } } if( toRemove != null ) { tour.Registered.Remove(toRemove); } } } catch { } }
public void TeamSubmit_SelectAddSelectDeleteSelect_OK() { using (System.Transactions.TransactionScope updateTransaction = new System.Transactions.TransactionScope()) { string connectionString = GetConnectionstring(); DataAccess d2 = new DataAccess(connectionString); Team team = new Team(); team.ID = -1; team.TeamName = "blabla"; team.TeamMembers = "asdf"; team.Password = "******"; team.IsAdmin = false; d2.SaveTeam(team); Tournament t = new Tournament(); t.Id = -1; t.Name = "TESTING"; d2.SaveTournament(t); Assignment a = new Assignment(); a.AssignmentId = -1; a.AssignmentName = "ASSIGNMENT"; d2.SaveAssignment(a); TournamentAssignment ta = new TournamentAssignment(); ta.TournamentAssignmentId = -1; ta.TournamentId = t.Id; ta.AssignmentId = a.AssignmentId; ta.AssignmentOrder = 1; ta.Points1 = 100; ta.Points2 = 50; ta.Points3 = 25; ta.Active = false; d2.SaveTournamentAssignment(ta); TeamTournamentAssignment tta = new TeamTournamentAssignment(); tta.TeamTournamentAssignmentId = -1; tta.TeamId = team.ID; tta.TournamentAssignmentId = ta.TournamentAssignmentId; d2.SaveTeamTournamentAssignment(tta); Submit submit = new Submit(); submit.ID = -1; submit.TeamTournamentAssignmentId = (int)tta.TeamTournamentAssignmentId; submit.TeamId = team.ID; byte[] uploadstream = new byte[2] {1,2}; submit.UploadStream = uploadstream; submit.FileName = "somename.cs"; d2.InsertTeamSubmit(submit); Assert.AreNotEqual(submit.ID, -1); List<Submit> submits = d2.GetTeamSubmitsForAssignment(submit.TeamTournamentAssignmentId); Assert.AreEqual(submits.Count, 1); //getbyid Submit byId = d2.GetTeamSubmitById(submit.ID); Assert.AreEqual(byId.ID,submit.ID); d2.DeleteTeamSubmit(submit.ID); List<Submit> submitsAfterDelete = d2.GetTeamSubmitsForAssignment(submit.TeamTournamentAssignmentId); Assert.AreEqual(0, submitsAfterDelete.Count); } }
private void PlayoffsViewer( HtmlTextWriter writer, Tournament tour ) { writer.WriteLine("<h2>{0}</h2>", CultureModule.getContent("tournament_playoffs")); Playoffs plays = (Playoffs) tour.CurrentPhase; if( plays.Lucky != null ) { writer.WriteLine("<p>{0}: {1}</p>", CultureModule.getContent("tournament_lucky"), OrionGlobals.getLink(plays.Lucky)); } WriteMatches(writer, plays.Matches); }
private Tournament CreateTournamentFromEntity(e.Tournament eTournament) { if (eTournament == null) { return null; } Tournament result = new Tournament() { CreateDate = eTournament.CreateDate, Id = eTournament.Id, Name = eTournament.Name }; return result; }
private void WriteRegistered( HtmlTextWriter writer, Tournament tour ) { writer.WriteLine("<h2>{0}</h2>", CultureModule.getContent("tournament_registered")); writer.WriteLine("<ul class='registered'>"); int bags = Championship.GetNumberOfGroups(tour.Registered.Count); int count = -1; int currBag = 1; writer.WriteLine("<li class='title'>{0} {1}</li>", CultureModule.getContent("tournament_bag"), currBag++, bags); foreach( Ruler ruler in tour.Registered ) { if( ++count == bags ) { count = 0; writer.WriteLine("<li class='title'>{0} {1}</li>", CultureModule.getContent("tournament_bag"), currBag++, bags); } writer.Write("<li>{0}", OrionGlobals.getLink(ruler) ); if( Page.User.IsInRole("admin") ) { writer.Write("<a href='{0}&remove={1}'><img src='{2}' /></a>", Page.Request.RawUrl, ruler.ForeignId, OrionGlobals.getCommonImagePath("remove.gif")); } writer.WriteLine("</li>"); } writer.WriteLine("</ul>"); }
public List <UIElement> GetListOfTournamentitems(Tournament tournament) { _listOfItems = new List <UIElement>(); var tournamentRounds = tournament.GetTournamentToPrint(); var nextCursorPositionLeft = 0; var nextDistanceBeewinPalyers = 60; var nextCursorPositionTop = 50; var middleRectangleVertical = 15; var minimalWidthCloud = 50; foreach (var round in tournamentRounds[0]) { var maxWidthCloud = GetMaxLengthNameInRound(round) * 10 + minimalWidthCloud; var middleRectangHorisontal = maxWidthCloud / 2; if (tournamentRounds[0][0].Meetings.Count != tournamentRounds[0][1].Meetings.Count) { var stage = new Label { Margin = new Thickness(nextCursorPositionLeft, 0, 0, 0), Content = GetStageToPrint(round.Stage) }; _listOfItems.Add(stage); } var distanceBetweenPlayers = nextDistanceBeewinPalyers; var positionCursorLeft = nextCursorPositionLeft; var positionCursorTop = nextCursorPositionTop; for (var i = 0; i < round.Meetings.Count; i++) { var meeting = round.Meetings[i]; var isEmptyMeetingInFirstRound = meeting.FirstPlayer == null && meeting.SecondPlayer == null && round.Equals(tournamentRounds[0][0]); var indexForDrowLine = (distanceBetweenPlayers / 2) + middleRectangleVertical; if (!isEmptyMeetingInFirstRound) { PrintNamePlayer(positionCursorLeft, positionCursorTop, meeting, true, maxWidthCloud); var lineVertical = new Line { Stroke = Brushes.Black, X1 = positionCursorLeft + maxWidthCloud, Y1 = positionCursorTop + middleRectangleVertical, X2 = positionCursorLeft + maxWidthCloud, Y2 = positionCursorTop + distanceBetweenPlayers + middleRectangleVertical }; _listOfItems.Add(lineVertical); var lineHorisontal = new Line { Stroke = Brushes.Black, X1 = positionCursorLeft + maxWidthCloud, Y1 = positionCursorTop + indexForDrowLine, X2 = positionCursorLeft + maxWidthCloud + middleRectangHorisontal, Y2 = positionCursorTop + indexForDrowLine }; _listOfItems.Add(lineHorisontal); if (i == 0) { nextCursorPositionLeft = positionCursorLeft + maxWidthCloud + middleRectangHorisontal; nextDistanceBeewinPalyers *= 2; nextCursorPositionTop = positionCursorTop + indexForDrowLine - middleRectangleVertical; } positionCursorTop += distanceBetweenPlayers; PrintNamePlayer(positionCursorLeft, positionCursorTop, meeting, false, maxWidthCloud); } positionCursorTop += distanceBetweenPlayers; } } var finishMeeting = tournamentRounds[0][tournamentRounds[0].Count - 1].Meetings[0]; PrintNamePlayer(nextCursorPositionLeft, nextCursorPositionTop, finishMeeting, finishMeeting.Winner == MeetingWinner.FirstPlayer, 3); return(_listOfItems); }
private void WriteUnits( HtmlTextWriter writer, Tournament tour ) { writer.WriteLine("<div class='planetInfoZoneTitle'><b>{0}</b></div>", CultureModule.getContent("tournament_units")); writer.WriteLine("<table class='planetFrame' width='100%'>"); writer.WriteLine("<tr>"); foreach( string ship in tour.BaseFleet.Ships.Keys ) { writer.WriteLine("<td class='resourceCell'><a href='{2}' alt='{3}' title='{3}'><img src='{0}units/{1}_preview.gif' class='unit_small_preview' /></a></td>", OrionGlobals.getCommonImagePath(), ship, Wiki.GetUrl("Unit", ship), CultureModule.getContent(ship)); } writer.WriteLine("</tr>"); writer.WriteLine("<tr>"); foreach( object quantity in tour.BaseFleet.Ships.Values ) { writer.WriteLine("<td class='resourceCell'>{0}</td>", quantity); } writer.WriteLine("</tr>"); writer.WriteLine("</table>"); }
private void CheckRegister(Tournament tour) { string str = Page.Request.QueryString["register"]; if( str == null ) { return; } if( tour.Register(getRuler()) ) { Information.AddInformation(CultureModule.getContent("tournament_ruler_registered")); Sort( tour.Registered ); } else { Information.AddError( CultureModule.getContent("tournament_ruler_already_registered") ); } }
public string BuildURL(Tournament item) { return(@"/api/tournament/" + item.Id); }
private void FinishedViewer( HtmlTextWriter writer, Tournament tour ) { writer.WriteLine("<h2>{0}</h2>", CultureModule.getContent("tournament_finished")); Playoffs plays = (Playoffs) tour.CurrentPhase; }
public void SetupForTest() { currentTournament = new Tournament("Vinter Turnering"); currentTournament.SetupTestRounds(); }
private void SubscriptionsViewer( HtmlTextWriter writer, Tournament tour ) { if( Page.User.IsInRole("ruler")) { string register = "®ister=1"; if( Page.Request.RawUrl.IndexOf("®ister") >= 0 ) { register = string.Empty; } writer.WriteLine("<a href='{2}{3}'><img src='{0}' /> {1}</a>", OrionGlobals.getCommonImagePath("ok.gif"), CultureModule.getContent("tournament_register"), Page.Request.RawUrl, register); } #if DEBUG for( int i = 0; i < 100; ++i ) { tour.Register( Universe.instance.CreateRuler("Zen " +i, "Zen"+i) ); } #endif WriteRegistered(writer, tour); }
public async void 大会の編集画面を表示() { // Arrange var id = 000001; var holdingPeriodStartDate = new DateTime(2020, 6, 10); var holdingPeriodEndDate = new DateTime(2020, 6, 20); var tournament = new Tournament( new TournamentName("ジュニア選手権"), TournamentType.WithDraw, new RegistrationYear(new DateTime(2020, 4, 1)), TypeOfYear.Odd, new AggregationMonth(new DateTime(2020, 6, 1)), new List <TennisEvent>() { TennisEvent.FromId("1_1_1"), TennisEvent.FromId("1_1_2") }, new HoldingPeriod(holdingPeriodStartDate, holdingPeriodEndDate), new List <HoldingDate>() { new HoldingDate(new DateTime(2020, 6, 12)), new HoldingDate(new DateTime(2020, 6, 13)) }, new Venue("日本テニスコート"), new EntryFee(100), MethodOfPayment.PrePayment, new ApplicationPeriod(new DateTime(2020, 5, 1), new DateTime(2020, 5, 31)), new Outline("大会名:ジュニア選手 権場所:日本テニスコート"), "メール件名", "メール本文", 1); var mailTemplate = new Dictionary <string, string>() { { "PrePayment", "メール内容" }, { "PostPayment", "メール内容" }, { "NotRecieve", "メール内容" }, { "Other", "メール内容" } }; var holdingDates = new List <JsonHoldingDate>() { new JsonHoldingDate(new DateTime(2020, 03, 30), true) }; var mockUseCase = new Mock <ITournamentUseCase>(); mockUseCase.Setup(m => m.GetTournament(id)) .ReturnsAsync(tournament) .Verifiable(); mockUseCase.Setup(m => m.CreateHoldingDates(holdingPeriodStartDate, holdingPeriodEndDate)) .Returns(holdingDates) .Verifiable(); mockUseCase.Setup(m => m.GetTournamentEntryReceptionMailBodies()) .Returns(mailTemplate) .Verifiable(); var controller = new TournamentsController(mockUseCase.Object); // Act var result = await controller.Edit(id); // Assert mockUseCase.Verify(); var viewResult = Assert.IsType <ViewResult>(result); var model = Assert.IsAssignableFrom <EditViewModel>(viewResult.ViewData.Model); Assert.Equal(mailTemplate, model.TournamentEntryReceptionMailBodies); }
private void WriteState( HtmlTextWriter writer, Tournament tour ) { //writer.WriteLine("<div class='planetInfoZoneTitle'><b>{0}</b></div>", CultureModule.getContent("tournament_info")); writer.WriteLine("<h2>{0}</b></h2>", CultureModule.getContent("tournament_info")); writer.WriteLine("<table class='planetFrame' width='100%'>"); writer.WriteLine("<tr>"); writer.WriteLine("<td>"); writer.WriteLine("{0}: <b>{1}</b><br/>", CultureModule.getContent("tournament_registered"), tour.Participants); if( tour.State == TournamentState.Championship ) { Championship champ = (Championship) tour.CurrentPhase; writer.WriteLine("{0}: <b>{1}</b><br/>", CultureModule.getContent("tournament_groups"), champ.Groups.Length); } writer.WriteLine("{0}: <b>{1}</b>", CultureModule.getContent("tournament_phase"), CultureModule.getContent(tour.State.ToString())); writer.WriteLine("</td>"); writer.WriteLine("</tr>"); writer.WriteLine("<tr>"); writer.WriteLine("</tr>"); writer.WriteLine("</table>"); }
public Tournament CreateTournament(Tournament model) { List <Tournament> tournament = TournamentsFile.FullFilePath().LoadFile().ConvertToTournament(); int currentId = 1; if (tournament.Count > 0) { currentId = tournament.OrderByDescending(x => x.Id).First().Id + 1; } model.Id = currentId; List <Matchup> matchupsHere = MatchupsFile.FullFilePath().LoadFile().ConvertToMatchup(); List <MatchupEntry> matchupEntriesHere = MatchupEntriesFile.FullFilePath().LoadFile().ConvertToMatchupEntry(); //Add the new record with new ID (max + 1) int currentMatchupId = 1; int currentMatchupEntryId = 1; foreach (List <Matchup> matchups in model.Rounds) { if (matchupsHere.Count > 0 && currentMatchupId == 1) { currentMatchupId = matchupsHere.OrderByDescending(x => x.Id).First().Id + 1; } foreach (Matchup matchup in matchups) { matchup.Id = currentMatchupId; currentMatchupId++; if (matchupEntriesHere.Count > 0 && currentMatchupEntryId == 1) { currentMatchupEntryId = matchupEntriesHere.OrderByDescending(x => x.Id).First().Id + 1; } foreach (MatchupEntry entry in matchup.Entries) { entry.Id = currentMatchupEntryId; currentMatchupEntryId++; if (entry.TeamCompeting != null) { entry.CompetingTeamId = entry.TeamCompeting.Id; } } } } foreach (List <Matchup> matchups in model.Rounds) { if (model.TournamentRoundsString != null) { model.TournamentRoundsString = model.TournamentRoundsString + $"|"; } foreach (Matchup matchup in matchups) { foreach (MatchupEntry entry in matchup.Entries) { //id|id if (matchup.entriesString == "") { matchup.entriesString = $"{entry.Id}"; } else { matchup.entriesString = matchup.entriesString + $"|{entry.Id}"; } if (entry.ParentMatchup != null) { entry.ParentId = entry.ParentMatchup.Id; } } if (matchup == matchups.Last()) { model.TournamentRoundsString = model.TournamentRoundsString + $"{matchup.Id}"; } else { model.TournamentRoundsString = model.TournamentRoundsString + $"{matchup.Id}^"; } } } SaveRoundsFile(model, MatchupsFile, MatchupEntriesFile); tournament.Add(model); tournament.SaveToTournamentFile(TournamentsFile); return(model); }
public TournamentTabViewModel() { Tournament = new Tournament(); _allTournamentNames = new TrulyObservableCollection<TournamentName>(); TournamentDescriptionNames = new TrulyObservableCollection<TournamentDescription>(); TournamentDescription = new TournamentDescription(); TournamentDescriptionNameIndex = -1; TournamentChairmen = new TrulyObservableCollection<TournamentChairman>(); TournamentChairmenSelectedIndex = -1; ReadTournamentChairmen(); }
private void AssetsVersionCheckCompleted() { if (!string.IsNullOrEmpty(UpdateManager.Get().GetError()) && UpdateManager.Get().UpdateIsRequired()) { Error.AddFatalLoc("GLUE_PATCHING_ERROR", new object[0]); } else { if (Network.ShouldBeConnectedToAurora()) { BnetPresenceMgr.Get().Initialize(); BnetFriendMgr.Get().Initialize(); BnetChallengeMgr.Get().Initialize(); BnetWhisperMgr.Get().Initialize(); BnetNearbyPlayerMgr.Get().Initialize(); FriendChallengeMgr.Get().OnLoggedIn(); SpectatorManager.Get().Initialize(); if (!Options.Get().GetBool(Option.CONNECT_TO_AURORA)) { Options.Get().SetBool(Option.CONNECT_TO_AURORA, true); } TutorialProgress progress = Options.Get().GetEnum <TutorialProgress>(Option.LOCAL_TUTORIAL_PROGRESS); if (progress > TutorialProgress.NOTHING_COMPLETE) { this.m_waitingForSetProgress = true; ConnectAPI.SetProgress((long)progress); } if (WebAuth.GetIsNewCreatedAccount()) { AdTrackingManager.Get().TrackAccountCreated(); WebAuth.SetIsNewCreatedAccount(false); } } ConnectAPI.RequestAccountLicenses(); ConnectAPI.RequestGameLicenses(); Box.Get().OnLoggedIn(); BaseUI.Get().OnLoggedIn(); InactivePlayerKicker.Get().OnLoggedIn(); HealthyGamingMgr.Get().OnLoggedIn(); DefLoader.Get().Initialize(); CollectionManager.Init(); AdventureProgressMgr.Init(); Tournament.Init(); GameMgr.Get().OnLoggedIn(); if (Network.ShouldBeConnectedToAurora()) { StoreManager.Get().Init(); } Network.TrackClient(Network.TrackLevel.LEVEL_INFO, Network.TrackWhat.TRACK_LOGIN_FINISHED); Network.ResetConnectionFailureCount(); if (Network.ShouldBeConnectedToAurora()) { ConnectAPI.DoLoginUpdate(); } else { this.m_waitingForUpdateLoginComplete = false; } Enum[] args = new Enum[] { PresenceStatus.LOGIN }; PresenceMgr.Get().SetStatus(args); if (SplashScreen.Get() != null) { SplashScreen.Get().StopPatching(); SplashScreen.Get().ShowRatings(); } this.PreloadActors(); if (!Network.ShouldBeConnectedToAurora()) { base.StartCoroutine(this.RegisterScreenWhenReady()); } SceneMgr.Get().LoadShaderPreCompiler(); } }
private void btnImport_Click(object sender, EventArgs e) { var targets = new Queue<string>(); using (var dialog = new OpenFileDialog()) { dialog.CheckFileExists = true; dialog.CheckPathExists = true; dialog.DefaultExt = ".export"; dialog.ValidateNames = true; dialog.Title = "Select the file or files to Import..."; dialog.RestoreDirectory = true; dialog.Multiselect = true; dialog.Filter = "Export Files (*.export)|*.export|All Files (*.*)|*.*"; if (dialog.ShowDialog() == DialogResult.Cancel) return; foreach (string filename in dialog.FileNames) targets.Enqueue(filename); } while (targets.Count > 0) { string target = targets.Dequeue(); var xml = new XmlDocument(); try { xml.Load(target); } catch { MessageBox.Show("An error occurred while trying to import " + Path.GetFileName(target) + ", it may not be an export or it is corrupted.", "Failed to Import", MessageBoxButtons.OK, MessageBoxIcon.Error); continue; } XmlNode exportNode = xml.SelectSingleNode("//Export"); if (exportNode == null) { MessageBox.Show("An error occurred while trying to import " + Path.GetFileName(target) + ", it does not contain an exported Event.", "Failed to Import", MessageBoxButtons.OK, MessageBoxIcon.Error); continue; } XmlNodeList playerNodes = exportNode.SelectNodes("Players/Player"); var newPlayers = new List<PlayerRecord>(); if (playerNodes != null) { foreach (XmlNode playerNode in playerNodes) { var record = new PlayerRecord(playerNode); if (Config.Settings.GetPlayer(record.ID) == null) newPlayers.Add(record); } } XmlNode tournamentNode = exportNode.SelectSingleNode("Tournament"); XmlNode leagueNode = exportNode.SelectSingleNode("League"); if (tournamentNode != null) { Tournament tournament = null; try { tournament = new Tournament(tournamentNode); } catch { MessageBox.Show("An error occurred while trying to import " + Path.GetFileName(target) + ", found a Tournament record but failed to parse it.", "Failed to Import", MessageBoxButtons.OK, MessageBoxIcon.Error); continue; } Tournament tempTournament = Config.Settings.GetTournament(tournament.Name); bool alreadyExists = false; string prefix = ""; while (tempTournament != null) { alreadyExists = true; prefix += "!"; tempTournament = Config.Settings.GetTournament(prefix + " " + tournament.Name); } string message = "The following information will be imported:\r\n"; message += "Tournament: " + tournament.Name + "\r\n"; if (alreadyExists) message += "(A Tournament already exists with this name, adding \"" + prefix + "\" to the name.)\r\n"; if (newPlayers.Count > 0) message += "New Players: " + newPlayers.Count.ToString() + " (out of " + playerNodes.Count.ToString() + " found.)\r\n"; message += "\r\nPress OK to import this Event."; if (MessageBox.Show(message, "Confirm Import", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1) == DialogResult.Cancel) continue; foreach (PlayerRecord record in newPlayers) Config.Settings.Players.Add(record); if (prefix.Length > 0) tournament.Name = prefix + " " + tournament.Name; Config.Settings.Tournaments.Add(tournament); Config.Settings.SaveEvents(); lstEvents.BeginUpdate(); var item = new ListViewItem(); item.Name = tournament.Name; item.Text = tournament.Name; item.SubItems.Add("Tournament"); item.SubItems.Add(tournament.Location); item.SubItems.Add(tournament.Date.ToShortDateString()); item.SubItems.Add(tournament.Players.Count.ToString()); if (tournament.Rounds.Count == 0) item.SubItems.Add("Not Started"); else if (tournament.Rounds.Count == tournament.TotalRounds && tournament.Rounds[tournament.TotalRounds - 1].Completed) item.SubItems.Add("Finished"); else { int roundNum = tournament.Rounds.Count; if (tournament.Rounds[roundNum - 1].Completed) item.SubItems.Add("Round " + roundNum.ToString() + " of " + tournament.TotalRounds.ToString() + " Done"); else item.SubItems.Add("Round " + roundNum.ToString() + " of " + tournament.TotalRounds.ToString() + " Active"); } lstEvents.Items.Add(item); lstEvents.Sort(); lstEvents.EndUpdate(); } else if (leagueNode != null) { var pastReference = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 0, 0, 0); League league = null; try { league = new League(leagueNode); } catch { MessageBox.Show("An error occurred while trying to import " + Path.GetFileName(target) + ", found a League record but failed to parse it.", "Failed to Import", MessageBoxButtons.OK, MessageBoxIcon.Error); continue; } League tempLeague = Config.Settings.GetLeague(league.Name); bool alreadyExists = false; string prefix = ""; while (tempLeague != null) { alreadyExists = true; prefix += "!"; tempLeague = Config.Settings.GetLeague(prefix + " " + league.Name); } string message = "The following information will be imported:\r\n"; message += "League: " + league.Name + "\r\n"; if (alreadyExists) message += "(A League already exists with this name, adding \"" + prefix + "\" to the name.)\r\n"; if (newPlayers.Count > 0) message += "New Players: " + newPlayers.Count.ToString() + " (out of " + playerNodes.Count.ToString() + " found.)\r\n"; message += "\r\nPress OK to import this Event."; if (MessageBox.Show(message, "Confirm Import", MessageBoxButtons.OKCancel, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1) == DialogResult.Cancel) continue; foreach (PlayerRecord record in newPlayers) Config.Settings.Players.Add(record); if (prefix.Length > 0) league.Name = prefix + " " + league.Name; Config.Settings.Leagues.Add(league); Config.Settings.SaveEvents(); lstEvents.BeginUpdate(); var item = new ListViewItem(); item.Name = league.Name; item.Text = league.Name; item.SubItems.Add("League"); item.SubItems.Add(league.Location); item.SubItems.Add(league.StartDate.ToShortDateString()); item.SubItems.Add(league.Players.Count.ToString()); if (league.MatchesPlayed.Count == 0) item.SubItems.Add("Not Started"); else if (league.EndDate < pastReference) item.SubItems.Add("Finished"); else { item.SubItems.Add(league.MatchesPlayed.Count.ToString() + " Result" + (league.MatchesPlayed.Count == 1 ? "" : "s") + " Entered"); } lstEvents.Items.Add(item); lstEvents.Sort(); lstEvents.EndUpdate(); } else { MessageBox.Show("An error occurred while trying to import " + Path.GetFileName(target) + ", the Event information was not found.", "Failed to Import", MessageBoxButtons.OK, MessageBoxIcon.Error); continue; } } }
/// <summary> /// When they click next round, set up the next tournament round /// </summary> private async void btnNextRound_Click(object sender, RoutedEventArgs e) { // Don't do anything if nothing is selected if (itemListView.SelectedIndex == -1) { return; } // Hide the button to stop double clicking btnNextRound.Visibility = Visibility.Collapsed; Tournament tournament = itemListView.SelectedItem as Tournament; TournamentRound newRound = new TournamentRound(); // This button can only be seen if it's possible to create a new tournament round newRound.Initialize(); // IMPORTANT: // If it's the first round, we must ensure that we have a specific number of competitors // The idea is that e.g. if there's 7 competitors, we can't have 3.5 games // so we must skip some to round two. List <int> ContestantIDs = tournament.RemainingContestantIDs.ToList(); // If this is the first round and the number of players is not a power of two we need to sort it out so that next round it will be (see user documentation for more information on why this is the case) // To check if it's a power of two, an efficient method using bitwise operators is used. // To understand why this works, consider that a power of two represented in binary looks as follows: // 10000000 (i.e. 1 + n 0s) // A power of two with one taken away in binary looks as follows: // 01111111 (i.e. 0 + n 1s) // This means that using an AND bitwise operator on these will return 0 if and only if it is a power of two. if (tournament.TournamentRounds.Count == 0 && (ContestantIDs.Count & (ContestantIDs.Count - 1)) != 0) { int nearestPow2 = 1; while (nearestPow2 < tournament.ContestantIDs.Count) { nearestPow2 *= 2; } if (nearestPow2 > tournament.ContestantIDs.Count) { nearestPow2 /= 2; } // We now know the nearest power of two below the number of members // Now we need to double the difference and put that many players into round one int numberOfPlayers = tournament.ContestantIDs.Count - nearestPow2; numberOfPlayers *= 2; List <Member> firstRoundContestants = new List <Member>(); for (int i = 0; i < numberOfPlayers; i++) { // Get the lowest ELO player Member lowestELO = null; foreach (Member member in tournament.Contestants) { // If we don't have a lowestELO yet or they have a lower ELO we set them to the variable if ((lowestELO == null || member.ELO < lowestELO.ELO) && !firstRoundContestants.Contains(member)) { lowestELO = member; } } // Add them to the first contestants firstRoundContestants.Add(lowestELO); } // Form a list of contestantIDs from the first round contestants ContestantIDs = new List <int>(); foreach (Member member in firstRoundContestants) { ContestantIDs.Add(member.ID); } } // Set up basic values from known data newRound.ContestantIDs = ContestantIDs; newRound.RoundNumber = tournament.TournamentRounds.Count + 1; newRound.TournamentID = tournament.ID; // Plan matches newRound.planMatches(); // Add to database and save data App.db.TournamentRounds.Add(newRound); App.db.SaveData(); // Refresh the rounds grid to reflect changes grdRounds.ItemsSource = null; grdRounds.ItemsSource = tournament.TournamentRounds; // Show the current round button as a round is now in progress btnCurrentRound.Visibility = Visibility.Visible; }