예제 #1
0
        public async Task <IActionResult> UpdateGame(NewGameModel model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("EditGame", "Game"));
            }

            if (model.ImageUpload == null)
            {
                model.GameLogo = _game.GetById(model.Id).GameLogo;
            }

            var game = BuildGame(model);

            game.Id = model.Id;

            await _game.EditGame(game);

            if (model.ImageUpload != null)
            {
                await UploadGameImageAsync(model);
            }

            return(RedirectToAction("Index", "Game"));
        }
예제 #2
0
        public async Task <ActionResult> CreateNewGame(NewGameModel model)
        {
            var user = await UserService.GetUser(new UserDTO { UserName = HttpContextManager.Current.User.Identity.Name });

            if (user == null)
            {
                throw new HttpException(503, "Unexpected error.");
            }

            var newGameDTO = new GameDTO
            {
                Opponents = new List <UserDTO> {
                    user
                },
                BlackPlayerId = model.FirstColor == "Black" ? user.Id : 0,
                WhitePlayerId = model.FirstColor == "White" ? user.Id : 0,
            };

            var createdGameDTO = await GameService.CreateNewGame(newGameDTO);

            if (createdGameDTO == null)
            {
                throw new HttpException(503, "Unexpected error.");
            }

            return(RedirectToAction("EnterGame", new { gameId = createdGameDTO.Id }));
        }
예제 #3
0
        public NewGameModel PostGame(NewGameModel game)
        {
            if (game.AwayTeam.TeamId == game.HomeTeam.TeamId)
            {
                throw new ArgumentException("Home team and Away team can not be the same team");
            }

            var newGame = new Game();

            newGame.HomeTeamId  = game.HomeTeam.TeamId;
            newGame.AwayTeamId  = game.AwayTeam.TeamId;
            newGame.StadiumId   = game.Stadium.StadiumId;
            newGame.Date        = game.Date;
            newGame.HomeRatio   = game.HomeRatio;
            newGame.TieRatio    = game.TieRatio;
            newGame.AwayRatio   = game.AwayRatio;
            newGame.RatioWeight = game.RatioWeight;

            var res = gamesRepository.InsertGame(newGame);

            Trace.TraceInformation("Posting new Game: {0}", game);
            gamesRepository.Save();
            game.GameId          = res.GameId;
            game.IsOpen          = true;
            game.IsPendingUpdate = false;
            AddLog(ActionType.CREATE, String.Format("Posting new game: {0}", newGame));
            AddMonkeyBet(res);

            return(game);
        }
예제 #4
0
        public GameModel NewGame(NewGameModel model)
        {
            var game = new GameModel(_gameEngine.GenerateSeed(model.Width, model.Height));

            DataStore.Add(game.GameId, game);
            return(game);
        }
예제 #5
0
        /// <summary>
        /// 対局計算のコマンド実行
        /// </summary>
        public void CalcGame()
        {
            // クラスを作って
            var newGameModel = new NewGameModel()
            {
                // オブジェクトを渡して
                EastBaseScore   = EastBaseScore,
                EastPriseScore  = EastPriseScore,
                SouthBaseScore  = SouthBaseScore,
                SouthPriseScore = SouthPriseScore,
                WestBaseScore   = WestBaseScore,
                WestPriseScore  = WestPriseScore,
                NorthBaseScore  = NorthBaseScore,
                NorthPriseScore = NorthPriseScore,
                Setting         = SelectedRule
            };

            // 動かして戻す
            var ret = newGameModel.ExecuteCalc();

            EastCalcedScore  = (int)ret[0];
            SouthCalcedScore = (int)ret[1];
            WestCalcedScore  = (int)ret[2];
            NorthCalcedScore = (int)ret[3];

            // 計算済みオブジェクトに格納
            SavedObject = Tuple.Create(
                Tuple.Create(SelectedPersonEast, EastBaseScore, EastPriseScore),
                Tuple.Create(SelectedPersonSouth, SouthBaseScore, SouthPriseScore),
                Tuple.Create(SelectedPersonWest, WestBaseScore, WestPriseScore),
                Tuple.Create(SelectedPersonNorth, NorthBaseScore, NorthPriseScore),
                SelectedRule.ID);
        }
