public HttpResponseMessage Put(GameDTO gameDTO) { HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.InternalServerError); try { if (ModelState.IsValid) { GameBusiness gameBusiness = new GameBusiness(); var result = gameBusiness.Update(gameDTO); if (result != null) { response = Request.CreateResponse(HttpStatusCode.OK, "Game successfully updated"); } else { response = Request.CreateResponse(HttpStatusCode.NotFound, "Game not found"); } } else { response = Request.CreateResponse(HttpStatusCode.BadRequest, "The request object doesn't match with the requirement"); } } catch (Exception e) { Logger.Error("GameController", "Get", e.Message); response = Request.CreateResponse(HttpStatusCode.InternalServerError, "Unexpected error"); } return response; }
public Game GetGameWithPublisher(GameDTO gameDto) { var game = new Game(); var publishers = _unitOfWork.Repository <Publisher>() .GetAll() .Where(x => gameDto.Translates.Any(z => x.Translates.Any(t => t.Name.Contains(z.PublisherName)))) .ToList(); if (publishers.Count > 0 && publishers.FirstOrDefault(x => x.Id != Guid.Empty) == null) { var mongoPublisher = publishers.First(); mongoPublisher.Id = Guid.NewGuid(); game.Publisher = mongoPublisher; game.PublisherId = mongoPublisher.Id; _unitOfWork.Repository <Publisher>().Add(mongoPublisher); } else { game.Publisher = publishers.FirstOrDefault(x => x.Id != Guid.Empty); game.PublisherId = null; game.PublisherId = (publishers.FirstOrDefault(x => x.Id != Guid.Empty) != null)? publishers.First(x => x.Id != Guid.Empty).Id:game.PublisherId; } return(game); }
public static GameModel FromEntity(GameDTO entity) => new GameModel { Name = entity.Name, GameType = entity.GameType, Players = entity.Players.Select(player => PlayerModel.FromEntity(player, entity.GameType)).ToList() };
public ResultToken StartGame(int gameId) { ResultToken result = new ResultToken(); result.Success = true; var game = gameEntities.Games.FirstOrDefault(a => a.GameId == gameId); try { if (game != null) { game.IsStarted = true; gameEntities.SaveChanges(); GameDTO gameDto = Mapping.Mapper.Map <GameDTO>(game); result.Data = gameDto; } } catch (Exception ex) { result.Success = false; Logger logger = LogManager.GetLogger("excpLogger"); logger.Error(ex); } return(result); }
public async Task <ActionResult <GameDTO> > AddGame([FromBody] GameDTO gameDTO) { var dto = _gameDTOToGame.Map(gameDTO); var result = await _gamesService.AddGame(dto); return(Ok(result)); }
public ActionResult GetGame(int gameId) { var game = _gameService.Get(gameId); var gameDto = new GameDTO(game); return(Ok(gameDto)); }
public async Task TestSetup() { SeedDTO seed = new SeedDTO { Seed = 42 }; StringContent postContent = TestUtilities.ObjToStringContent(seed); HttpClient client = TestUtilities.GetHttpClient(); HttpResponseMessage response = await client.PostAsync("newgame", postContent); string content = await response.Content.ReadAsStringAsync(); BoardDTO gameObj = JsonConvert.DeserializeObject <BoardDTO>(content); gameDTO = new GameDTO { Board = gameObj.Cards, GameID = gameObj.GameID }; for (int i = 0; i < 24; i++) { List <Card> cards = TestUtilities.FindSet(gameDTO.Board); GuessDTO guess = new GuessDTO { GameID = gameDTO.GameID, Card1 = cards[0], Card2 = cards[1], Card3 = cards[2] }; StringContent guessContent = TestUtilities.ObjToStringContent(guess); HttpResponseMessage postResponse = await client.PostAsync("submitguess", guessContent); string responseContent = await postResponse.Content.ReadAsStringAsync(); gameDTO = JsonConvert.DeserializeObject <GameDTO>(responseContent); } }
public JsonResult Delete([DataSourceRequest] DataSourceRequest request, GameDTO questionDTO) { try { //check to ensure the user owns the resources she is trying to access. if not; we get out of here. //Somebody is trying to do bad stuff. if (!ProbeValidate.IsQuestionForLoggedInUser((long)questionDTO.Id)) { ModelState.AddModelError("", "Question Delete could not be accomplished"); return(Json(ModelState.ToDataSourceResult())); } if (questionDTO != null && ModelState.IsValid) { ProbeQuestion.DeleteQuestion(this, db, questionDTO.Id); } return(Json(ModelState.IsValid ? true : ModelState.ToDataSourceResult())); } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(ex); //log to elmah ModelState.AddModelError("", ProbeConstants.MSG_UnsuccessfulOperation_STR); return(Json(ModelState.ToDataSourceResult())); } }//public JsonResult Delete([DataSourceRequest] DataSourceRequest request, QuestionDTO questionDTO)
private static void TestCreateNewGame() { GameDTO testGame = new GameDTO { Name = "Test Game", Turns = 5, Category = null, }; var players = new List<PlayerDTO>(); for(int i= 0; i<4; i++) { players.Add( new PlayerDTO { Name = "Anders", Number = i+1 }); } testGame.Players = players; var response = Client.CreateNewGame(testGame); Console.WriteLine(response.Data.Id); Console.WriteLine(response.Data.Name); }
public async Task UpdateGame(GameDTO gameDTO, CancellationToken cancellationToken = default) { await CheckGamesProperties(gameDTO, cancellationToken); var game = _mapper.Map <Game>(gameDTO); await _gameRepository.UpdateAsync(game, cancellationToken); }
async void CreatePracticeGame() { LoLLauncher.RiotObjects.Platform.Game.PracticeGameConfig cfg = new LoLLauncher.RiotObjects.Platform.Game.PracticeGameConfig(); cfg.GameName = "thelawkings" + new Random().Next().ToString(); LoLLauncher.RiotObjects.Platform.Game.Map.GameMap map = new LoLLauncher.RiotObjects.Platform.Game.Map.GameMap(); map.Description = "DUBLEBERTAN"; map.DisplayName = "DUBLEBERTAN"; map.TotalPlayers = 2; map.Name = "dummy"; map.MapId = (int)GameMode.TwistedTreeline; map.MinCustomPlayers = 1; cfg.GameMap = map; cfg.MaxNumPlayers = 6; cfg.GamePassword = "******"; cfg.GameTypeConfig = 1; cfg.AllowSpectators = "NONE"; cfg.GameMode = StringEnum.GetStringValue(GameMode.TwistedTreeline); Thread.Sleep(TimeSpan.FromMilliseconds((double)1000 * 20)); if (!m_disposed) { GameDTO game = await connection.CreatePracticeGame(cfg); if (game.Id == 0) { Logger.Push("Game failed to create", "warning", username); } else { Logger.Push("Game (" + game.Id + ") created.", "info", username); } } }
/// <summary> /// Checks the database for the lobby and if it does not exist then it adds it. /// Does not lock the database or commit /// </summary> /// <param name="lobby"></param> /// <returns>True if players need to be committed</returns> public bool RecordLobby(GameDTO lobby) { if (lobby == null) { throw new ArgumentNullException("lobby"); } lock (_lobbycache) { //Lets clear the cache if it somehow hits 1k people. //That way people who afk in lobbies don't complain about a memory leak. if (_currentlobby == 0 || _currentlobby != lobby.Id || _lobbycache.Count > 1000) { _currentlobby = lobby.Id; _lobbycache.Clear(); } } bool commit = false; foreach (PlayerParticipant plr in lobby.TeamOne.Union(lobby.TeamTwo).Where(p => p is PlayerParticipant).ToList()) { var entry = new PlayerEntry(plr); if (RecordPlayer(entry, false)) { commit = true; } } return(commit); }
internal void MapGameDTOtoEntity(Game game, GameDTO gameDTO) { game.About = gameDTO.About; game.Developer = gameDTO.Developer; game.Description = gameDTO.Description; game.Name = gameDTO.Name; game.Price = gameDTO.Price; game.Publisher = gameDTO.Publisher; game.ReleaseDate = gameDTO.ReleaseDate; foreach (var s in gameDTO.SystemRequirements) { MapSystemRequirementsDTOtoEntity(game, s); } foreach (var cr in gameDTO.CustomerReviews) { MapCustomerReviewsDTOToEntity(game, cr); } foreach (var i in gameDTO.Images) { MapImageDTOToEntity(game, i); } }
private bool OnGameDTO(GameDTO game) { switch (game.GameState) { case GameState.TERMINATED: if (inGame) { OnAdvancedOutOfPlayLoop(false); loop.Reset(); return(true); } break; case GameState.TERMINATED_IN_ERROR: if (inGame) { OnAdvancedOutOfPlayLoop(true); loop.Reset(); return(true); } break; case GameState.START_REQUESTED: inGame = true; OnStateChanged(); return(true); } return(false); }
public void Update() { var gameBusiness = new GameBusiness(); var requestObject = new GameDTO() { Id = 1, Name = "Game_Updated" }; var result = gameBusiness.Update(requestObject); Assert.IsNotNull(result); Assert.AreEqual(1, result.Id); Assert.AreEqual("Game_Updated", result.Name); requestObject = new GameDTO() { Id = 500, Name = "Game_Updated" }; result = gameBusiness.Update(requestObject); Assert.IsNull(result); }
public async Task GetFiguresOnTableTest() { //Arrange figureManager = new MockFigureManager() .MockGetFiguresForTable(); Work.SetManagers(null, null, null, figureManager); var table_good = new GameDTO { Id = ServiceDataToUse.User.Id }; var table_bad = new GameDTO { Id = 123 }; //Act var service = new GameService(Work.Object); var result_good = await service.GetFiguresOnTable(table_good); var result_bad = await service.GetFiguresOnTable(table_bad); //Assert Assert.AreEqual(result_good.Count(), 1, "Bad number of figures on the fresh table"); Assert.IsNull(result_bad, "Not 0 figures on table with bad Id"); }
public ActionResult CreateGame() { var game = _gameService.Create(); var gameDto = new GameDTO(game); return(Ok(gameDto)); }
public async Task GetGameTest() { //Arrange gameManager = new MockGameManager() .MockFindByIdAsync(); Work.SetManagers(null, gameManager); var table_good = new GameDTO { Id = 1 }; var table_bad = new GameDTO { Id = 123 }; //Act var service = new GameService(Work.Object); var result_good = await service.GetGame(table_good); var result_bad = await service.GetGame(table_bad); //Assert Assert.AreEqual(result_good.Id, table_good.Id, "Not the same id returned for good table."); Assert.IsNotNull(result_good.Opponents, "No opponents for good table"); Assert.IsNull(result_bad, "Not null table with bad table Id"); }
public async Task <IActionResult> Post([FromForm] GameDTO game) { try { GameProcessor processor = new GameProcessor(game); GameResult gameResult = processor.Process(); HistoryDTO historyDTO = new HistoryDTO { GameResultType = gameResult.GameResultType, FirstPlayerName = game.FirstPlayerName, FirstPlayerElement = game.FirstPlayerElement, SecondPlayerName = game.SecondPlayerName, SecondPlayerElement = game.SecondPlayerElement }; await historyService.AddAsync(historyMapper.ToEntity(historyDTO)); return(Ok(gameResult)); } catch (Exception ex) { return(StatusCode(500, ex.Message)); } }
public async Task ChangeTurnPriorityTest() { //Arrange gameManager = new MockGameManager() .MockFindByIdAsync() .MockTurnChange(); Work.SetManagers(null, gameManager); var table_good = new GameDTO { Id = ServiceDataToUse.Game.Id, LastTurnPlayerId = 2 }; var table_bad = new GameDTO { Id = 123, LastTurnPlayerId = 2 }; //Act var service = new GameService(Work.Object); var result_good = await service.ChangeTurnPriority(table_good); var result_bad = await service.ChangeTurnPriority(table_bad); //Assert Assert.IsTrue(result_good.Succedeed, "Error while changing turn priority for valid game"); Assert.IsFalse(result_bad.Succedeed, "Success while changing turn priority for invalid game"); }
public async Task TestReset() { SeedDTO seed = new SeedDTO { Seed = 42 }; StringContent postContent = TestUtilities.ObjToStringContent(seed); HttpClient client = TestUtilities.GetHttpClient(); HttpResponseMessage response = await client.PostAsync("newgame", postContent); string content = await response.Content.ReadAsStringAsync(); BoardDTO gameObj = JsonConvert.DeserializeObject <BoardDTO>(content); List <Card> cards = TestUtilities.FindSet(gameObj.Cards); GuessDTO guess = new GuessDTO { GameID = gameObj.GameID, Card1 = cards[0], Card2 = cards[1], Card3 = cards[2] }; StringContent guessContent = TestUtilities.ObjToStringContent(guess); HttpResponseMessage postResponse = await client.PostAsync("submitguess", guessContent); string responseContent = await postResponse.Content.ReadAsStringAsync(); gameDTO = JsonConvert.DeserializeObject <GameDTO>(responseContent); Assert.IsFalse(gameDTO.WinState, "After a reset, game marked as won still"); Assert.AreEqual(78, gameDTO.CardsRemaining, "After a reset, expected 78 cards remaining but actual was different"); }
public async Task DeteteGameTest() { //Arrang gameManager = new MockGameManager() .MockDeleteAsync() .MockFindByIdAsync(); tableManager = new MockTableManager() .MockDeleteAsync(); figureManager = new MockFigureManager() .MockDeleteAsync(); Work.SetManagers(null, gameManager, tableManager, figureManager); var tableDTO_good = new GameDTO { Id = ServiceDataToUse.Table.Id }; var tableDTO_bad = new GameDTO { Id = 124 }; //Act GameService service = new GameService(Work.Object); var details_good = await service.DeteteGame(tableDTO_good); var details_bad = await service.DeteteGame(tableDTO_bad); //Assert Assert.IsTrue(details_good.Succedeed, "Failed while deleting new table."); Assert.IsFalse(details_bad.Succedeed, "Succes while deleting bad table."); }
public ResultToken CreateGame(string playerName, int noOfPlayers, bool isPublic) { ResultToken result = new ResultToken(); result.Success = true; try { Game newGame = new Game(); newGame.StartTime = DateTime.UtcNow; newGame.PlayersCount = noOfPlayers; newGame.CreatedPlayer = playerName; newGame.IsPublic = isPublic; newGame.IsActive = true; newGame.GameCode = GenerateGameCode(); gameEntities.Games.Add(newGame); gameEntities.SaveChanges(); GameDTO gameDto = Mapping.Mapper.Map <GameDTO>(newGame); result.Data = gameDto; } catch (Exception ex) { result.Success = false; Logger logger = LogManager.GetLogger("excpLogger"); logger.Error(ex); } return(result); }
public ICollection <EventDTO> Get(GameDTO game) { List <EventDTO> events = new List <EventDTO>(); events = ies.GetByGame(game).ToList(); return(events); }
public GameDTO CreateGame(string playerName, int playerCount, bool isPrivate) { GameDTO returnObj = null; GameDTO game = new GameDTO(); game.CreatedPlayer = playerName; game.PlayersCount = playerCount; game.IsPublic = !isPrivate; try { using (APIService apiClient = new APIService()) { var temp = apiClient.MakePostRequest("api/Game/CreateGame", game); ResultToken result = apiClient.ConvertObjectToToken(temp); if (result.Success && result.Data != null) { returnObj = JsonConvert.DeserializeObject <GameDTO>(result.Data.ToString()); } } } catch (Exception ex) { Logger logger = LogManager.GetLogger("excpLogger"); logger.Error(ex); } return(returnObj); }
public ResultToken CreateGame([FromBody] GameDTO game) { using (GameService gameService = new GameService()) { var result = gameService.CreateGame(game.CreatedPlayer, game.PlayersCount, game.IsPublic); return(result); } }
static void Main(string[] args) { using (var context = new GamesStoreContext()) { var parser = new GameParser(); var repo = new Repository <GameDTO>(context); for (int i = 1; i <= 8; i++) { using (var errorLog = new StreamWriter($"..\\..\\puzzles\\errorLog.txt")) using (var reader = new StreamReader($"..\\..\\puzzles\\m2_{i}.pgn")) { var builder = new StringBuilder(); var line = string.Empty; while (!reader.EndOfStream) { builder.Clear(); builder.AppendLine(line); while (!reader.EndOfStream && !(line = reader.ReadLine()).Contains("Event")) { if (line.Contains("Date")) { line = line.Replace("-", "."); line.Replace("\"?\"", "\"????\""); } // Skip [Round] as it's not properly parsed by pgn if (line.Contains("Round")) { continue; } builder.AppendLine(line); } var text = builder.ToString(); text = text.TrimEnd('\r', '\n'); try { foreach (var game in parser.Parse(text)) { var gameDto = new GameDTO() { PgnString = text }; repo.Insert(gameDto); repo.Save(); } } catch (Exception ex) { errorLog.WriteLine($"File m2_{i}.pgn\n Error: {ex.Message}\n While parsing FEN: {text}"); } } } Console.WriteLine($"File m2_{i}.pgn processed"); } } }
public async Task <GameDTO> CreateNewGame(GameDTO gameDTO) { ApplicationUser user = await Database.UserManager.FindByNameAsync(gameDTO.Opponents.First().UserName); if (user != null) { List <ApplicationUser> opponents = new List <ApplicationUser> { user }; var newGame = new Game { Opponents = opponents }; if (gameDTO.WhitePlayerId == 0) { newGame.BlackPlayerId = user.Id; } else { newGame.WhitePlayerId = user.Id; } newGame.LastTurnPlayerId = newGame.BlackPlayerId; bool gameCreateRes = await Database.GameManager.CreateAsync(newGame); bool tableCreateRes = await Database.TableManager.CreateAsync(newGame); bool figuresCreateRes = await Database.FigureManager.CreateAsync(newGame.Id); if (!(gameCreateRes && tableCreateRes && figuresCreateRes)) { return(null); } user.Games.Add(newGame); try { await Database.SaveChangesAsync(); } catch { return(null); } return(new GameDTO { Id = newGame.Id, Opponents = GetOpponents(newGame), CreationTime = newGame.Table.CreationTime.ToShortTimeString(), LastTurnPlayerId = newGame.LastTurnPlayerId, BlackPlayerId = newGame.BlackPlayerId, WhitePlayerId = newGame.WhitePlayerId }); } return(null); }
private GameDTO SwapPlayers(GameDTO gameDTO) { PlayerDTO player = gameDTO.connectedPlayers[0]; gameDTO.connectedPlayers[0] = gameDTO.connectedPlayers[1]; gameDTO.connectedPlayers[1] = player; return(gameDTO); }
public OrderDetailDTO GetExistedOrderDetail(OrderDetail orderDetailEntity, GameDTO game, short quantity) { var orderDetailDto = Mapper.Map <OrderDetailDTO>(orderDetailEntity); orderDetailDto.Quantity += quantity; orderDetailDto.Price += quantity * game.Price; return(orderDetailDto); }
public ActionResult Edit(int GameId) { GameDTO game = service.OrderService.GetGame(GameId); var mapper = new MapperConfiguration(cfg => cfg.CreateMap <GameDTO, GameViewModel>()).CreateMapper(); var gameView = mapper.Map <GameDTO, GameViewModel>(game); return(View(gameView)); }
static void Main(string[] args) { using (var context = new GamesStoreContext()) { var parser = new GameParser(); var repo = new Repository<GameDTO>(context); for (int i = 1; i <= 8; i++) { using (var errorLog = new StreamWriter($"..\\..\\puzzles\\errorLog.txt")) using (var reader = new StreamReader($"..\\..\\puzzles\\m2_{i}.pgn")) { var builder = new StringBuilder(); var line = string.Empty; while (!reader.EndOfStream) { builder.Clear(); builder.AppendLine(line); while (!reader.EndOfStream && !(line = reader.ReadLine()).Contains("Event")) { if (line.Contains("Date")) { line = line.Replace("-", "."); line.Replace("\"?\"", "\"????\""); } // Skip [Round] as it's not properly parsed by pgn if (line.Contains("Round")) continue; builder.AppendLine(line); } var text = builder.ToString(); text = text.TrimEnd('\r', '\n'); try { foreach (var game in parser.Parse(text)) { var gameDto = new GameDTO() { PgnString = text }; repo.Insert(gameDto); repo.Save(); } } catch (Exception ex) { errorLog.WriteLine($"File m2_{i}.pgn\n Error: {ex.Message}\n While parsing FEN: {text}"); } } } Console.WriteLine($"File m2_{i}.pgn processed"); } } }
private void CompleteJsGame(RiotAccount account, GameDTO game, RiotJsTransformer.JavascriptyGame jsGame) { if (game == null) { return; } GameTypeConfigDTO gameTypeConfigDTO = account.GameTypeConfigs.FirstOrDefault<GameTypeConfigDTO>((GameTypeConfigDTO x) => x.Id == (double)game.GameTypeConfigId); if (gameTypeConfigDTO == null) { return; } if (this.lastGameState != game.GameState || this.lastPickTurn != game.PickTurn) { this.lastGameState = game.GameState; this.lastPickTurn = game.PickTurn; string heroSelectState = jsGame.HeroSelectState; string str = heroSelectState; if (heroSelectState != null) { if (str == "pre") { this.lastTurnDuration = (int)gameTypeConfigDTO.BanTimerDuration; goto Label0; } else if (str == "pick") { this.lastTurnDuration = (int)gameTypeConfigDTO.MainPickTimerDuration; goto Label0; } else { if (str != "post") { goto Label2; } this.lastTurnDuration = (int)gameTypeConfigDTO.PostPickTimerDuration; goto Label0; } } Label2: this.lastTurnDuration = 0; Label0: this.lastTurnEnds = DateTime.UtcNow + TimeSpan.FromSeconds((double)this.lastTurnDuration); } jsGame.TurnDuration = this.lastTurnDuration; jsGame.TurnEnds = this.lastTurnEnds; }
public static RiotJsTransformer.JavascriptyGame TransformGame(GameDTO game, RiotAccount account) { return RiotJsTransformer.TransformGame(game, account, account.AccountId); }
private void CompleteJsGame(RiotAccount account, GameDTO game, RiotJsTransformer.JavascriptyGame jsGame) { if (game == null) return; GameTypeConfigDTO gameTypeConfigDto = Enumerable.FirstOrDefault<GameTypeConfigDTO>((IEnumerable<GameTypeConfigDTO>) account.GameTypeConfigs, (Func<GameTypeConfigDTO, bool>) (x => x.Id == (double) game.GameTypeConfigId)); if (gameTypeConfigDto == null) return; if (this.lastGameState != game.GameState || this.lastPickTurn != game.PickTurn) { this.lastGameState = game.GameState; this.lastPickTurn = game.PickTurn; switch (jsGame.HeroSelectState) { case "pre": this.lastTurnDuration = (int) gameTypeConfigDto.BanTimerDuration; break; case "pick": this.lastTurnDuration = (int) gameTypeConfigDto.MainPickTimerDuration; break; case "post": this.lastTurnDuration = (int) gameTypeConfigDto.PostPickTimerDuration; break; default: this.lastTurnDuration = 0; break; } this.lastTurnEnds = DateTime.UtcNow + TimeSpan.FromSeconds((double) this.lastTurnDuration); } jsGame.TurnDuration = this.lastTurnDuration; jsGame.TurnEnds = this.lastTurnEnds; }
private static int GetTurnHash(GameDTO game) { int num = Math.Max(Array.IndexOf<string>(RiotJsTransformer.allTurns, game.GameState), 0); return game.PickTurn << 4 | num & 15; }
public static RiotJsTransformer.JavascriptyGame TransformGame(GameDTO game, RiotAccount account, long accountId) { if (game == null) { return new RiotJsTransformer.JavascriptyGame() { State = "none" }; } else { GameTypeConfigDTO gameTypeConfigDto = Enumerable.FirstOrDefault<GameTypeConfigDTO>((IEnumerable<GameTypeConfigDTO>) account.GameTypeConfigs, (Func<GameTypeConfigDTO, bool>) (x => x.Id == (double) game.GameTypeConfigId)) ?? new GameTypeConfigDTO(); List<BannedChampion> list = game.BannedChampions ?? new List<BannedChampion>(0); var fAnonymousType34 = new { TeamOne = Enumerable.Where<BannedChampion>((IEnumerable<BannedChampion>) list, (Func<BannedChampion, bool>) (x => x.TeamId == 100)), TeamTwo = Enumerable.Where<BannedChampion>((IEnumerable<BannedChampion>) list, (Func<BannedChampion, bool>) (x => x.TeamId == 200)) }; RiotJsTransformer.JavascriptyGame javascriptyGame = new RiotJsTransformer.JavascriptyGame() { RealmId = account.RealmId, MatchId = (long) game.Id, Name = game.Name.Trim(), State = GameJsApiService.GetGameState(game.GameState), HeroSelectState = GameJsApiService.GetGameHeroSelectState(game.GameState), TeamOne = RiotJsTransformer.ToTeam(accountId, fAnonymousType34.TeamOne, 1, (IEnumerable<IParticipant>) game.TeamOne), TeamTwo = RiotJsTransformer.ToTeam(accountId, fAnonymousType34.TeamTwo, 2, (IEnumerable<IParticipant>) game.TeamTwo), IsOwner = game.OwnerSummary != null && (long) game.OwnerSummary.AccountId == accountId, ConferenceJid = game.RoomName + ".pvp.net", ConferencePassword = game.RoomPassword, TurnHash = RiotJsTransformer.GetTurnHash(game), GameTypeConfigName = gameTypeConfigDto.Name, QueueName = game.QueueTypeName, Created = game.CreationTime, ExpiryTime = DateTime.UtcNow + TimeSpan.FromMilliseconds(game.ExpiryTime), MapId = game.MapId }; Dictionary<string, RiotJsTransformer.JavascriptyPlayer> dictionary = Enumerable.ToDictionary<RiotJsTransformer.JavascriptyPlayer, string, RiotJsTransformer.JavascriptyPlayer>(Enumerable.Where<RiotJsTransformer.JavascriptyPlayer>(Enumerable.Concat<RiotJsTransformer.JavascriptyPlayer>((IEnumerable<RiotJsTransformer.JavascriptyPlayer>) javascriptyGame.TeamOne.Members, (IEnumerable<RiotJsTransformer.JavascriptyPlayer>) javascriptyGame.TeamTwo.Members), (Func<RiotJsTransformer.JavascriptyPlayer, bool>) (x => x.InternalName != null)), (Func<RiotJsTransformer.JavascriptyPlayer, string>) (x => x.InternalName), (Func<RiotJsTransformer.JavascriptyPlayer, RiotJsTransformer.JavascriptyPlayer>) (x => x)); foreach (PlayerChampionSelectionDTO championSelectionDto in game.PlayerChampionSelections) { RiotJsTransformer.JavascriptyPlayer javascriptyPlayer; if (dictionary.TryGetValue(championSelectionDto.SummonerInternalName, out javascriptyPlayer)) { javascriptyPlayer.SpellIds = new int[2] { (int) championSelectionDto.Spell1Id, (int) championSelectionDto.Spell2Id }; javascriptyPlayer.ChampionId = championSelectionDto.ChampionId; javascriptyPlayer.SkinId = javascriptyPlayer.ChampionId * 1000 + championSelectionDto.SelectedSkinIndex; } } foreach (RiotJsTransformer.JavascriptyPlayer javascriptyPlayer in Enumerable.Select<KeyValuePair<string, RiotJsTransformer.JavascriptyPlayer>, RiotJsTransformer.JavascriptyPlayer>((IEnumerable<KeyValuePair<string, RiotJsTransformer.JavascriptyPlayer>>) dictionary, (Func<KeyValuePair<string, RiotJsTransformer.JavascriptyPlayer>, RiotJsTransformer.JavascriptyPlayer>) (x => x.Value))) { javascriptyPlayer.RealmId = account.RealmId; if (javascriptyGame.HeroSelectState == "post" || javascriptyPlayer.PickState == "pending" && javascriptyPlayer.ChampionId > 0) javascriptyPlayer.PickState = "completed"; } return javascriptyGame; } }
private static bool IsChampSelect(GameDTO game) { if (game == null) return false; switch (game.GameState) { case "PRE_CHAMP_SELECT": case "CHAMP_SELECT": case "POST_CHAMP_SELECT": return true; default: return false; } }
public JsSpectatorThing(string status, GameDTO game, string realmId, long summonerId, TimeSpan observerDelay) { Match match = InGameMatchTransformer.Transform(game, realmId); this.Status = status; this.Game = match; this.Dude = ((IEnumerable<Team>)match.Teams).SelectMany<Team, TeamMember>((Team x) => x.Members).First<TeamMember>((TeamMember x) => { long? nullable = x.SummonerId; long num = summonerId; if (nullable.GetValueOrDefault() != num) { return false; } return nullable.HasValue; }); this.StandardSpectateBegins = DateTime.UtcNow + observerDelay; }
public JsSpectatorThing(string status, GameDTO game, string realmId, long summonerId, TimeSpan observerDelay) { Match match = InGameMatchTransformer.Transform(game, realmId); this.Status = (object) status; this.Game = (object) match; this.Dude = (object) Enumerable.First<TeamMember>(Enumerable.SelectMany<Team, TeamMember>((IEnumerable<Team>) match.Teams, (Func<Team, IEnumerable<TeamMember>>) (x => (IEnumerable<TeamMember>) x.Members)), (Func<TeamMember, bool>) (x => { long? nullable = x.SummonerId; long num = summonerId; if (nullable.GetValueOrDefault() == num) return nullable.HasValue; else return false; })); this.StandardSpectateBegins = (object) (DateTime.UtcNow + observerDelay); }
public void WithGame(GameDTO game) { _game = game; Borrower = game.Borrower ?? string.Empty; }
private static string GetChampionSelectionsString(GameDTO game) { if (game.PlayerChampionSelections == null) return ""; else return string.Join<int>("/", Enumerable.Select<PlayerChampionSelectionDTO, int>((IEnumerable<PlayerChampionSelectionDTO>) game.PlayerChampionSelections, (Func<PlayerChampionSelectionDTO, int>) (x => x.ChampionId))); }
private void NotifyGameChanged(RiotAccount account, GameDTO game) { RiotJsTransformer.JavascriptyGame javascriptyGame = RiotJsTransformer.TransformGame(game, account); this.CompleteJsGame(account, game, javascriptyGame); string str = PushNotification.Serialize(javascriptyGame); if (str == this.lastGameJson) { return; } this.lastGameJson = str; JsApiService.PushJson("game:current", str); }
private void UpdateGame(RiotAccount account, GameDTO game) { GameDTO gameDTO; GameDTO gameDTO1 = JsApiService.RiotAccount.Game; if (GameNotificationService.IsGameTerminated(game)) { gameDTO = null; } else { gameDTO = game; } GameDTO gameDTO2 = gameDTO; account.Game = gameDTO2; if (JsApiService.AccountBag.Active != account) { if (gameDTO2 != null) { account.InvokeAsync<object>("gameService", "quitGame"); } return; } if (!GameNotificationService.IsChampSelect(gameDTO1) && GameNotificationService.IsChampSelect(gameDTO2)) { object[] id = new object[] { game.Id, "CHAMP_SELECT_CLIENT" }; account.InvokeAsync<object>("gameService", "setClientReceivedGameMessage", id); } if (!GameNotificationService.IsGameInProgressStrict(gameDTO1) && GameNotificationService.IsGameInProgressStrict(gameDTO2)) { this.GetFullGameAsync(account); } this.NotifyGameChanged(account, game); }
private static bool IsGameTerminated(GameDTO game) { if (game == null) { return true; } string gameState = game.GameState; string str = gameState; if (gameState != null && (str == "FAILED_TO_START" || str == "TERMINATED" || str == "TERMINATED_IN_ERROR")) { return true; } return false; }
private static bool IsGameInProgressStrict(GameDTO game) { if (game == null) { return false; } return game.GameState == "IN_PROGRESS"; }
private static bool IsChampSelect(GameDTO game) { if (game == null) { return false; } string gameState = game.GameState; string str = gameState; if (gameState != null && (str == "PRE_CHAMP_SELECT" || str == "CHAMP_SELECT" || str == "POST_CHAMP_SELECT")) { return true; } return false; }
public static RiotJsTransformer.JavascriptyGame TransformGame(GameDTO game, RiotAccount account, long accountId) { RiotJsTransformer.JavascriptyPlayer championId; if (game == null) { return new RiotJsTransformer.JavascriptyGame() { State = "none" }; } GameTypeConfigDTO gameTypeConfigDTO = account.GameTypeConfigs.FirstOrDefault<GameTypeConfigDTO>((GameTypeConfigDTO x) => x.Id == (double)game.GameTypeConfigId) ?? new GameTypeConfigDTO(); List<BannedChampion> bannedChampions = game.BannedChampions ?? new List<BannedChampion>(0); var variable = new { TeamOne = from x in bannedChampions where x.TeamId == 100 select x, TeamTwo = from x in bannedChampions where x.TeamId == 200 select x }; RiotJsTransformer.JavascriptyGame javascriptyGame = new RiotJsTransformer.JavascriptyGame() { RealmId = account.RealmId, MatchId = (long)game.Id, Name = game.Name.Trim(), State = GameJsApiService.GetGameState(game.GameState), HeroSelectState = GameJsApiService.GetGameHeroSelectState(game.GameState), TeamOne = RiotJsTransformer.ToTeam(accountId, variable.TeamOne, 1, game.TeamOne), TeamTwo = RiotJsTransformer.ToTeam(accountId, variable.TeamTwo, 2, game.TeamTwo), IsOwner = (game.OwnerSummary == null ? false : (long)game.OwnerSummary.AccountId == accountId), ConferenceJid = string.Concat(game.RoomName, ".pvp.net"), ConferencePassword = game.RoomPassword, TurnHash = RiotJsTransformer.GetTurnHash(game), GameTypeConfigName = gameTypeConfigDTO.Name, QueueName = game.QueueTypeName, Created = game.CreationTime, ExpiryTime = DateTime.UtcNow + TimeSpan.FromMilliseconds(game.ExpiryTime), MapId = game.MapId }; RiotJsTransformer.JavascriptyGame javascriptyGame1 = javascriptyGame; Dictionary<string, RiotJsTransformer.JavascriptyPlayer> dictionary = ( from x in javascriptyGame1.TeamOne.Members.Concat<RiotJsTransformer.JavascriptyPlayer>(javascriptyGame1.TeamTwo.Members) where x.InternalName != null select x).ToDictionary<RiotJsTransformer.JavascriptyPlayer, string, RiotJsTransformer.JavascriptyPlayer>((RiotJsTransformer.JavascriptyPlayer x) => x.InternalName, (RiotJsTransformer.JavascriptyPlayer x) => x); foreach (PlayerChampionSelectionDTO playerChampionSelection in game.PlayerChampionSelections) { if (!dictionary.TryGetValue(playerChampionSelection.SummonerInternalName, out championId)) { continue; } int[] spell1Id = new int[] { (int)playerChampionSelection.Spell1Id, (int)playerChampionSelection.Spell2Id }; championId.SpellIds = spell1Id; championId.ChampionId = playerChampionSelection.ChampionId; championId.SkinId = championId.ChampionId * 1000 + playerChampionSelection.SelectedSkinIndex; } foreach (RiotJsTransformer.JavascriptyPlayer realmId in from x in dictionary select x.Value) { realmId.RealmId = account.RealmId; if (!(javascriptyGame1.HeroSelectState == "post") && (!(realmId.PickState == "pending") || realmId.ChampionId <= 0)) { continue; } realmId.PickState = "completed"; } return javascriptyGame1; }
private static bool IsGameTerminated(GameDTO game) { if (game == null) return true; switch (game.GameState) { case "FAILED_TO_START": case "TERMINATED": case "TERMINATED_IN_ERROR": return true; default: return false; } }
private void NotifyGameChanged(RiotAccount account, GameDTO game) { RiotJsTransformer.JavascriptyGame jsGame = RiotJsTransformer.TransformGame(game, account); this.CompleteJsGame(account, game, jsGame); string json = PushNotification.Serialize((object) jsGame); if (json == this.lastGameJson) return; this.lastGameJson = json; JsApiService.PushJson("game:current", json); }
public void WithGame(GameDTO game) { this.game = game; Borrower = game.Borrower ?? string.Empty; Refresh(); }
private static string GetChampionSelectionsString(GameDTO game) { if (game.PlayerChampionSelections == null) { return ""; } return string.Join<int>("/", from x in game.PlayerChampionSelections select x.ChampionId); }
private void UpdateGame(RiotAccount account, GameDTO game) { GameDTO game1 = JsApiService.RiotAccount.Game; GameDTO game2 = GameNotificationService.IsGameTerminated(game) ? (GameDTO) null : game; account.Game = game2; if (JsApiService.AccountBag.Active != account) { if (game2 == null) return; account.InvokeAsync<object>("gameService", "quitGame"); } else { if (!GameNotificationService.IsChampSelect(game1) && GameNotificationService.IsChampSelect(game2)) account.InvokeAsync<object>("gameService", "setClientReceivedGameMessage", new object[2] { (object) game.Id, (object) "CHAMP_SELECT_CLIENT" }); if (!GameNotificationService.IsGameInProgressStrict(game1) && GameNotificationService.IsGameInProgressStrict(game2)) this.GetFullGameAsync(account); this.NotifyGameChanged(account, game); } }