public async Task KickOff(Guid sessionId) { var session = _matchmakingService.GetSession(sessionId); var match = new Models.Match { Id = sessionId, HomeTeam = new TeamDetails { UserId = session.HostPlayerId } }; match.HomeTeam.Squad = BuildSquad(await _bus.RequestAsync <GetSquadRequest, GetSquadResponse>(new GetSquadRequest(match.HomeTeam.UserId))); match.AwayTeam = new TeamDetails { UserId = session.JoinedPlayerId.Value }; match.AwayTeam.Squad = BuildSquad(await _bus.RequestAsync <GetSquadRequest, GetSquadResponse>(new GetSquadRequest(match.AwayTeam.UserId))); match.KickOff = DateTime.Now; var simulatedMatch = _matchEngine.SimulateReentrant(match); await _matchRepository.CreateAsync(simulatedMatch); }
public Models.Match SimulateReentrant(Models.Match match) { match.AsAtElapsed(true); for (int minute = match.Elapsed; minute < Constants.MATCH_LENGTH_IN_MINUTES; minute++) //TODO atm its simulating the same minute again on reentrancy, is this right? { Squad inPossession = PossessionHelper.InPossession(match, out var notInPossession, out var homePossChance, out var awayPossChance); IAction action = _actionService.RollAction(); if (action != null) { var affectedSquad = action.AffectsTeamInPossession ? inPossession : notInPossession; var card = _actionService.RollCard(affectedSquad, action, match.Events); if (card != null) { var @event = action.SpawnEvent(card, affectedSquad.Id, minute, match); if (@event != null) { match.Events.Add(@event); } } } //TODO Fitness drain match.Statistics.Add(new MinuteStats(minute, inPossession.Id, homePossChance, awayPossChance)); } //extra time? return(match); }
public void SaveMatchdata2DB(IEnumerable <Json <Match> > matches) { foreach (var _pubgmatch in matches) { string matchid = _pubgmatch.AsObject().Data.MatchId; if (this.dbc.Matches.Where(_rec => _rec.Matchid == matchid).Count() == 0) { Match.Matchdata.MatchAttributes matchattr = _pubgmatch.AsObject().Data.Attributes; Database.Models.Match match = new Models.Match() { Matchid = matchid, CreatedAt = matchattr.CreatedAt, Duration = (int)matchattr.Duration.TotalSeconds, GameMode = (Models.Match.MatchGameMode)matchattr.GameMode, MapName = (Models.Match.MatchMapName)matchattr.Map, IsCustomMatch = Convert.ToInt16(matchattr.IsCustomMatch), SeasonState = (Models.Match.MatchSeasonState?)matchattr.SeasonState, Jsondata = _pubgmatch.Value }; this.dbc.Matches.Add(match); } } this.dbc.SaveChanges(); }
public StatsView(Models.Match match) { OVM = new OverviewViewModel(match); Match = match; BindingContext = OVM; InitializeComponent(); }
public IEvent SpawnEvent(Card card, Guid squadId, int minute, Models.Match match) { var oppositionsDefenceRating = RatingHelper.CurrentRating(PositionalArea.DEF, match.GetOppositionSquad(squadId), match.Events); var shootersRating = RatingHelper.CurrentRating(card.Id, match.GetSquad(squadId)); var shotOnTargetChance = (int)Math.Round(oppositionsDefenceRating + shootersRating * Constants.SHOOTER_AGAINST_DEFENDERS_MODIFIER); var randomNumber = _randomnessProvider.Next(0, shotOnTargetChance); if (randomNumber <= shootersRating * Constants.SHOOTER_AGAINST_DEFENDERS_MODIFIER) { var gkRating = RatingHelper.CurrentRating(PositionalArea.GK, match.GetOppositionSquad(squadId), match.Events); var goalChanceAccum = (int)Math.Round(gkRating + shootersRating * Constants.SHOOTER_AGAINST_GK_MODIFIER); var goalRandomNumber = _randomnessProvider.Next(0, goalChanceAccum); if (goalRandomNumber <= shootersRating * Constants.SHOOTER_AGAINST_GK_MODIFIER) { return(new Goal(minute, card.Id, squadId)); } return(new ShotOnTarget(minute, card.Id, squadId)); } return(new ShotOffTarget(minute, card.Id, squadId)); }
protected object JsonMatchResponse(Models.Match match, bool includeGames) { List <object> gameData = new List <object>(); IPlayer Challenger = match.Challenger; IPlayer Defender = match.Defender; if (includeGames) { foreach (IGame game in match.GetGames()) { gameData.Add(JsonGameResponse(game)); } } return(new { matchId = match.match.Id, matchNum = match.match.MatchNumber, ready = match.match.IsReady, finished = match.match.IsFinished, challenger = JsonPlayerDataResponse(Challenger, match.ChallengerScore()), defender = JsonPlayerDataResponse(Defender, match.DefenderScore()), games = gameData }); }
private bool isAfterTournamentStart(Models.Match match) { //TODO Determine match start (match.Time?), see if it is after tournamentStart static var Debug.WriteLine(match.Time.ToString()); return(false); }
public Match() { InitializeComponent(); Models.Match m = ((MainApplication)FindResource("AppViewModel")).Match; Console.WriteLine(m.Status); DataContext = m; }
public async Task <ActionResult> Post([FromBody] Models.Match match) { await _unitOfWork.Matches.UpdateAsync(Mapper.Map(match)); await _unitOfWork.SaveAsync(); return(Created($"Match/{match.Id}", match)); }
public void SaveMatch(Models.Match match) { if (match == null) { throw new ArgumentNullException(nameof(match)); } _context.Matches.Add(match); }
public OverviewView(Models.Match match) { OVM = new OverviewViewModel(match); Match = match; BindingContext = OVM; InitializeComponent(); //Fulltime_Label.SetBinding(Label.BindingContextProperty, OVM.Match.Result.ScoreInfo.Score[0].Name); //Halftime_Label.SetBinding(Label.BindingContextProperty,OVM.Match.Result.ScoreInfo.Score[1].Name); }
public LineUpView(Models.Match match) { OVM = new OverviewViewModel(match); BindingContext = OVM; ImageField = new Image { Aspect = Aspect.AspectFit }; ImageField.Source = ImageSource.FromResource("SportCCAPItesting.Field.png", typeof(LineUpView).GetTypeInfo().Assembly); InitializeComponent(); }
static public string ParserScore(string theHtml) { string res = ""; var doc = new HtmlAgilityPack.HtmlDocument(); HtmlAgilityPack.HtmlNode.ElementsFlags["br"] = HtmlAgilityPack.HtmlElementFlag.Empty; doc.LoadHtml(theHtml); string xpathTBody = "//div[@class='table-main']"; var tagTBody = doc.DocumentNode.SelectSingleNode(xpathTBody); if (tagTBody == null) { throw new Exception("Не обнаружен tbody"); } var allElementsWithClassTennis = doc.DocumentNode.SelectNodes("//tr[contains(@class,'stage-finished')]"); foreach (var item in allElementsWithClassTennis) { if (item.ChildNodes[2].InnerText != "Завершен") { continue; } if (item.Attributes["id"].Value.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries)[0] == "x") { continue; } string ss = item.Attributes["id"].Value.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries)[2]; res += ss + ","; MyScoreTennisEntity.Models.Match theMatch = Models.Match.GetByNumber(ss); if (theMatch == null) { theMatch = new Models.Match(); theMatch.Number = ss; theMatch.Status = 1; theMatch.Save(); } } string matchesAllHtml = tagTBody.ChildNodes[0].InnerHtml; return(res); }
public async Task <IActionResult> OnGetAsync(int?id) { if (id == null) { return(NotFound()); } Match = await _context.Match.FirstOrDefaultAsync(m => m.Id == id); if (Match == null) { return(NotFound()); } return(Page()); }
public static void ClassInit(TestContext context) { //Arrange Match = new Models.Match { TournamentId = "TID" }; var matches = new List <Models.Match> { Match }; var mockRepo = new Mock <IRepository <Models.Match> >(); mockRepo.Setup(x => x.Create(It.IsAny <Models.Match>())).Returns("matchId"); mockRepo.Setup(x => x.GetList()).Returns(matches); mockRepo.Setup((IRepository <Models.Match> x) => x.GetItem(It.IsAny <string>())).Returns((Models.Match)Match); MatchService = new MatchService(mockRepo.Object); }
public void Post([FromBody] CreateMatch SaveMatch) { var home = _dbContext.Clubs.Where(x => x.ShortCode == SaveMatch.HomeTeam).FirstOrDefault(); var away = _dbContext.Clubs.Where(x => x.ShortCode == SaveMatch.AwayTeam).FirstOrDefault(); var match = new Models.Match() { Id = Guid.NewGuid(), HomeTeam = home, AwayTeam = away, KickOff = SaveMatch.KickOff }; _dbContext.Add(match); _dbContext.SaveChanges(); }
public async Task <IActionResult> OnPostAsync(int?id) { if (id == null) { return(NotFound()); } Match = await _context.Match.FindAsync(id); if (Match != null) { _context.Match.Remove(Match); await _context.SaveChangesAsync(); } return(RedirectToPage("./Index")); }
public static Squad InPossession(Models.Match match, out Squad notInPossession, out int homeChance, out int awayChance) { homeChance = PossessionChance(match.HomeTeam.Squad, match.Events); awayChance = PossessionChance(match.AwayTeam.Squad, match.Events); var homePossession = ChanceHelper.CumulativeTrueOrFalse(homeChance, awayChance); if (homePossession) { notInPossession = match.AwayTeam.Squad; return(match.HomeTeam.Squad); } else { notInPossession = match.HomeTeam.Squad; return(match.AwayTeam.Squad); } }
public static Models.Match generatePrediction(Models.Match match) { int[] homeTeamPositions = { int.Parse(Regex.Match(match.HomeStats.position, @"\d+").Value), int.Parse(Regex.Match(match.HomeStats.HomeOrAwayPosition, @"\d+").Value) }; int[] awayTeamPositions = { int.Parse(Regex.Match(match.AwayStats.position, @"\d+").Value), int.Parse(Regex.Match(match.AwayStats.HomeOrAwayPosition, @"\d+").Value) }; match.HomeStats.PredictionPoints = Math.Round(2.5 + calculatePoints(match.HomeStats.overallLastSix) + leaguePositionPoints(homeTeamPositions[0], homeTeamPositions[1]), 2); match.AwayStats.PredictionPoints = Math.Round(calculatePoints(match.AwayStats.overallLastSix) + leaguePositionPoints(awayTeamPositions[0], awayTeamPositions[1]), 2); match.predictedResult = predictResult(match.HomeStats.PredictionPoints, match.AwayStats.PredictionPoints); match.predictionString = predictionString(match.predictedResult); match.predictedScore = predictScore(match.HomeStats.overallLast6Scored, match.AwayStats.overallLast6Scored, match.predictedResult); match.predictionMade = true; return(match); }
public static List <CurrentMatchResult> ResultsHelper(Models.Match match) { var results = new List <CurrentMatchResult> { new CurrentMatchResult() { TeamId = match.FirstTeamId, Penalty = match.FirstTeamPenalty, Score = match.FirstTeamScore, TeamName = match.FirstTeam.Name }, new CurrentMatchResult() { TeamId = match.SecondTeamId, Penalty = match.SecondTeamPenalty, Score = match.SecondTeamScore, TeamName = match.SecondTeam.Name } }; return(results); }
public IEvent SpawnEvent(Card card, Guid squadId, int minute, Models.Match match) { int randomNumber = _randomnessProvider.Next(1, 40); if (randomNumber == 1) { return(new RedCard(minute, card.Id, squadId)); } if (randomNumber >= 2 && randomNumber < 5) { var yellowCards = match.Events.Where(x => x.GetType() == typeof(YellowCard)).Select(x => x.CardId); if (yellowCards.Contains(card.Id)) { return(new RedCard(minute, card.Id, squadId)); //TODO return yellow and red event } return(new YellowCard(minute, card.Id, squadId)); } if (randomNumber >= 5) { return(new Events.Foul(minute, card.Id, squadId)); } return(null); }
//this is all pretty sloppy public HttpResponseMessage Post(Models.Match match) { var highWins = (this.context.Games.AsQueryable()) .Where(x => x.Id == ObjectId.Parse(match.GameId)) .Select(x => x.HighestScoreWins) .SingleOrDefault(); match.HighestScoreWins = highWins; match.Description = GetDescription(match, highWins); this.context.Matches.InsertOne(match); //todo: replace with linq? not sure how it will affect the .PUsh // probably better since i need to grab something about the game up there var filter = Builders <Models.Game> .Filter.Eq("Id", ObjectId.Parse(match.GameId)); var update = Builders <Models.Game> .Update .Push("MatchIds", match.Id); this.context.Games.UpdateOne(filter, update); return(new HttpResponseMessage(HttpStatusCode.OK)); }
public JsonResult MatchInfo(int tournamentId, int bracketId, int matchId) { Models.Tournament tournament = new Models.Tournament(service, tournamentId); Models.Bracket bracket = tournament.GetBracket(bracketId); Models.Match match = bracket.GetMatchById(matchId); List <object> matches = new List <object>(); matches.Add(JsonMatchResponse(match, true)); if (match != null) { status = true; message = "Match was loaded."; data = new { bracketFinished = bracket.IBracket.IsFinished, isLocked = bracket.IsLocked, matches = matches }; } return(BundleJson()); }
public void AllAwayMatchesByTeamIdShouldReturnCorrectCount() { var options = new DbContextOptionsBuilder <FooteoDbContext>() .UseInMemoryDatabase(databaseName: "AllAwayMatches_Teams_DB") .Options; var dbContext = new FooteoDbContext(options); var townsService = new TownsService(dbContext); var leaguesService = new LeaguesService(dbContext, townsService); var mockUserStore = new Mock <IUserStore <FooteoUser> >(); var userManager = new Mock <UserManager <FooteoUser> >(mockUserStore.Object, null, null, null, null, null, null, null, null); var town = townsService.CreateTown("Ruse"); var user = new FooteoUser { Age = new Random().Next(20, 30), Email = $"*****@*****.**", FirstName = "Footeo", LastName = "Player", UserName = $"footeoPlayer", Town = town, PasswordHash = "123123", Player = new Player { FullName = "Footeo Player" } }; dbContext.Users.Add(user); dbContext.SaveChanges(); userManager.Setup(u => u.RemoveFromRoleAsync(user, "Player")).Returns(Task.FromResult(IdentityResult.Success)); userManager.Setup(u => u.AddToRoleAsync(user, "PlayerInTeam")).Returns(Task.FromResult(IdentityResult.Success)); userManager.Setup(u => u.AddToRoleAsync(user, "Captain")).Returns(Task.FromResult(IdentityResult.Success)); var teamsService = new TeamsService(dbContext, townsService, leaguesService, userManager.Object, null); teamsService.CreateTeam("Team4", "TTT", user.UserName); var team = dbContext.Teams.FirstOrDefault(n => n.Name == "Team4"); for (int i = 1; i <= 4; i++) { var match = new Models.Match { HomeTeam = new Team { Name = $"HomeTeam{i}", Initials = "HT", Town = town }, AwayTeamGoals = i, HomeTeamGoals = 0, AwayTeam = team, Result = $"HomeTeam{i} 0 : {i} Team4" }; dbContext.Matches.Add(match); dbContext.SaveChanges(); } var allAwayMatches = teamsService.AllAwayMatchesByTeamId(team.Id).ToList(); var allAwayMatchesCount = allAwayMatches.Count; var expectedAwayMatchesCount = 4; Assert.AreEqual(expectedAwayMatchesCount, allAwayMatchesCount); }
public string GetMatchToken(User user, Models.Match match) { return(GenerateToken($"{user.Id}-{match.MatchId}")); }
public void DetachLocal(Models.Match match, int id) { Others.DetachLocal.Detach(_context, match, id); }
public static DAL.Entities.Match Map(Models.Match match) => new DAL.Entities.Match(match.Id, match.YellowTeamId, match.RedTeamId, match.YellowScore, match.RedScore, match.Note);
public Head2HeadView(Models.Match match) { InitializeComponent(); }
public StrokeNumberSection(PlotStyle plotStyle, int strokeNumber, IDictionary <string, List <Models.Rally> > sets, Models.Match match, object p) { NumberPlots = new List <PlotModel>(); foreach (var set in sets.Keys) { if (sets[set].Count > 0) { var statistics = new TechniqueStatistics(match, p, sets[set], strokeNumber); PlotModel plot = plotStyle.CreatePlot(); plot.Title = GetSetTitleString(set); plot.TitleFontSize = 16; plot.LegendOrientation = LegendOrientation.Horizontal; plot.LegendPlacement = LegendPlacement.Outside; plot.LegendPosition = LegendPosition.BottomCenter; plot.PlotAreaBorderThickness = new OxyThickness(1, 0, 0, 1); var categoryAxis = new CategoryAxis(); categoryAxis.Position = AxisPosition.Bottom; categoryAxis.MinorStep = 1; var linearAxis = new LinearAxis(); linearAxis.Position = AxisPosition.Left; linearAxis.MinorStep = 1; linearAxis.MajorStep = 4; linearAxis.AbsoluteMinimum = 0; linearAxis.MaximumPadding = 0.06; linearAxis.MinimumPadding = 0; var techniqueToSeries = new Dictionary <string, ColumnSeries>(); int index = 0; foreach (var number in statistics.NumberToTechniqueCountDict.Keys) { var numberCount = 0; foreach (var count in statistics.NumberToTechniqueCountDict[number].Values) { numberCount += count; } if (numberCount > 0) { categoryAxis.Labels.Add(string.Format("{0} ({1})", number, numberCount)); foreach (var technique in statistics.NumberToTechniqueCountDict[number].Keys) { var techniqueCount = statistics.NumberToTechniqueCountDict[number][technique]; if (techniqueCount > 0) { ColumnSeries series; if (techniqueToSeries.ContainsKey(technique)) { series = techniqueToSeries[technique]; } else { series = GetNewSeries(technique); techniqueToSeries[technique] = series; } series.Items.Add(new ColumnItem(techniqueCount, categoryIndex: index)); } } index++; } } foreach (var series in techniqueToSeries.Values) { plot.Series.Add(series); } plot.Axes.Add(categoryAxis); plot.Axes.Add(linearAxis); NumberPlots.Add(plot); Debug.WriteLine("{2} for stroke {0} of set {1} ready.", GetStrokeNumberString(strokeNumber), set, SectionName); } } }
public JsonResult MatchUpdate(int tournamentId, int bracketId, int matchNum, List <GameViewModel> games) { if (games != null) { if (account.IsLoggedIn()) { Models.Tournament tournament = new Models.Tournament(service, tournamentId); Models.Bracket bracket = tournament.GetBracket(bracketId); Models.Match match = bracket.GetMatchByNum(matchNum); bool validUpdate = true; if (tournament.IsAdmin(account.Model.AccountID)) { // Verify these matches exists foreach (GameViewModel gameModel in games) { PlayerSlot winner = gameModel.DefenderScore > gameModel.ChallengerScore ? PlayerSlot.Defender : PlayerSlot.Challenger; bool containsGame = match.match.Games.Any(x => x.GameNumber == gameModel.GameNumber); // Tie game check if (gameModel.ChallengerScore == gameModel.DefenderScore) { continue; } // Add the game if (!match.match.IsFinished && !containsGame) { if (!bracket.AddGame(matchNum, gameModel.DefenderScore, gameModel.ChallengerScore, winner)) { validUpdate = false; break; } } // Update the game else if (containsGame) { if (!bracket.UpdateGame(matchNum, gameModel.GameNumber, gameModel.DefenderScore, gameModel.ChallengerScore, winner)) { validUpdate = false; break; } } } // Updating of the matches happens by an event. status = bracket.UpdateMatch(bracket.IBracket.GetMatchModel(matchNum)); match = bracket.GetMatchByNum(matchNum); bool refresh = bracket.roundsModified; List <int> matchesAffected = bracket.MatchesAffectedList(matchNum); List <object> matchUpdates = new List <object>(); if (status) { message = "Current match was updated"; // Creates objects for all matches affected, including the match you're currently on foreach (int matchNumAffected in matchesAffected) { matchUpdates.Add(JsonMatchResponse(bracket.GetMatchByNum(matchNumAffected), false)); } } // Prepare data data = new { bracketFinished = bracket.IBracket.IsFinished, isLocked = bracket.IsLocked, matches = matchUpdates, refresh = refresh }; } else { message = "You are not authorized to do this."; } } else { message = "You must login to do this action."; } } else { message = "No games were received."; } return(BundleJson()); }