예제 #6
0
        private NewGameModel PopulateNewGameModel(VariantService service)
        {
            var model = new NewGameModel();

            model.Variants        = service.ListPlayableVersions(User.Identity.Name);
            model.Difficulties    = service.ListAiDifficulties();
            model.AllowOnlinePlay = User.Identity.IsAuthenticated;
            return(model);
        }
예제 #7
0
        public IActionResult AddGame()
        {
            var model = new NewGameModel
            {
                GameName        = "",
                GameDescription = "",
                GameLogo        = ""
            };

            return(View(model));
        }
예제 #8
0
        //
        // GET: /Games/Create

        public ActionResult Create()
        {
            var m = new NewGameModel();

            foreach (var i in Warehouse.db.Intellect)
            {
                m.Intellects.Add(new KeyValuePair <Guid, string>(i.Intellect_ID,
                                                                 String.Format("{0}: {1}", i.Account.Account_Name, i.Intellect_Name)));
            }
            return(View(m));
        }
예제 #9
0
        public async Task <ActionResult <GameModel> > New([FromBody] NewGameModel model)
        {
            if (model.BombChance < 0 || model.BombChance > 100 ||
                model.Width < 1 || model.Height < 1 ||
                model.Width > 20 || model.Height > 20)
            {
                return(BadRequest("Некорректные входные данные"));
            }

            var gameModel = await _gameService.Create(model.Width, model.Height, model.BombChance);

            return(Ok(gameModel));
        }
        public async Task <ActionResult <int> > AddGame(NewGameModel game)
        {
            var userID   = User.FindFirst(c => c.Type == "UserID").Value;
            var cmd      = new AddGameCommand(game, userID);
            var response = await _mediator.Send(cmd);

            if (response != null)
            {
                return(Created(response.Link, response.GameID));
            }

            return(BadRequest("Something went wrong while trying to add new game to database"));
        }
        public async Task <IActionResult> CreateGame([FromForm] NewGameModel gameModel)
        {
            if (!IsValidImage(gameModel.Image))
            {
                return(BadRequest(
                           $"invalid content type for image, got {gameModel.Image.ContentType} but expected image/png"));
            }

            var item = await _gamesService.CreateGame(gameModel);

            return(item != null
                                ? (IActionResult)CreatedAtAction(nameof(GetGame), new { id = item.Id }, item)
                                : BadRequest("Failed to create game"));
        }
예제 #12
0
        public async Task <GameModel> GetNewGameAsync(NewGameModel model)
        {
            var content  = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json");
            var response = await _client.PostAsync(_uri + "/api/game", content);

            if (response.IsSuccessStatusCode)
            {
                return(JsonConvert.DeserializeObject <GameModel>(await response.Content.ReadAsStringAsync()));
            }
            else
            {
                throw new Exception(response.StatusCode.ToString());
            }
        }
예제 #13
0
 /**
  * Creates a game from the model to add to the database
  */
 private Game BuildGame(NewGameModel model)
 {
     return(new Game
     {
         GameName = model.GameName.ToUpper(),
         GameLogo = model.GameLogo,
         // Points are put in the User Game Service, these values are simply
         // Placeholders
         WinPoints = 0,
         DrawPoints = 0,
         LossPoints = 0,
         GameDescription = model.GameDescription
     });
 }
