protected override void SetMatches(Player[] players) { for (int i = 0; i < players.Length - 1; i++) { for (int j = i + 1; j < players.Length; j++) { Matches.Add(new Match(players[i], players[j])); } } }
public bool Score(int selectedMatch, int score1, int score2) { var match = Matches[selectedMatch]; if (match.State == MatchState.Ended) { return(false); } if (score1 == score2) { return(false); } string matchWinner; if (score1 > score2) { matchWinner = match.Team1; } else { matchWinner = match.Team2; } match.Score1 = score1; match.Score2 = score2; match.State = MatchState.Ended; //Select a match that only have one team(is considered a Open Match) //If dont exist, create a new one var nextMatch = Matches.Where(m => m.State == MatchState.Open).FirstOrDefault(); if (nextMatch == null) { nextMatch = new Match(matchWinner, String.Empty, MatchState.Open); Matches.Add(nextMatch); } else { nextMatch.Team2 = matchWinner; nextMatch.State = MatchState.Closed; } //If the collection dont have any Closed Match avaiable, //that means all the matches are ended and this winner is the Tournament Winner if (!Matches.Any(m => m.State == MatchState.Closed)) { Winner = matchWinner; state = TournamentState.Ended; return(true); } return(true); }
/// <summary> Matches the specified item. </summary> /// <param name="item"> The item. </param> /// <param name="test"> if set to <c>true</c> [test]. </param> public void Match(T item, bool test) { if (test) { Matches.Add(item); } else { Mismatches.Add(item); } }
protected void ChangeMatchCountTo(int count) { Matches.Clear(); while (Matches.Count < count) { Matches.Add(Match.Create(this)); } MarkAsModified(); }
public static void ProcessMatchInformations(IList <MatchInformation> matchInformations) { RawMatchData.AddRange(matchInformations); foreach (var matchInfo in matchInformations) { var fighter1 = GetOrCreateFighter(matchInfo.Fighter1); var fighter2 = GetOrCreateFighter(matchInfo.Fighter2); if (fighter1 == null || fighter2 == null) { continue; } // Win / loss by points? var resultByPoints = matchInfo.Method.ToLower().Contains("pts") || matchInfo.Method.ToLower().Contains("points"); MatchResult result; switch (matchInfo.Result) { case ("W"): result = resultByPoints ? MatchResult.WinByPoints : MatchResult.WinBySubmission; break; case ("L"): result = resultByPoints ? MatchResult.LossByPoints : MatchResult.LossBySubmission; break; case ("D"): result = MatchResult.Draw; break; default: throw new ArgumentException("Result could not be analyzed!"); } int year; if (!Int32.TryParse(matchInfo.Year, out year)) { year = 0; } var match = new MatchWithoutId() { Fighter1 = fighter1, Fighter2 = fighter2, Result = result, Year = year }; Matches.Add(match); } }
/// <summary> /// Add a new pose /// </summary> /// <param name="pose">Source pose</param> /// <param name="name">Name of the new pose</param> /// <returns>ID of the added pose</returns> public NuitrackPose AddPose(NuitrackPose pose, string name = null) { name = name == null?string.Format("Pose {0}", poseEvents.Count + 1) : pose.name; NuitrackPose poseDuplicate = new NuitrackPose(name, pose); poseEvents.Add(pose, new PoseProcessEvent()); Matches.Add(pose, new Dictionary <int, float>()); return(poseDuplicate); }
/// <summary> /// Add a new pose /// </summary> /// <param name="skeleton">Source skeleton</param> /// <param name="name">Name of the new pose</param> /// <returns>ID of the added pose</returns> public NuitrackPose AddPose(UserData.SkeletonData skeleton, string name = null) { name ??= string.Format("Pose {0}", poseEvents.Count + 1); NuitrackPose pose = new NuitrackPose(name, skeleton); poseEvents.Add(pose, new PoseProcessEvent()); Matches.Add(pose, new Dictionary <int, float>()); return(pose); }
private void RandomPairing(List <Player> piPlayers) { var rand = new Random(); var playersRandomOrder = piPlayers.OrderBy(a => rand.Next(int.MaxValue)).ToList(); for (int i = 0; i + 1 < playersRandomOrder.Count(); i += 2) { var match = new Match(playersRandomOrder[i], playersRandomOrder[i + 1]); Matches.Add(match); } }
private void Win(Player winner, Player looser) { if (_bufferPlayer == null) { _bufferPlayer = winner; } else { Matches.Add(new Match(_bufferPlayer, winner)); _bufferPlayer = null; } }
public override void Init() { var nbPlayers = Players.Count % 2 != 0 ? Players.Count - 1 : Players.Count; for (int i = 0; i < nbPlayers; i += 2) { Matches.Add(new Match(Players[i], Players[i + 1])); } _nbMatches = nbPlayers / 2; SetState(); }
/// <summary> /// Uses the playerlist to generate the bracket structure & Matches. /// This creates & populates all the Match objects, and ties them together. /// If any Matches already exist, they will be deleted first. /// If there are <2 players, nothing will be made. /// </summary> /// <param name="_gamesPerMatch">Max games for every Match</param> public override void CreateBracket(int _gamesPerMatch = 1) { // First, clear any existing Matches and results: ResetBracketData(); if (Players.Count < 2) { return; } /* * A stepladder/gauntlet bracket has just one match per round. * The bottom two seeds face off in the first round, * and the winner of each match moves on to face the next lowest seed. * The top seed is placed directly in the final round. */ // Create Matches and assign Players: int playerIndex = Players.Count - 2; for (int i = 1; playerIndex >= 0; ++i, --playerIndex) { Match match = new Match(); match.SetMatchNumber(i); match.SetRoundIndex(i); match.SetMatchIndex(1); match.SetMaxGames(_gamesPerMatch); // Every Match has one Player directly placed: match.AddPlayer(Players[playerIndex], PlayerSlot.Defender); Matches.Add(match.MatchNumber, match); } // Now, manually add the lowest seed to the first Match: Matches[1].AddPlayer(Players.Last(), PlayerSlot.Challenger); // Set Bracket fields: NumberOfMatches = Matches.Count; NumberOfRounds = Matches.Count; // Tie Matches together: // (easy in Stepladder: each MatchNumber leads to MatchNumber+1) for (int m = 1; m <= NumberOfMatches; ++m) { if (m > 1) { Matches[m].AddPreviousMatchNumber(m - 1, PlayerSlot.Challenger); } if (m < NumberOfMatches) { Matches[m].SetNextMatchNumber(m + 1); } } }
/// <summary> /// Adds a list of match to the list of matches. Removes identical previous matches if the "IgnoreDuplicates" option is set. /// </summary> /// <param name="matches">the <see cref="IEnumerable{MatchItem}"/> list to add to the Matches </param> private void AddMatches(IEnumerable <MatchItem> matches) { bool isDuplicate = false; var matchItems = matches as List <MatchItem> ?? matches.ToList(); foreach (var item in matchItems) { if (IgnoreDuplicateMatches) {//remove duplicates of any exist already, so only the new entry is in the list var duplicates = Matches.Where(m => m == item).ToList(); if (duplicates.Any()) { isDuplicate = true; foreach (var duplicate in duplicates) { Matches.Remove(duplicate); } } } Matches.Add(item); } NewestLogEntry = Matches.Last(); if (!isDuplicate) {//only notify if this isn't a duplicate or IgnoreDuplicateMatches is false. //isDuplicate is true if any of the matches is a duplicate. Because all matches are for the same message (but possibly different rules), one duplicate means the whole list of matches is a duplicate if (SystemTrayEnabled) { _trayIcon.ShowBalloonTip(5000, "Found new Matches!", string.Join("\r\n", matchItems.Select(m => "Rule: " + m.MatchingRuleName + " User: "******" Message: " + m.Message)), ToolTipIcon.Info); } if (PlaySoundEnabled) { if (!string.IsNullOrEmpty(SoundPath) && File.Exists(SoundPath)) { var wplayer = new WindowsMediaPlayer(); wplayer.URL = SoundPath; wplayer.controls.play(); } else { Console.Beep(500, 300); } } } }
private void SearchFacets(string searchKeyword) { Matches.Clear(); var matchingFacets = _facetTypes.SelectMany(x => x.Facets.Where(y => y.DisplayName.ToLower() .Contains(searchKeyword.ToLower()))) .Select(x => x.DisplayName) .Distinct(); foreach (var facet in matchingFacets) { Matches.Add(facet); } }
/// <summary> ///Добавляет в базу данных не сортированный матч, то есть только полученный с помощью парсера /// </summary> /// <param name="match">не отсортированный матч</param> public void AddNotSortedMatch(Match match) { Gamer[] gamersLeft = match.Left.Gamers.ToArray(); Gamer[] gamersRight = match.Right.Gamers.ToArray(); Team left = CreateTeamByNewGamers(match.Left.Name, gamersLeft); Team right = CreateTeamByNewGamers(match.Right.Name, gamersRight); Team.UpdateTeamByResultMatch(left, right, match.ScoresLeft, match.ScoresRight); Match addingMatch = new Match(left, right, match.ScoresLeft, match.ScoresRight, match.URL); Teams.Add(left); Teams.Add(right); Matches.Add(addingMatch); }
internal void AddMatch(Token token, object value, FileLocation location) { if (TryConcatMatch(token, value, location)) { return; } Matches.Add(new Match { Token = token, Value = value, Location = location.Clone() }); }
internal async Task NewMatch(Match match) { IsLoading = true; MainException = null; try { await GetDataStore().AddMatchAsync(match); } catch (Exception ex) { MainException = ex; Matches.Add(match); } IsLoading = false; }
private void ReloadTournaments(List <Tournament> tournaments) { Matches.Clear(); foreach (var tournament in tournaments) { Matches.Add(new MatchItemViewModel { //Dates = tournament.Dates, //Groups = tournament.Groups, //Logo = tournament.Logo, //Name = tournament.Name, //TournamentId = tournament.TournamentId, }); } }
internal bool AddMatch(Hint hint, TokenEnumerator enumerator) { if (Matches.Any(m => m.Text == hint.Text)) { return(false); } Matches.Add(new HintMatch { Text = hint.Text, Optional = hint.Optional, Location = enumerator.Location.Clone() }); return(true); }
private void generateMatches(List <string> playerNames) { foreach (string name in playerNames) { Players.Add(new Player(name)); } Player[] player = Players.ToArray(); for (int i = 0; i < player.Length; i++) { for (int j = i + 1; j < player.Length; j++) { Matches.Add(new Match(player[i], player[j])); } } }
public override void Init() { // Generate matches for (int i = 0; i < Players.Count; i++) { for (int j = 0; j < i; j++) { Match match = new Match(Players.ElementAt(j), Players.ElementAt(i)); Matches.Add(match); } } // Randomize order var rnd = new Random(); Matches = Matches.OrderBy(x => rnd.Next()).ToList(); }
public void Start() { state = TournamentState.Started; for (int i = 0; i <= Teams.Count - 1; i = i + 2) { if (i == Teams.Count - 1) { Matches.Add(new Match(Teams[i], String.Empty, MatchState.Open)); //In case of odd team number } else { Matches.Add(new Match(Teams[i], Teams[i + 1], MatchState.Closed)); } } }
protected void SyncMatch(TournamentTeam team) { var m = Matches.Find(o => o.Team == team.Serial.ValueHash && !o.IsComplete); if (m == null || m.IsDisposed) { if (!IsRunning || CurrentCapacity <= CountActiveParticipants()) { return; } Matches.Add(m = new TournamentMatch(Matches.Count, this, team)); } m.Sync(this, team); }
/// <summary> /// Sets this Bracket's main data from a related BracketModel. /// Data affected includes most fields, as well as the playerlist. /// </summary> /// <param name="_model">Related BracketModel</param> protected override void SetDataFromModel(BracketModel _model) { // Call the base (Bracket) method to set common data and playerlist: base.SetDataFromModel(_model); this.NumberOfGroups = _model.NumberOfGroups; if (_model.Matches.Count > 0) { foreach (MatchModel matchModel in _model.Matches) { // Convert each MatchModel to a Match, and add: Matches.Add(matchModel.MatchNumber, new Match(matchModel)); } this.NumberOfMatches = Matches.Count; this.NumberOfRounds = Matches.Values .Max(m => m.RoundIndex); this.IsFinished = Matches.Values .All(m => m.IsFinished); } // "Recreate" the groups: List <List <IPlayer> > playerGroups = DividePlayersIntoGroups(); for (int g = 0; g < playerGroups.Count; ++g) { // Use these groups to remake the GroupRankings: GroupRankings.Add(new List <IPlayerScore>()); foreach (IPlayer player in playerGroups[g]) { // Make a new ranking object for each Player, // and add it to Rankings and GroupRankings: IPlayerScore pScore = new PlayerScore(player.Id, player.Name); Rankings.Add(pScore); GroupRankings[g].Add(pScore); } } // Go through the Matches to recalculate the current Rankings: RecalculateRankings(); if (this.IsFinalized && false == Validate()) { throw new BracketValidationException ("Bracket is Finalized but not Valid!"); } }
public List <MatchResult> FindAllMatches(List <Person> personList = null) { Matches.Clear(); if (personList == null && Persons == null) { return(new List <MatchResult>()); } else if (personList == null && Persons != null) { personList = Persons; } for (int i = 0; i < personList.Count(); i++) { for (int j = i + 1; j < personList.Count(); j++) { int equalsFound = 0; int inequalsFound = 0; foreach (BasePattern pattern in MatchingPatterns) { BasePattern.MATCH_RESULT result = pattern.Compare(personList[i], personList[j]); if (result == BasePattern.MATCH_RESULT.NOT_EQUAL) { inequalsFound++; break; } else if (result == BasePattern.MATCH_RESULT.EQUAL) { equalsFound++; } } if (inequalsFound == 0 && equalsFound > 0) { MatchResult newMatch = new MatchResult(personList[i], personList[j]); Logger.Info($"New Match! -> {newMatch.ToString()}"); Matches.Add(newMatch); OnMatchFound?.Invoke(newMatch); } } } return(Matches); }
private void AddMatch(MatchData matchData) { var regex = new Regex(@"^([0-9].11)"); var match = new InitialDataUpload.Models.Match(); match.MatchId = matchData.matchId; match.Is_Ranked = matchData.queueType.Equals("RANKED_SOLO_5x5"); match.Match_Region = dictRegion[matchData.region]; match.Pre_Change = regex.IsMatch(matchData.matchVersion); match.Players = new List <Player>(); foreach (InitialDataUpload.Models.Participant participant in matchData.participants) { var itemsBought = string.Format("{0},{1},{2},{3},{4},{5},{6}", participant.stats.item0, participant.stats.item1, participant.stats.item2, participant.stats.item3, participant.stats.item4, participant.stats.item5, participant.stats.item6); var player = new Player { Rank = dictRank[participant.highestAchievedSeasonTier], Region = dictRegion[matchData.region], Winner = participant.stats.winner, ItemsBought = itemsBought, Kills = participant.stats.kills, Deaths = participant.stats.deaths, Assists = participant.stats.assists, TripleKills = participant.stats.tripleKills, QuadraKills = participant.stats.quadraKills, PentaKills = participant.stats.pentaKills, MagicDamageDealt = participant.stats.magicDamageDealt, LargestKillingSpree = participant.stats.largestKillingSpree }; player.ChampionUsed = MatchesContext.Champions.Where(c => c.ChampionId == participant.championId).Single(); match.Players.Add(player); } match.Highest_Rank = (Rank)match.Players.Select(p => p.Rank).Max(); Matches.Add(match); }
public void ParseMatches() { var matches = GetDataByCssSelector("div[data-filter-con='live'] div[data-name='dashboard-champ-content'] div.c-events__item.c-events__item_col"); Parallel.ForEach(matches, game => { try { var id = game.FindElement(By.CssSelector("a[data-idgame]"), true)?.GetAttribute("data-idgame"); var category = game.FindElement(By.CssSelector("a[data-idgame]"), true)?.GetAttribute("data-sportid"); var link = game.FindElement(By.CssSelector("div.c-events-scoreboard a.c-events__name"), true)?.GetAttribute("href"); var time = game.FindElement(By.CssSelector("div.c-events__time"), true).Text.Replace("\r\n", ", "); var teams = game.FindElements(By.CssSelector("div.c-events__team")).Select(team => new Team(team.Text)).ToArray(); var score = game.FindElements(By.CssSelector("div.c-events-scoreboard__line")).Select(line => line.Text.Replace("\r\n", " ").Split(' ')).ToList(); for (int i = 0; i < teams.Length; i++) { teams[i].Score = score[i].Select(n => int.Parse(n)).ToArray(); } var coefficients = game.FindElements(By.CssSelector("div.c-events__item.c-events__item_col div.c-bets a")).Take(3); var coef1 = coefficients.ElementAt(0).Text; var coefDraw = coefficients.ElementAt(1).Text; var coef2 = coefficients.ElementAt(2).Text; var match = new Match { Id = int.Parse(id ?? "-1"), Category = (SportCategory)int.Parse(category ?? "0"), Uri = link, Time = time, Team1 = teams[0], Team2 = teams[1], Coef1 = coef1, Coef2 = coef2, CoefDraw = coefDraw }; Matches.Add(match); } catch (StaleElementReferenceException) { Console.WriteLine("Ошибка парсинга."); } }); Print(); }
public ComponentDirectiveVisitor(string filePath, IReadOnlyList <TagHelperDescriptor> tagHelpers, string currentNamespace) { _filePath = filePath; for (var i = 0; i < tagHelpers.Count; i++) { var tagHelper = tagHelpers[i]; // We don't want to consider non-component tag helpers in a component document. if (!tagHelper.IsAnyComponentDocumentTagHelper() || IsTagHelperFromMangledClass(tagHelper)) { continue; } if (tagHelper.IsComponentFullyQualifiedNameMatch()) { // If the component descriptor matches for a fully qualified name, using directives shouldn't matter. Matches.Add(tagHelper); continue; } _notFullyQualifiedComponents ??= new(); _notFullyQualifiedComponents.Add(tagHelper); if (currentNamespace is null) { continue; } if (tagHelper.IsChildContentTagHelper()) { // If this is a child content tag helper, we want to add it if it's original type is in scope. // E.g, if the type name is `Test.MyComponent.ChildContent`, we want to add it if `Test.MyComponent` is in scope. TrySplitNamespaceAndType(tagHelper, out var typeNamespace); if (!typeNamespace.IsEmpty && IsTypeInScope(typeNamespace, currentNamespace)) { Matches.Add(tagHelper); } } else if (IsTypeInScope(tagHelper, currentNamespace)) { // Also, if the type is already in scope of the document's namespace, using isn't necessary. Matches.Add(tagHelper); } } }
public SingleElimBracket(BracketModel _model) { // Call a helper method to copy the bracket status fields, // and to load the playerlist: SetDataFromModel(_model); /* * Since this method is extended in child classes, * we may be loading a lower bracket. * We need to add a couple checks here to make sure * we don't accidentally load lower bracket Matches * into our upper bracket. */ int totalUBMatches = Players.Count - 1; if (_model.Matches.Count > 0) { foreach (MatchModel mm in _model.Matches.OrderBy(m => m.MatchNumber)) { if (mm.MatchNumber <= totalUBMatches) { Matches.Add(mm.MatchNumber, new Match(mm)); } else { // Match doesn't belong in upper bracket, so we're done: break; } } this.NumberOfMatches = Matches.Count; this.NumberOfRounds = Matches.Values .Max(m => m.RoundIndex); } if (BracketType.SINGLE == BracketType) { RecalculateRankings(); if (this.IsFinalized && false == Validate()) { throw new BracketValidationException ("Bracket is Finalized but not Valid!"); } } }
public async Task SaveOrUpdateMatch(ChessMatch match) { await Task.Run(async() => { var matchEntity = await Matches.SingleOrDefaultAsync(x => x.id == match.Id); if (matchEntity == null) { matchEntity = new ChessMatchEntity { id = match.Id }; Matches.Add(matchEntity); } matchEntity.matchjson = JsonConvert.SerializeObject(match); if (match.History.Any()) { matchEntity.lastmove = match.History.OrderByDescending(x => x.MoveDate).First().MoveDate; } }); }
private void CreateNextMatches() { List <MatchDto> matchesPrevRound = Matches.Where(m => m.Round == CurrentRound).ToList(); CurrentRound += 1; for (int i = 0; i < matchesPrevRound.Count; i += 2) { UserReadDto winner1 = matchesPrevRound[i].Winner == Winner.One ? matchesPrevRound[i].Player1 : matchesPrevRound[i].Player2; UserReadDto winner2 = matchesPrevRound[i + 1].Winner == Winner.One ? matchesPrevRound[i + 1].Player1 : matchesPrevRound[i + 1].Player2; Matches.Add(new MatchDto(TournamentDto, winner1, winner2, CurrentRound)); } }