public HttpResponseMessage Put([FromBody] CreateGameModel model) { if (!ModelState.IsValid) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } IDictionary <string, string> languagesNames = new Dictionary <string, string>(); IDictionary <string, string> languagesDescriptions = new Dictionary <string, string>(); languagesNames.Add("ru", model.Name); languagesDescriptions.Add("ru", model.Description); if (model.IsContainEnglishTranslation) { languagesNames.Add("en", model.EnglishName); languagesDescriptions.Add("en", model.EnglishDescription); } int gameId = _gameService.Create( model.Key, languagesNames, languagesDescriptions, model.Price, model.UnitsInStock, model.Discounted, model.PublishingDate, model.GenresIds, model.PlatformTypesIds, model.PublishersIds); return(Request.CreateResponse(HttpStatusCode.Created, gameId)); }
public BlackJackGameModel CreateGame([FromBody] CreateGameModel createGameModel) { var newGameId = _gameService.CreateGame(createGameModel.PlayerName); var game = _gameService.GetGameById(newGameId); return(game != null?ToModel(game) : null); }
public IActionResult AddGame(CreateGameModel gameToAdd) { var gameList = context.GetAllGamesFromDatabase(); foreach (var game in gameList) { if (game.Name == gameToAdd.Name) { ModelState.AddModelError("error", "Could not add game: Duplicate found. "); } } if (gameToAdd.Year == 0) { ModelState.AddModelError("error", "Year can not be empty. "); return(BadRequest(ModelState)); } else if (gameToAdd.Developer == "Choose Developer..." || gameToAdd.Publisher == "Choose Publisher...") { ModelState.AddModelError("error", "Publisher/Developer can not be empty. "); return(BadRequest(ModelState)); } else if (!ModelState.IsValid) { return(BadRequest(ModelState)); } else { context.AddGame(gameToAdd); return(Ok($"Added {gameToAdd.Name}")); } }
public async Task <IWriterResult> CreateGame(CreateGameModel model) { using (var context = DataContextFactory.CreateContext()) { if (await GameNameExists(context, model.Name)) { return(new WriterResult(false, "Game with name already exists")); } context.Games.Add(new Entity.Game { Name = model.Name, Description = model.Description, Type = model.Type, Status = Enums.GameStatus.NotStarted, Platform = model.Platform, Width = model.Width, Height = model.Height, ClicksPerSecond = model.ClicksPerSecond, Rank = model.Rank, Timestamp = DateTime.UtcNow }); await context.SaveChangesAsync(); return(new WriterResult(true)); } }
static public void AssignPlayerCookies(CreateGameModel model, Microsoft.AspNetCore.Http.HttpResponse Response) { CookieOptions cookie = new CookieOptions(); cookie.Expires = DateTime.Now.AddHours(1); Response.Cookies.Append("gameid", model.GameId.ToString(), cookie); }
public IActionResult AddPlayer(CreateGameModel model) { var gameId = model.gameId; var game = GetTotalGameInfo(gameId); CreateGameModel postBackModel = new CreateGameModel(); if (ModelState.IsValid) { AddPlayer playerData = new AddPlayer(); playerData.Name = model.ludoplayer.name; playerData.Color = model.ludoplayer.playerColor; var request = new RestRequest($"api/ludo/{gameId}/players", Method.POST); request.RequestFormat = DataFormat.Json; request.AddJsonBody(playerData); IRestResponse addPlayerRequest = _client.Post(request); var postedgame = GetTotalGameInfo(gameId); postBackModel.ludoPlayers = postedgame.ludoPlayers; postBackModel.numberOfPlayers = postedgame.numberOfPlayers; postBackModel.gameId = postedgame.gameId; Log.Information("Added player with name: {nameOfPlayer}" + " with color: {playerColor}" + " and gameId: {gameId}", model.ludoplayer.name, model.ludoplayer.playerColor, gameId); return(View("GameConfiguration", postBackModel)); } else { postBackModel.ludoPlayers = game.ludoPlayers; postBackModel.numberOfPlayers = game.numberOfPlayers; postBackModel.gameId = game.gameId; return(View("GameConfiguration", postBackModel)); } }
public IActionResult CreateGame(CreateGameModel model) { // Create game model.GameId = ApiMethods.CreateGame(client); logger.LogInformation("User created a new game."); // Add all players that aren't null to the game. if (model.Player1Name != null) { ApiMethods.AddPlayer(model.GameId, model.Player1Name, "0", client); logger.LogInformation($"User added player: {model.Player1Name}"); } if (model.Player2Name != null) { ApiMethods.AddPlayer(model.GameId, model.Player2Name, "1", client); logger.LogInformation($"User added player: {model.Player2Name}"); } if (model.Player3Name != null) { ApiMethods.AddPlayer(model.GameId, model.Player3Name, "2", client); logger.LogInformation($"User added player: {model.Player3Name}"); } if (model.Player4Name != null) { ApiMethods.AddPlayer(model.GameId, model.Player4Name, "3", client); logger.LogInformation($"User added player: {model.Player4Name}"); } // Set cookies ApiMethods.AssignPlayerCookies(model, Response); return(RedirectToAction("Lobby")); }
/* public members */ public static void CreateGame(int userId, CreateGameModel gameModel) { ValidateGameTitle(gameModel.Title); ValidateGamePassword(gameModel.Password); ValidateUserNumber(gameModel.Number); var context = new BullsAndCowsEntities(); using (context) { var redUser = GetUser(userId, context); var gameOpenStatus = context.GameStatuses.First(st => st.Status == GameStatusOpen); var game = new Game() { Title = gameModel.Title, Password = gameModel.Password, RedUser = redUser, RedUserNumber = gameModel.Number, GameStatus = gameOpenStatus }; context.Games.Add(game); context.SaveChanges(); } }
public ActionResult CreateGame(CreateGameModel model) { var existing = Game.GameList.Where(g => g.Name == model.Name).FirstOrDefault(); if (existing == null) { if (string.IsNullOrEmpty(model.Name)) { model.Name = model.PlayerName + " " + DateTime.Now.ToString("hh:mm"); } var newGame = new Game() { DebugAllowed = model.DebugAllowed, Name = model.Name, GameId = Guid.NewGuid().ToString() }; Game.GameList.Add(newGame); var joinModel = new JoinModel() { Name = model.PlayerName, GameId = newGame.GameId }; return(Join(joinModel)); } else { var joinModel = new JoinModel() { Name = model.PlayerName, GameId = existing.GameId }; return(Join(joinModel)); } }
public IHttpActionResult CreateGame(CreateGameModel createGameModel) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var currentUserId = this.User.Identity.GetUserId(); var game = new Game() { Name = createGameModel.Name, RedUser = this.Data.Users.Find(currentUserId), State = GameState.WaitingForOpponent, RedUserNumber = int.Parse(createGameModel.Number) }; this.Data.Games.Add(game); this.Data.SaveChanges(); var location = Url.Link("DefaultApi", new { id = game.Id }); var gameModel = (new Game[] { game }).AsQueryable() .Select(GameModel.FromGame) .First(); return(Created <GameModel>(location, gameModel)); }
public ActionResult <GameFullStateModel> CreateGame([FromBody] CreateGameModel createParameters) { return(_gameCreationService.CreateGame(createParameters)); // return new GameFullStateModel // { // CurrentPlayer = "red", // HasScrolled = false, // PlayerState = new List<PlayerState> // { // new PlayerState { // Coordinates = new Models.Coordinates { // Row = 0, // Column = 0 // }, // Name = "red", // Type = "red" // } // }, // ID = Guid.NewGuid().ToString(), // IsMoving = false, // Tiles = Enumerable.Range(0, 10) // .SelectMany(row => Enumerable.Range(0, 10) // .Select(column => new GameFullStateModel.Tile // { // Directions = GenerateDirections(), // Coordinates = new Models.Coordinates { Row = row, Column = column } // }) // ).ToList() // }; }
public void ShouldCreateGame() { var model = new CreateGameModel { Description = "Description", Discounted = false, EnglishDescription = "EnglishDescription", EnglishName = "EnglishName", Key = "Key", GenresIds = new List <int>(), IsContainEnglishTranslation = true, Name = "Name", PlatformTypesIds = new List <int>(), Price = 10, PublishersIds = new List <int>(), UnitsInStock = 10, PublishingDate = DateTime.UtcNow }; _gameService.Setup(m => m.Create(It.IsAny <CreatingGameDto>())); HttpResponseMessage response = _gamesController.Put(model); _gameService.Verify(m => m.Create(It.IsAny <CreatingGameDto>()), Times.AtLeastOnce); Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); }
public async Task CreateGame() { var languageId = await Fixture.CreateDefaultLanguage(); var userId = await Fixture.CreateDefaultUser(); var gamesRepository = Fixture.GetService <IGamesRepository>(); var createModel = new CreateGameModel { Code = "gamecode1", LanguageId = languageId, OwnerId = userId, Name = "Test game", ShowAdultContent = true, PointsLimit = 6, }; var game = await gamesRepository.CreateGame(createModel); Assert.NotNull(game); Assert.True(game.ShowAdultContent); Assert.Equal(languageId, game.LanguageId); Assert.Equal(userId, game.OwnerId); Assert.Equal("Test game", game.Name); Assert.Equal(GameStatusEnum.InProgress, game.Status); Assert.Equal(6, game.PointsLimit); TestHelper.AssertNumberOfFields <CreateGameModel>(6); }
public IHttpActionResult Create(CreateGameModel createGame) { if (!this.ModelState.IsValid) { return this.BadRequest(this.ModelState); } var userId = this.User.Identity.GetUserId(); var user = this.BullsAndCowsData.Users.All().FirstOrDefault(u => u.Id == userId); var newGame = new Game { RedId = userId, Red = user, DateCreated = DateTime.Now, Name = createGame.Name, GameState = GameState.WaitingForOpponent, RedNumber = createGame.Number }; this.BullsAndCowsData.Games.Add(newGame); this.BullsAndCowsData.SaveChanges(); var createdGameModel = new GameModel(newGame); return this.CreatedAtRoute("DefaultApi", new { id = createdGameModel.Id }, createdGameModel); }
public static CreatingGameDto ToCreatingDto(this CreateGameModel model) { Dictionary <string, string> languagesNames = new Dictionary <string, string>(); Dictionary <string, string> languagesDescriptions = new Dictionary <string, string>(); languagesNames.Add("ru", model.Name); languagesDescriptions.Add("ru", model.Description); if (model.IsContainEnglishTranslation) { languagesNames.Add("en", model.EnglishName); languagesDescriptions.Add("en", model.EnglishDescription); } return(new CreatingGameDto { Key = model.Key, LanguagesNames = languagesNames, LanguagesDescriptions = languagesDescriptions, Price = model.Price, UnitsInStock = model.UnitsInStock, Discounted = model.Discounted, PublishingDate = model.PublishingDate, GenreIds = model.GenresIds, PlatformTypeIds = model.PlatformTypesIds, PublisherIds = model.PublishersIds }); }
public async Task ThrowForDuplicatedCode() { var languageId = await Fixture.CreateDefaultLanguage(); var userId = await Fixture.CreateDefaultUser(); var gamesRepository = Fixture.GetService <IGamesRepository>(); var createModel = new CreateGameModel { Code = "gamecode1", LanguageId = languageId, OwnerId = userId, Name = "Test game", ShowAdultContent = true }; Func <Task> createTwoGames = () => Task.Run(async() => { var id = await gamesRepository.CreateGame(createModel); id = await gamesRepository.CreateGame(createModel); }); var ex = await Assert.ThrowsAnyAsync <Microsoft.EntityFrameworkCore.DbUpdateException>(createTwoGames); Assert.NotNull(ex); }
public GameFullStateModel CreateGame(CreateGameModel gameParameters) { if (gameParameters.PlayerNames == null || gameParameters.PlayerNames.Count < 1 || gameParameters.PlayerNames.Count > 4) { throw new ArgumentOutOfRangeException("Wrong number of players"); } var id = Guid.NewGuid().ToString(); var possiblePlayers = new [] { ("red", 0, 0), ("green", 0, 10), ("blue", 10, 0), ("yellow", 10, 10) };
public IHttpActionResult JoinGame(int id, CreateGameModel model) { if (!this.ModelState.IsValid) { return(this.BadRequest(this.ModelState)); } if (model.Number.ToString().Length != 4) { return(this.BadRequest("Please enter number with 4 digits")); } if (ContainsDuplicates(model.Number)) { return(this.BadRequest("Your number should consist of 4 different digits")); } var gameToJoin = this.ApplicationData.Games.Find(id); if (gameToJoin == null) { return(this.NotFound()); } var currentPlayerId = this.User.Identity.GetUserId(); if (gameToJoin.RedPlayerId == currentPlayerId) { return(this.BadRequest("A game, created by a user, cannot be joined by the same user")); } if (gameToJoin.BluePlayerId == currentPlayerId) { return(this.BadRequest("You are already playing in this game")); } gameToJoin.BluePlayerId = currentPlayerId; gameToJoin.BluePlayerNumber = model.Number; var generatedRandomNumber = random.Next(0, 2); if (generatedRandomNumber == 0) { gameToJoin.GameState = GameState.RedInTurn; } else { gameToJoin.GameState = GameState.BlueInTurn; } this.ApplicationData.SaveChanges(); return(Ok(new { result = string.Format(@"You joined game ""{0}""", gameToJoin.Name) })); }
public async Task <IActionResult> Create() { CreateGameModel createGame = new CreateGameModel(); var genres = await _commonService.GetAllGenres(); List <SelectListItem> listItems = _mapper.Map <IEnumerable <Genre>, List <SelectListItem> >(genres); createGame.Genres = listItems; return(View(createGame)); }
public void DuplicateNamedGameIsCatchAndNotAllowed(string tName) { var vDocumentStore = GetEmbeddedDatabase; var vModel = new CreateGameModel {Name = tName}; var vCommand = new CreateGameCommand(vDocumentStore, vModel); vCommand.Execute(); Assert.AreEqual(eGameCreationStatus.DuplicateName, vCommand.Execute()); }
public HttpResponseMessage CreateGame(string sessionKey, [FromBody] CreateGameModel gameModel) { var response = this.PerformOperation(() => { var userId = UsersRepository.LoginUser(sessionKey); GamesRepository.CreateGame(userId, gameModel); }); return(response); }
public HttpResponseMessage Put([FromBody] CreateGameModel model) { if (!ModelState.IsValid) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState)); } int gameId = _gameService.Create(model.ToCreatingDto()); return(Request.CreateResponse(HttpStatusCode.Created, gameId)); }
public Task CreateGame(CreateGameModel tCreateGameModel) { return Task.Factory.StartNew( () => { var vCommand = mCommandFactory.CreateCreateGameCommand(tCreateGameModel); vCommand.Execute(); }); }
public async Task <IHttpActionResult> Create(CreateGameModel model) { if (!model.SelfPlaying && string.IsNullOrEmpty(model.OpponentId) && model.OpponentExtInfo == null) { return(InternalServerError(new Exception("Not engouh info"))); } string userId = User.Identity.GetUserId(); try { var gameId = await _gameService.CreateAsync(userId, model); // if self-playing - auto accept game if (model.SelfPlaying) { await Accepted(gameId, null); RecurringJob.AddOrUpdate <IGameAiFactory>(gameId, p => p.AnayticForGame(gameId), Cron.MinuteInterval(_gameAiSettings.Interval)); } if (!string.IsNullOrEmpty(model.OpponentId) || !string.IsNullOrEmpty(model.OpponentExtInfo?.Key)) { var opponent = await _userService.GetByIdAsync(model.OpponentId) ?? await _userService.GetBySocialInfoAsync(model.OpponentExtInfo); var user = await _userService.GetByIdAsync(userId); if (opponent != null && user != null) { var inviteModel = new NotifyGameInviteModel { CurrentUser = opponent, Opponent = user }; BackgroundJob.Enqueue <INotifySenderProvider>( a => a.SendNotify(Mapper.Map <List <NotifyTokenDto> >(opponent.Tokens), gameId, "GameInvite", "icon", Smart.Format(_notifySettings.GameInviteTitle, inviteModel), Smart.Format(_notifySettings.GameInviteMessage, inviteModel))); } } return(Ok(new CreateGameModelResult { Id = gameId })); } catch (KeyNotFoundException ex) { return(InternalServerError(ex)); } }
public IActionResult Create([FromBody] CreateGameModel model) { if (model.Size < 0) { return(BadRequest("Board size can't be less than 0.")); } _builder.WithBoardSize(model.Size); var game = _builder.Build(); var report = _simulator.Simulate(_gameHost, game); return(Ok(report)); }
public IActionResult CreateGame(CreateGameModel request) { if (request.HomeTeamId == request.AwayTeamId) { return(RedirectToAction("Index", "Game", new { errorMsg = $"You must select two different teams." })); } var errorMessage = ""; var paramList = new Parameter[2]; paramList[0] = new Parameter("apiToken", Connector.CurrentApiToken, ParameterType.QueryString); paramList[1] = new Parameter("teamId", request.HomeTeamId, ParameterType.QueryString); List <Player> HomeTeamPlayers = this.ApiClient.Get <List <Player> >("Players/ByTeam", paramList, ref errorMessage); errorMessage = ""; paramList = new Parameter[2]; paramList[0] = new Parameter("apiToken", Connector.CurrentApiToken, ParameterType.QueryString); paramList[1] = new Parameter("teamId", request.AwayTeamId, ParameterType.QueryString); List <Player> AwayTeamPlayers = this.ApiClient.Get <List <Player> >("Players/ByTeam", paramList, ref errorMessage); if (HomeTeamPlayers == null || AwayTeamPlayers == null) { return(RedirectToAction("Index", "Game", new { errorMsg = $"Error retrieving team player lists." })); } if (HomeTeamPlayers.Count < 5 || AwayTeamPlayers.Count < 5) { return(RedirectToAction("Index", "Game", new { errorMsg = $"Teams must both have at least 5 players to play." })); } CreateGameRequest apiRequest = new CreateGameRequest { ApiToken = Connector.CurrentApiToken, LeagueKey = Connector.League.LeagueKey, HomeTeamId = request.HomeTeamId, AwayTeamId = request.AwayTeamId, SeasonId = Connector.Season.SeasonId }; errorMessage = ""; Connector.Game = this.ApiClient.Post <Game>("Game/Create", JsonConvert.SerializeObject(apiRequest), ref errorMessage); Connector.GameScore = null; if (Connector.Game != null) { SetupConnectorAndSettingsForNewGame(); return(RedirectToAction("Index", "Game", new { actionMsg = $"New game created!" })); } return(RedirectToAction("Index", "Game", new { errorMsg = $"Error creating game: {errorMessage}" })); }
public void CreatesGameInRaven(string tName) { var vDocumentStore = GetEmbeddedDatabase; var vModel = new CreateGameModel {Name = tName}; var vCommand = new CreateGameCommand(vDocumentStore, vModel); vCommand.Execute(); using(var vSession = vDocumentStore.OpenSession()) { Assert.IsNotNull(vSession.Load<Game>("Games/" + tName)); } }
public async Task <ActionResult> CreateGameModal(CreateGameModel model) { if (!ModelState.IsValid) { return(View(model)); } var result = await GameWriter.CreateGame(model); if (!ModelState.IsWriterResultValid(result)) { return(View(model)); } return(CloseModalSuccess()); }
// Use this for initialization public override void Start() { base.Start(); m_createGameModel = new CreateGameModel(this); createGameView.CreateGameController = this; createGameView.Start(); // Fade in the background m_readyForInput = false; Fader.AttachFaderTo(this.gameObject, Color.black, Fader.eFadeType.fadeIn, 1.0f, () => { m_readyForInput = true; }); }
public async Task <IActionResult> Create(CreateGameModel game) { var genres = await _commonService.GetAllGenres(); List <SelectListItem> listItems = _mapper.Map <IEnumerable <Genre>, List <SelectListItem> >(genres); game.Genres = listItems; if (ModelState.IsValid) { await _gamesService.AddGame(game); return(RedirectToAction(nameof(GamesController.Index), new { pageNumber = 1 })); } return(View(game)); }
public IActionResult EditGame(string nameOfGameToEdit, CreateGameModel gameToEdit) { if (gameToEdit.Year == 0) { ModelState.AddModelError("error", "Year can not be empty"); return(BadRequest(ModelState)); } else if (ModelState.IsValid) { context.EditGame(nameOfGameToEdit, gameToEdit); return(Ok($"{nameOfGameToEdit} has been edited.")); } else { return(BadRequest(ModelState)); } }
public IActionResult CreateGame() { var request = new RestRequest("api/ludo/", Method.POST); IRestResponse <int> ludoGameResponse = _client.Execute <int>(request); var gameId = ludoGameResponse.Data; var game = GetTotalGameInfo(gameId); var model = new CreateGameModel(); model.numberOfPlayers = game.numberOfPlayers; model.ludoPlayers = game.ludoPlayers ?? new List <LudoPlayer>(); model.gameId = game.gameId; //var gameModel = GetTotalGameInfo(gameId); Log.Information("Created game with gameId: {gameId}", gameId); return(View("~/Views/Ludo/GameConfiguration.cshtml", model)); }
public IHttpActionResult CreateGame(CreateGameModel gameModel) { if (!this.ModelState.IsValid) { return(this.BadRequest(this.ModelState)); } if (gameModel.Number.ToString().Length != 4) { return(this.BadRequest("Please enter number with 4 digits")); } if (ContainsDuplicates(gameModel.Number)) { return(this.BadRequest("Your number should consist of 4 different digits")); } var userId = this.User.Identity.GetUserId(); var game = new Game { Name = gameModel.Name, RedPlayerId = userId, RedPlayerNumber = gameModel.Number, GameState = GameState.WaitingForOpponent, DateCreated = DateTime.Now, isFinished = false }; var addedGame = this.ApplicationData.Games.Add(game); this.ApplicationData.SaveChanges(); var gameModelToSend = new GameModel(); gameModelToSend.Name = addedGame.Name; gameModelToSend.Id = addedGame.Id; gameModelToSend.Blue = "No blue player yet"; gameModelToSend.Red = this.User.Identity.Name; gameModelToSend.GameState = GameState.WaitingForOpponent.ToString();; gameModelToSend.DateCreated = addedGame.DateCreated; return(Created("api/games", gameModelToSend)); }
public async Task <GameListItem> CreateGame(CreateGameModel model) { var userId = GetUserIdByCurrentConnectionId(); if (GetGamesAwaitingForSecondPlayer().Any(g => g.UserId == userId)) { throw new Exception("You are already creating another game"); } var newGame = new GameModel(model.GamePassword); newGame.SetFirstPlayer(model.TeamId, model.UserName, userId); _games.Add(newGame); await SendGamesAwaitingForSecondPlayerToAllClientsAsync(); return(BuildGameListItem(newGame)); }