예제 #14
0
        private async Task <ChessGameInfo> PostNewGameAsync(NewGameModel model)
        {
            HttpResponseMessage response = await client.PostAsync("api/game/new",
                                                                  new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"));

            var result = await response.Content.ReadAsStringAsync();

            Console.WriteLine(result);
            if (!response.IsSuccessStatusCode)
            {
                throw new Exception($"Error: {response.StatusCode}\n{result}");
            }
            return(JsonConvert.DeserializeObject <ChessGameInfo>(result));
        }
        public async Task <IActionResult> PostNewGame([FromBody] NewGameModel model)
        {
            ServiceEventSource.Current.ServiceMessage(context, $"PostNewGame({model.PlayerColor}): {User.Identity.Name}");
            try
            {
                var gameId      = $"{User.Identity.Name}-{Guid.NewGuid()}";
                var chessClient = proxyFactory.CreateServiceProxy <IChessFabrickStatefulService>(chessStatefulUri, ChessFabrickUtils.GuidPartitionKey(gameId));
                var game        = await chessClient.NewGameAsync(gameId, User.Identity.Name, model.PlayerColor);

                return(Ok(game));
            } catch (Exception ex)
            {
                return(StatusCode(500, ex.Message));
            }
        }
예제 #16
0
        public IActionResult EditGame(int gameId)
        {
            var game = _game.GetById(gameId);

            var model = new NewGameModel
            {
                Id = gameId,
                GameDescription = game.GameDescription,
                GameLogo        = game.GameLogo,
                GameName        = game.GameName
            };


            return(View(model));
        }
예제 #17
0
        public async Task <IActionResult> CreateNewGame(NewGameModel model)
        {
            if (ModelState.IsValid)
            {
                Game game = new Game {
                    Name = model.Name, Tags = model.Tags
                };
                db.Games.Add(game);
                games.Add(game);
                await db.SaveChangesAsync();

                return(AddPlayer(game, true));
            }
            return(RedirectToAction("Index", "Home", model));
        }
예제 #18
0
        public ActionResult Index(NewGameModel model)
        {
            if (this.ModelState.IsValid)
            {
                var response = this.GameService.NewGame(((PonyName)model.Name).GetDisplayName(), model.Width, model.Height, model.SelectedDifficulty);
                if (response.MazeId != null)
                {
                    return this.RedirectToAction("Index", "Game", new { id = response.MazeId });
                }
                else
                {
                    this.ModelState.AddModelError(string.Empty, response.State);
                }
            }

            return this.View(model);
        }
예제 #19
0
        public GameModel GetNewGame(NewGameModel model)
        {
            var request = new RestRequest("api/games/", Method.POST);

            request.AddJsonBody(model);

            var response = _client.Execute(request);

            if (response.IsSuccessful)
            {
                return(JsonConvert.DeserializeObject <GameModel>(response.Content));
            }
            else
            {
                throw new Exception(response.ErrorMessage, response.ErrorException);
            }
        }
예제 #20
0
        private async Task UploadGameImageAsync(NewGameModel model)
        {
            var game      = _game.GetById(model.Id);
            var container = _uploadService.GetGameImagesBlobContainer(_azureBlobStorageConnection);

            var contentDisposition = ContentDispositionHeaderValue.Parse(model.ImageUpload.ContentDisposition);
            var fileName           = contentDisposition.FileName.Trim('"');

            // Replace it with gameId to save space in Azure blob
            // As the file with the same name will overrite the old file.
            var fileExtension  = fileName.Substring(fileName.LastIndexOf('.'));
            var gameIdFileName = String.Concat(model.Id, fileExtension);

            var blockBlob = container.GetBlockBlobReference(gameIdFileName);

            await blockBlob.UploadFromStreamAsync(model.ImageUpload.OpenReadStream());

            await _game.SetGameImageAsync(game, blockBlob.Uri);
        }
예제 #21
0
        public async Task <IActionResult> AddNewGame(NewGameModel model)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction("AddGame", "Game"));
            }

            var game = BuildGame(model);

            await _game.AddGame(game);

            model.Id = game.Id;

            if (model.ImageUpload != null)
            {
                await UploadGameImageAsync(model);
            }

            return(RedirectToAction("Index", "Game"));
        }
        public IList <GameTurnModel> ProcessGame([FromBody] NewGameModel newGameModel)
        {
            var game = newGameModel.ConvertToGame();

            if (game.Players.First().Actions.All(action => action.FirstActionSegment.SegmentType == PlayerActionType.BattleBots))
            {
                throw new InvalidOperationException("Successfully triggered test Exception. You can't do that many battle bots!");
            }

            game.StartGame();
            var turnModels = new List <GameTurnModel>();

            game.PhaseStarting += (sender, eventArgs) =>
            {
                var lastPhase = turnModels.Last().Phases.LastOrDefault();
                lastPhase?.SubPhases.Add(new GameSnapshotModel(game, "End of Phase"));
                turnModels.Last().Phases.Add(new GamePhaseModel {
                    Description = eventArgs.PhaseHeader
                });
                turnModels.Last().Phases.Last().SubPhases.Add(new GameSnapshotModel(game, "Start of Phase"));
            };
            game.EventMaster.EventTriggered += (sender, eventArgs) =>
            {
                turnModels.Last().Phases.Last().SubPhases.Add(new GameSnapshotModel(game, eventArgs.PhaseHeader));
            };
            game.LostGame += (sender, args) =>
            {
                turnModels.Last().Phases.Last().SubPhases.Add(new GameSnapshotModel(game, "Lost!"));
            };

            while (game.GameStatus == GameStatus.InProgress)
            {
                turnModels.Add(new GameTurnModel {
                    Turn = game.CurrentTurn
                });
                game.PerformTurn();
                turnModels.Last().Phases.Last().SubPhases.Add(new GameSnapshotModel(game, "End of Phase"));
            }

            return(turnModels);
        }
