private async void Save() { var lastMatch = MatchHistory.LastMatch; MatchRecord newMatch; if (lastMatch != null) { newMatch = lastMatch.NewRelativeRecord(CR.Value, DateTime.Now, SelectedMap); } else { await _dialogService.ShowMessage("Recording first game as a win, because there are no previous records to base it on", "Recording new match"); newMatch = new MatchRecord() { CR = CR.Value, Diff = CR.Value, Date = DateTime.Now, Map = SelectedMap, Result = MatchResult.WIN }; } MatchHistory.Add(newMatch); MessengerInstance.Send(new Messages.NewMatchRecord(newMatch)); CR = null; SelectedMap = Maps.First(); }
// Stores personal history in a dictionary. public void StorePersonalHistory(String summonerName, TextBox status) { String summonerIdUrl = Coder.GetSummonerIdUrl(region, summonerName); String summonerIdJson = reader.Request(summonerIdUrl); String summonerId = Parser.GetSummonerId(summonerIdJson); int matchNumber = 0; // loops until there is no more match history while (true) { String matchHistoryUrl = Coder.GetMatchHistoryUrl(region, summonerId, matchNumber, matchNumber + MATCH_SEARCH_LIMIT); String matchHistoryJson = reader.Request(matchHistoryUrl); // there is no more match history if (matchHistoryJson.Equals("{}") | matchHistoryJson.Equals(String.Empty)) { break; } MatchHistory matchHistory = Parser.ParseMatchHistory(matchHistoryJson); status.Text = (matchNumber + matchHistory.matches.Count) + " games found"; status.Refresh(); foreach (MatchHistoryNameSpace.Match match in matchHistory.matches) { MatchHistoryNameSpace.Participant participant = match.participants[0]; personalHistory[match.matchId] = new PersonalParticipant(match.participants[0].teamId, participant.stats.winner, participant.championId); } matchNumber += MATCH_SEARCH_LIMIT; } }
public void SymulateGroupStage() { foreach (var match in MatchPlanned.List) { match.SymulateGame(); MatchHistory.Add(match); MatchPlanned.Count--; } MatchPlanned.List = new List <Match>(); WasGroupStageSymulated = true; SortTeamsPoints(); if (TeamList.Count >= 4) { SemiA = RankingTeam[0]; SemiB = RankingTeam[1]; SemiC = RankingTeam[2]; SemiD = RankingTeam[3]; } else if (TeamList.Count >= 2) { FinalA = RankingTeam[0]; FinalB = RankingTeam[1]; } }
//Gets the last time the summoner played public static string GetLastTimePlayedStr(MatchHistory matchHistory) { var matchTimestmap = matchHistory.Matches.First().Timestamp; DateTime date = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc); DateTime lastMatchTime = date.AddMilliseconds(matchTimestmap).ToLocalTime(); var difference = (DateTime.Now - lastMatchTime); if (difference.Days > 0) { return("Played " + (difference.Days == 1 ? difference.Days + " day" : difference.Days + " days") + " ago"); } else if (difference.Days == 0) { if (difference.Hours == 0) { return("Played " + (difference.Minutes == 1 ? difference.Minutes + " minute" : difference.Minutes + " minutes") + " ago"); } else if (difference.Hours == 1) { return("Played " + difference.Hours + " hour ago"); } else { return("Played " + difference.Hours + " hours ago"); } } return("Played " + difference.Hours + " hours ago"); }
public MatchHistory Get(int id) { var lobby = _repository.Lobbies.Include(l => l.Reputations).ThenInclude(r => r.Reputation).Include(l => l.Reputations).ThenInclude(r => r.User).Include(l => l.Players).ThenInclude(p => p.User).SingleOrDefault(l => l.Id == id); var matchHistory = new MatchHistory { Id = lobby.Id, Joined = lobby.Joined.ToString("d"), Name = lobby.Name, Started = lobby.Started.HasValue, NegativeReputations = lobby.Reputations.Count(r => r.Reputation.Type == ReputationType.NEGATIVE), PositiveReputations = lobby.Reputations.Count(r => r.Reputation.Type == ReputationType.POSITIVE), Players = lobby.Players.Count(p => p.User != null && p.Position > 0), LobbySlots = new List <MatchHistoryLobbySlot>(), Reputations = lobby.Reputations.OrderBy(r => r.Reputation.Type).Select(r => new Models.UserReputation { Id = r.Id, Added = r.Added.ToString("d"), Comment = r.Comment, User = new Models.User { Name = r.User.Name, SSteamId = r.User.SteamId.ToString() }, Reputation = new Models.Reputation { Id = r.Reputation.Id, Name = r.Reputation.Name, Type = r.Reputation.Type } }).ToList() }; foreach (var lobbySlot in lobby.Players.Where(p => p.Position > 0)) { matchHistory.LobbySlots.Add(GetPlayer(lobbySlot)); } matchHistory.LobbySlots = matchHistory.LobbySlots.Where(ls => ls.Position > 0).OrderBy(ls => ls.Position).ToList(); return(matchHistory); }
/// <summary> /// Initializes a new instance of the <see cref="RiotClient"/> class. /// </summary> /// <param name="apiKey">The API key.</param> public RiotClient(string apiKey) { IChampion champion = new Champion(apiKey); ICurrentGame currentGame = new CurrentGame(apiKey); IFeaturedGames featuredGames = new FeaturedGames(apiKey); IGame game = new Game(apiKey); ILeague league = new League(apiKey); ILolStaticData lolStaticData = new LolStaticData(apiKey); ILolStatus lolStatus = new LolStatus(); IMatch match = new Match(apiKey); IMatchHistory matchHistory = new MatchHistory(apiKey); IMatchList matchList = new MatchList(apiKey); IStats stats = new Stats(apiKey); ISummoner summoner = new Summoner(apiKey); ITeam team = new Team(apiKey); this.Champion = champion; this.CurrentGame = currentGame; this.FeaturedGames = featuredGames; this.Game = game; this.League = league; this.LolStaticData = lolStaticData; this.LolStatus = lolStatus; this.Match = match; this.MatchHistory = matchHistory; this.MatchList = matchList; this.Stats = stats; this.Summoner = summoner; this.Team = team; }
public void TestMatchPoller() // still not working { MatchHistory history = new MatchHistory(); history.Matches[5].Id = 66; mockWebAPI.Setup(webAPI => webAPI.GetMatchHistory()) .Returns(history); var poller = new MatchPoller(mockWebAPI.Object, 100); MatchSummary match = null; var matches = poller.PollMatches().GetEnumerator(); int count = 0; for (int i = 0; i < 6; i++) { matches.MoveNext(); match = matches.Current; count++; } Assert.AreEqual(66, match.Id); Assert.AreEqual(6, count); }
//public void RecordEvent(String id, String eventName) //{ // var newEvent = new StateChangeEvent(id, eventName); // DocumentSession.Store(newEvent); // var key = DocumentSession.Advanced.GetDocumentId(newEvent); // GetHistory(id).Records.Add(key); //} public MatchHistory BeginHistory(String matchId) { var history = new MatchHistory(matchId); DocumentSession.Store(history); DocumentSession.SaveChanges(); return(history); }
private Func <LiveCharts.Defaults.ObservableValue, int, object> ShouldBeWeekendColoured(Brush weekendBrush) { return((item, index) => { if (index > MatchHistory.Count() - 1) { return null; } return IsWeekendDay(MatchHistory.ElementAt(index).Date) ? weekendBrush : null; }); }
public void ExampleTestWithMoq() { // Here we are saying, for this test only, if our mock object's Get // method is called with any Uri as the parameter, return the string "{}" mockClient.Setup(client => client.Get(It.IsAny <Uri>())) .Returns("{}"); // Now we can test GetMatchHistory without ever calling Steam's service. // We're testing just the logic that is in DotaWebApi, in isolation, which is // much easier than trying to test the logic of everything together. MatchHistory actual = api.GetMatchHistory(new MatchHistoryRequest()); Assert.IsNull(actual); // See: https://code.google.com/p/moq/wiki/QuickStart for more examples of using Moq. }
private void GeneratePlot() { var matchesInDateRange = MatchHistory.Where(m => Between(m, Settings.StartDate, Settings.EndDate)); var lineSeries = new LineSeries { Title = "SR", Values = new ChartValues <LiveCharts.Defaults.ObservableValue>( from r in matchesInDateRange select new LiveCharts.Defaults.ObservableValue(r.CR) ), LineSmoothness = 0, PointGeometry = DefaultGeometries.Circle, Fill = System.Windows.Media.Brushes.Transparent, DataLabels = false }; Brush weekendBrush = Brushes.DodgerBlue; lineSeries.Configuration = LiveCharts.Configurations.Mappers.Xy <LiveCharts.Defaults.ObservableValue>() .X((item, index) => index) .Y(item => item.Value) .Fill(ShouldBeWeekendColoured(weekendBrush)) .Stroke(ShouldBeWeekendColoured(weekendBrush)); var xLabels = from r in matchesInDateRange select r.Date.ToString("G"); Func <double, string> yFormatter = (i) => i.ToString(); Func <double, string> xFormatter = (i) => i.ToString("C"); if (DataSeries != null) { DataSeries.Clear(); } else { DataSeries = new SeriesCollection(); } DataSeries.Add(lineSeries); Labels = xLabels.ToArray(); YFormatter = yFormatter; XFormatter = xFormatter; YAxisStartValue = matchesInDateRange.FirstOrDefault()?.CR ?? 0; }
private MatchHistory GetMatchHistoryOfSummoner(string accountId, string region, int?startIndex = null, int?endIndex = null) { var pathBuilder = new UrlPathBuilder(); var matchHistory = new MatchHistory(); var matchList = new MatchList(); if (startIndex.HasValue && endIndex.HasValue) { matchList = GetMatchListOfSummoner(accountId, region, startIndex.Value, endIndex.Value); } else { matchList = GetMatchListOfSummoner(accountId, region); } using (var client = new HttpClient()) { try { client.DefaultRequestHeaders.Add("X-Riot-Token", ConfigWrapper.ApiKey); foreach (var matchRef in matchList.Matches) { var response = client.GetAsync(new Uri(pathBuilder.GetMatchByGameIdUrl(matchRef.GameId, region))); response.Wait(); var result = response.Result; if (result.IsSuccessStatusCode) { var readData = result.Content.ReadAsStringAsync(); readData.Wait(); var match = JsonConvert.DeserializeObject <Match>(readData.Result); foreach (var participant in match.Participants) { SummonerInfoUtils.SetParticipantCustomFields(participant, match, readData.Result); } SummonerInfoUtils.SetMatchCustomFields(match, accountId, matchRef); matchHistory.Matches.Add(match); } } } catch (Exception) {} } return(matchHistory); }
public FitnessViewModel(GeneticManagement gen) { _gpContainer = gen; int popSize = _gpContainer._population.Count; if ((popSize & (popSize - 1)) == 0) { _bracketSize = popSize; } else { for (int i = popSize; (popSize & (popSize - 1)) != 0; i--) { popSize = i; } _bracketSize = popSize; } _activeMatches = new ObservableCollection <MatchHistory>(); _finishedMatches = new ObservableCollection <MatchHistory>(); _scores = new Dictionary <GeneticTree, float>(); _gpContainer._fitnesses = Enumerable.Repeat(0.5f, (int)_gpContainer._populationSize).ToList(); BindingOperations.EnableCollectionSynchronization(_activeMatches, collectionLock); //BindingOperations.EnableCollectionSynchronization(_finishedMatches, collectionLock); foreach (var item in _gpContainer._population) { _scores.Add(item, 0); } _highlightedMatch = null; _highlightedMove = 0; _highlightMatchCommand = new RelayCommand(x => { _setHighlight((MatchHistory)x); }, x => true); _highlightForwardCommand = new RelayCommand(x => { _highlightMove(1); }, x => true); _highlightBackwardCommand = new RelayCommand(x => { _highlightMove(-1); }, x => true); _beginFitnessCommand = new RelayCommand(async x => await beginFitnessEvaluation(), x => true); MatchHistory empty = new MatchHistory(); empty.addNewState("................................................................"); _highlightMatchCommand.Execute(empty); }
public IActionResult Index(string sportName) { MatchDetails matchDetails = new MatchDetails(); try { List <Squad> leagueResponse = _matchService.GetLeagueDetails(sportName); string webroot = _env.WebRootPath; matchDetails.SquadList = leagueResponse; matchDetails.SportName = sportName; var filePath = System.IO.Path.Combine(webroot, "FantasyCard.json"); var jsonData = System.IO.File.ReadAllText(filePath); List <MatchHistory> persons = JsonConvert.DeserializeObject <List <MatchHistory> >(jsonData); List <MatchHistory> matchLst = new List <MatchHistory>(); if (persons == null) { persons = new List <MatchHistory>(); } foreach (var items in matchDetails.SquadList) { MatchHistory matchHistory = new MatchHistory(); matchHistory.matchId = items.id; matchHistory.name = items.name; matchHistory.tourId = items.tourId; matchHistory.site = sportName; matchHistory.startdate = items.startDate; persons.Add(matchHistory); } string newJson = JsonConvert.SerializeObject(persons); System.IO.File.WriteAllText(filePath, newJson); } catch (Exception ex) { string error = ex.Message; string webroot = _env.WebRootPath; var file = System.IO.Path.Combine(webroot, "error.txt"); using (StreamWriter writer = new StreamWriter(file, true)) { writer.WriteLine(DateTime.Now + ":---> " + error); } } return(View(matchDetails)); }
private void _setHighlight(MatchHistory h) { _highlightedMatch = h; if (h._states.Count != 0) { _highlightedPosition = h._states[0]; _highlightedMove = 0; _buttons = new SquareTypeIndex[Board.BOARD_SIZE]; _pieces = new PieceIndex[Board.BOARD_SIZE]; for (int i = 0; i < Board.BOARD_SIZE; i++) { _buttons[i] = new SquareTypeIndex(0, (byte)i); _pieces[i] = new PieceIndex(_highlightedPosition._pieces[i], (byte)i); } OnPropertyChanged("_buttons"); OnPropertyChanged("_pieces"); OnPropertyChanged("_highlightedMatch"); } }
public void TestMatchHistory() { var response = @" { result: { status: 1, num_results: 25, total_results: 500, results_remaining: 475, matches: [{ match_id: 295198203, match_seq_num: 268707406, start_time: 1378049271, lobby_type: 0, players: [{ account_id: 37732908, player_slot: 0, hero_id: 53 }, { account_id: 33332908, player_slot: 1, hero_id: 46 }] }] } }"; mockClient.Setup(client => client.Get(It.IsAny <Uri>())) .Returns(response); MatchHistory history = api.GetMatchHistory(new MatchHistoryRequest()); Assert.AreEqual(history.NumResults, 25); Assert.AreEqual(history.ResultsRemaining, 475); Assert.AreEqual(history.TotalResults, 500); Assert.AreEqual(history.Matches[0].Id, 295198203); Assert.AreEqual(history.Matches[0].LobbyType, 0); Assert.AreEqual(history.Matches[0].SeqNum, 268707406); Assert.AreEqual(history.Matches[0].Players[1].HeroId, 46); Assert.AreEqual(history.Matches[0].Players[1].AccountId, 33332908); Assert.AreEqual(history.Matches[0].Players[1].PlayerSlot, 1); }
public void Save(DomainEvent domainEvent) { using (var session = _documentStore.OpenSession()) { MatchHistory history = session.Load <MatchHistory>(domainEvent.SagaId); if (history == null) { history = new MatchHistory(domainEvent.SagaId); session.Store(history); } var eventWrapper = new EventWrapper(domainEvent); session.Store(eventWrapper); string key = session.Advanced.GetDocumentId(eventWrapper); history.Records.Add(key); session.SaveChanges(); } }
public static ACSMatchList GetMatchList(int startIndex, int endIndex) { String history = ""; String bearerToken = APIRequest.Instance.IDToken; Login.Session session; if (!Login.GetSession(out session)) { return(null); } MatchHistory.GetMatchHistoryUrl(out history); String acsUrl; PlatformConfig.GetConfigSetting("LCUACS", "Endpoint", out acsUrl); String region; PlatformConfig.GetConfigSetting("LoginDataPacket", "platformId", out region); String url = String.Format("{0}/v1/stats/player_history/{1}/{2}?begIndex={3}&endIndex={4}", acsUrl, region, session.accountId, startIndex, endIndex); using (WebClient webClient = new WebClient()) { webClient.Proxy = null; //Because otherwise downloads are slow webClient.Headers.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"); webClient.Headers.Add("Bearer", bearerToken); webClient.CachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache); using (MemoryStream stream = new MemoryStream(webClient.DownloadData(url))) { using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) { history = reader.ReadToEnd(); } } } ACSMatchList matchHistoryList = JsonHandler.LoadJson <ACSMatchList>(history); return(matchHistoryList); }
public void TestSteamDateConverter() { var response = @" { result: { matches: [{ start_time: 1377063945 }] } }"; mockClient.Setup(client => client.Get(It.IsAny <Uri>())) .Returns(response); MatchHistory history = api.GetMatchHistory(new MatchHistoryRequest()); var actual = history.Matches[0].StartTime; var expected = new DateTime(2013, 08, 21, 05, 45, 45); Assert.AreEqual(expected, actual); }
public MatchHistory GetMatchesById(string id, string region) { var uri = new Uri("https://" + region + ".api.riotgames.com/lol/match/v4/matchlists/by-account/" + id + "?api_key=" + Config.ApiKey); MatchHistory matchHistory = null; try { matchHistory = new HttpClient().GetFromJsonAsync <MatchHistory>(uri).Result; } catch (HttpRequestException e) { Console.WriteLine("Message :{0} ", e.Message); } catch (AggregateException e) { Console.WriteLine("Message :{0} ", e.Message); } return(matchHistory); }
public String GetShareableMatchHistoryURL(UInt64 matchId) { String url = null; if (!MatchHistory.GetMatchDetailsUrlTemplate(out url)) { return(url); } RiotClient.RegionLocale locale; if (!RiotClient.GetRegionLocale(out locale)) { return(url); } Login.Session session; if (!Login.GetSession(out session)) { return(url); } return(String.Format(url, matchId, session.accountId, locale.webLanguage)); }
private void GenerateStatistics() { string[] maps = Maps.All.Where(m => m != "N/A").ToArray(); TotalPlayed = MatchHistory.Count(); TotalWon = MatchHistory.Wins(); TotalDrawn = MatchHistory.Draws(); TotalLost = MatchHistory.Losses(); TotalWithMaps = MatchHistory.Count(r => r.Map != "N/A"); Stats = new ObservableCollection <MapStatistics>( from map in maps let matches = MatchHistory.Where(match => match.Map == map) orderby matches.Wins() descending, matches.Count() descending select new MapStatistics() { Map = map, TotalPlayed = matches.Count(), TotalWon = matches.Wins(), TotalDrawn = matches.Draws(), TotalLost = matches.Losses() } ); }
public void UndoLastAction(String matchId) { using (var session = _documentStore.OpenSession()) { MatchHistory matchHistory = session.Load <MatchHistory>(matchId); if (matchHistory == null) { return; } EventWrapper lastEvent = session.Load <EventWrapper>(matchHistory.Records).LastOrDefault(); if (lastEvent == null) { return; } string key = session.Advanced.GetDocumentId(lastEvent); session.Delete(lastEvent); matchHistory.Records.Remove(key); session.SaveChanges(); } }
public void Empty(String id) { using (var session = _documentStore.OpenSession()) { MatchHistory history = session.Load <MatchHistory>(id); if (history == null) { return; } EventWrapper[] events = session.Load <EventWrapper>(history.Records); foreach (var @event in events) { if (@event != null) { session.Delete(@event); } } session.Delete(history); session.SaveChanges(); } }
public static MatchHistory ParseMatchHistory(String json) { MatchHistory matchHistory = JsonConvert.DeserializeObject <MatchHistory>(json); return(matchHistory); }
public void AddMatchToHistory(MyMatch match) { MatchHistory.Add(match); }
public async void GetSummonerProfile(string s) { PublicSummoner Summoner = await Client.PVPNet.GetSummonerByName(String.IsNullOrWhiteSpace(s)?Client.LoginPacket.AllSummonerData.Summoner.Name : s); if (String.IsNullOrWhiteSpace(Summoner.Name)) { MessageOverlay overlay = new MessageOverlay(); overlay.MessageTitle.Content = "No Summoner Found"; overlay.MessageTextBox.Text = "The summoner \"" + s + "\" does not exist."; Client.OverlayContainer.Content = overlay.Content; Client.OverlayContainer.Visibility = Visibility.Visible; return; } SummonerNameLabel.Content = Summoner.Name; SummonerLevelLabel.Content = "Level " + Summoner.SummonerLevel; if (Summoner.SummonerLevel < 30) { LeagueHeader.Visibility = System.Windows.Visibility.Collapsed; } else { Client.PVPNet.GetAllLeaguesForPlayer(Summoner.SummonerId, new SummonerLeaguesDTO.Callback(GotLeaguesForPlayer)); } int ProfileIconID = Summoner.ProfileIconId; var uriSource = Path.Combine(Client.ExecutingDirectory, "Assets", "profileicon", ProfileIconID + ".png"); ProfileImage.Source = Client.GetImage(uriSource); PlatformGameLifecycleDTO n = await Client.PVPNet.RetrieveInProgressSpectatorGameInfo(s); if (n.GameName != null) { InGameHeader.Visibility = Visibility.Visible; InGameHeader.IsSelected = true; Ingame ingame = InGameContainer.Content as Ingame; ingame.Update(n); } else { InGameHeader.Visibility = Visibility.Collapsed; OverviewHeader.IsSelected = true; } if (Summoner.InternalName == Client.LoginPacket.AllSummonerData.Summoner.InternalName) { ChampionsTab.Visibility = System.Windows.Visibility.Visible; SkinsTab.Visibility = System.Windows.Visibility.Visible; } else { ChampionsTab.Visibility = System.Windows.Visibility.Hidden; SkinsTab.Visibility = System.Windows.Visibility.Hidden; } MatchHistory history = MatchHistoryContainer.Content as MatchHistory; history.Update(Summoner.AcctId); Overview overview = OverviewContainer.Content as Overview; overview.Update(Summoner.SummonerId, Summoner.AcctId); }
// POST: odata/ODMatchHistories public IHttpActionResult Post(MatchHistory matchHistory) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.MatchHistories.Add(matchHistory); try { db.SaveChanges(); } catch (DbUpdateException) { if (MatchHistoryExists(matchHistory.MatchId)) { return Conflict(); } else { throw; } } return Created(matchHistory); }
protected override void ActiveProfileChanged() { Records = new ObservableCollection <MatchRecord>( MatchHistory.OrderByDescending(r => r.Date) ); }
private void OnNewRecord(NewMatchRecord message) { Records = new ObservableCollection <MatchRecord>( MatchHistory.OrderByDescending(r => r.Date) ); }
public async Task <object> beginFitnessEvaluation() { if (_gpContainer._fitnessType == ChessTournamentType.SINGLE_ELIMINATION) { while (_bracketSize > 1) { List <Task <int> > tasks = new List <Task <int> >(); List <Pairing> bracket = (List <Pairing>)getPairings(); foreach (var pairing in bracket) { Task <int> t = new Task <int>(() => { MatchHistory hist = new MatchHistory(pairing); lock (collectionLock) { App.Current.Dispatcher.Invoke(() => _activeMatches.Add(hist)); _activeMatches = new ObservableCollection <MatchHistory>(_activeMatches); OnPropertyChanged("_activeMatches"); } Process p = new Process(); p.StartInfo.FileName = "pairing.exe"; p.StartInfo.Arguments = $"{_gpContainer._evalDepth} \"{Board.DEFAULT_POSITION}\" \"{pairing._white._rpn}\" \"{pairing._black._rpn}\""; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.OutputDataReceived += new DataReceivedEventHandler((sender, e) => { lock (collectionLock) { float balance = float.NaN; bool status = float.TryParse(e.Data, NumberStyles.Float, CultureInfo.InvariantCulture, out balance); if (status == false) { hist.addNewState(e.Data); } else { hist._materialBonus = balance; } } }); p.Start(); p.BeginOutputReadLine(); p.WaitForExit(); lock (collectionLock) { App.Current.Dispatcher.Invoke(() => _activeMatches.Remove(hist)); _activeMatches = new ObservableCollection <MatchHistory>(_activeMatches); OnPropertyChanged("_activeMatches"); App.Current.Dispatcher.Invoke(() => _finishedMatches.Add(hist)); _finishedMatches = new ObservableCollection <MatchHistory>(_finishedMatches); OnPropertyChanged("_finishedMatches"); } int result = p.ExitCode; lock (scoresLock) { switch (result) { case 1: hist._state = MatchState.WIN_WHITE; _scores[pairing._white] += 1; break; case 2: hist._state = MatchState.WIN_BLACK; _scores[pairing._black] += 1; break; case 3: hist._state = MatchState.DRAW; _scores[pairing._white] += 0.5f; _scores[pairing._black] += 0.5f; break; } if (hist._materialBonus < 0) { _scores[pairing._black] += Math.Abs(hist._materialBonus); _scores[pairing._black] = (float)Math.Round(_scores[pairing._black], 1); } else { _scores[pairing._white] += Math.Abs(hist._materialBonus); _scores[pairing._white] = (float)Math.Round(_scores[pairing._white], 1); } if (hist._state == MatchState.WIN_WHITE && hist._materialBonus > 0.25f) { _scores[pairing._white] += 5; } else if (hist._state == MatchState.WIN_BLACK && hist._materialBonus < -0.25f) { _scores[pairing._black] += 5; } _scores = new Dictionary <GeneticTree, float>(_scores); OnPropertyChanged("_scores"); } return(0); }); tasks.Add(t); t.Start(); } await Task.WhenAll(tasks); _gpContainer._population.OrderByDescending(x => _scores[x]); _gpContainer._fitnesses = _scores.Values.OrderByDescending(x => x).ToList(); _bracketSize /= 2; } } else { List <Task <int> > tasks = new List <Task <int> >(); List <List <Pairing> > bracket = (List <List <Pairing> >)getPairings(); foreach (var pairingList in bracket) { Task <int> t = new Task <int>(() => { foreach (var pairing in pairingList) { MatchHistory hist = new MatchHistory(pairing); lock (collectionLock) { App.Current.Dispatcher.Invoke(() => _activeMatches.Add(hist)); _activeMatches = new ObservableCollection <MatchHistory>(_activeMatches); OnPropertyChanged("_activeMatches"); } Process p = new Process(); p.StartInfo.FileName = "pairing.exe"; p.StartInfo.Arguments = $"{_gpContainer._evalDepth} \"{Board.DEFAULT_POSITION}\" \"{pairing._white._rpn}\" \"{pairing._black._rpn}\""; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.OutputDataReceived += new DataReceivedEventHandler((sender, e) => { float balance = float.NaN; bool status = float.TryParse(e.Data, NumberStyles.Float, CultureInfo.InvariantCulture, out balance); if (status == false) { hist.addNewState(e.Data); } else { hist._materialBonus = balance; } }); p.Start(); p.BeginOutputReadLine(); p.WaitForExit(); lock (collectionLock) { App.Current.Dispatcher.Invoke(() => _activeMatches.Remove(hist)); _activeMatches = new ObservableCollection <MatchHistory>(_activeMatches); App.Current.Dispatcher.Invoke(() => _finishedMatches.Add(hist)); _finishedMatches = new ObservableCollection <MatchHistory>(_finishedMatches); OnPropertyChanged("_activeMatches"); OnPropertyChanged("_finishedMatches"); } int result = p.ExitCode; lock (scoresLock) { switch (result) { case 1: hist._state = MatchState.WIN_WHITE; _scores[pairing._white] += 1; break; case 2: hist._state = MatchState.WIN_BLACK; _scores[pairing._black] += 1; break; case 3: hist._state = MatchState.DRAW; _scores[pairing._white] += 0.5f; _scores[pairing._black] += 0.5f; break; } if (hist._materialBonus < 0) { _scores[pairing._black] += Math.Abs(hist._materialBonus); _scores[pairing._black] = (float)Math.Round(_scores[pairing._black], 1); } else { _scores[pairing._white] += Math.Abs(hist._materialBonus); _scores[pairing._white] = (float)Math.Round(_scores[pairing._white], 1); } _scores = new Dictionary <GeneticTree, float>(_scores); OnPropertyChanged("_scores"); } } return(0); }); tasks.Add(t); t.Start(); } await Task.WhenAll(tasks); _gpContainer._population.OrderByDescending(x => _scores[x]); _gpContainer._fitnesses = _scores.Values.OrderByDescending(x => x).ToList(); } _gpContainer.calculatePositions(); return(Task.FromResult <object>(null)); }