예제 #23
0
        public async Task <Game> CreateGame(NewGameModel model)
        {
            try
            {
                var dbModel = _mapper.Map <Game>(model);
                await _context.Games.AddAsync(dbModel);

                await _context.SaveChangesAsync();

                if (model.Image != null)
                {
                    await _gameImageService.SetImageAsync(dbModel.Id, model.Image.OpenReadStream());
                }

                return(dbModel);
            }
            catch
            {
                return(null);
            }
        }
예제 #24
0
        public JsonResult NewGame(int gameDefId, NewGameModel newGameModel)
        {
            if (Platform.IsUserLogged())
            {
                newGameModel.Nick = User.Identity.Name;
            }

            try
            {
                newGameModel.Validate();
                Game = Platform.NewGameInstance(Platform.GetGameDefinitionById(gameDefId), newGameModel.Name, newGameModel.Password);
                int playerId = Game.AddPlayer(new Player(newGameModel.Nick, Permission.TYPE.Moderator));
                SaveGame(Game.Id);

                Platform.GameAuthentication.AddPermission(Game.Id, playerId, newGameModel.Nick, Crypto.HashPassword(newGameModel.Password), Permission.TYPE.Moderator);

                return(Json(new Result(new { gameId = Game.Id }).AsSuccess()));
            }
            catch (Error.ValidationException validation)
            {
                return(Json(validation.Result));
            }
        }
예제 #25
0
 public AddGameCommand(NewGameModel model, string userID)
 {
     NewGameModel = model;
     UserID       = userID;
 }
예제 #26
0
 public async Task <GameModel> GetNewGameAsync(NewGameModel model)
 {
     return(await Task.FromResult(GetNewGame(model)));
 }
예제 #27
0
        public async Task <IActionResult> DeleteGame(NewGameModel model)
        {
            await _game.DeleteGame(model.Id);

            return(RedirectToAction("Index", "Home"));
        }
예제 #28
0
 public GameModel GetNewGame(NewGameModel model)
 {
     return(GetNewGameAsync(model).Result);
 }
예제 #29
0
 public GameResultModel NewGame([FromBody] NewGameModel model)
 {
     return(_mapper.Map <Game, GameResultModel>(_gameAppService.Create(model.Nickname, model.NumberOfPlayers)));
 }
예제 #30
0
        public IActionResult NewGame([FromBody] NewGameModel model)
        {
            var game = _gameService.NewGame(model);

            return(Ok(game));
        }