Exemplo n.º 1
0
        public async Task <IActionResult> NewGame()
        {
            // todo: match making queue/service
            var oppenentId = 2;

            User whiteUser = await _userRepo.GetUser(this.GetCurrentUserId());

            User blackUser = await _userRepo.GetUser(oppenentId);

            Game newGame = new Game(whiteUser, blackUser);

            newGame.StatusCode = GameStatus.Inprogress;
            newGame.Initialize();
            _gameRepo.Add(newGame);
            foreach (Piece piece in newGame.Pieces)
            {
                _gameRepo.Add(piece);
            }
            var result = await _gameRepo.SaveAll();

            GameDto gameDto = _mapper.Map <GameDto>(newGame);

            return(Created("/game/" + gameDto.Id + "/play", gameDto));
            //  return CreatedAtAction("GetGame", gameDto);
            // return CreatedAtRoute( );
            //  Ok(gameDto);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Creates a new game.
        /// </summary>
        /// <param name="game">Game to create.</param>
        public void Create(Game game)
        {
            _authService.CheckAccess(AuthOperations.Games.Create);

            if (game == null)
            {
                throw new ArgumentNullException("game");
            }

            if (game.Result != null)
            {
                ValidateResult(game.Result);
            }

            TournamentScheduleDto tournamentScheduleInfo = _tournamentScheduleDtoByIdQuery
                                                           .Execute(new TournamentScheduleInfoCriteria {
                TournamentId = game.TournamentId
            });

            ValidateGame(game, tournamentScheduleInfo);
            if (game.Result != null)
            {
                UpdateTournamentLastTimeUpdated(game);
            }
            else
            {
                // Set default empty result
                game.Result = new Result();
            }

            _gameRepository.Add(game);
            _gameRepository.UnitOfWork.Commit();
        }
        public string CreateMultiPlayer(int[] positions)
        {
            Game game = new Game();

            game.CreateMultiplayer(positions[0], positions[1],
                                   positions[2], positions[3],
                                   positions[4], positions[5],
                                   positions[6], positions[7]);
            _repository.Add(game);

            return(game.GameId.ToString());
        }
Exemplo n.º 4
0
        public async Task <Game> Add(Game game, CancellationToken cancellationToken)
        {
            var existingGame = await _gameRepository.Get(game.Id, cancellationToken);

            if (existingGame != null)
            {
                throw new Exception();
            }

            await _gameRepository.Add(game, cancellationToken);

            return(game);
        }
Exemplo n.º 5
0
        public override void Add(Game item, string cultureCode)
        {
            AssignIdIfEmpty(item);
            if (item.Genres == null)
            {
                item.Genres = item.NameGenres != null?_genreRepository.LoadDomainEntities(item.NameGenres) : _genreRepository.Get(genre => genre.Locals.Any(z => z.Name == "Other")).ToList();
            }

            item.PlatformTypes = item.NamePlatformTypes != null?_platformRepository.LoadDomainEntities(item.NamePlatformTypes) : null;

            if (item.Publisher != null)
            {
                item.Publisher = _publisherRepository.GetItemById(item.Publisher.Id);
            }

            if (!item.Locals.Any())
            {
                item.Locals = new List <GameLocal>()
                {
                    new GameLocal()
                    {
                        Culture = new Culture()
                        {
                            Code = cultureCode
                        },
                        Description = item.Description
                    }
                };
            }

            _gameRepository.Add(item);
            UnitOfWork.Save();
            Logger.Write(Operation.Insert, item);
        }
Exemplo n.º 6
0
        public IActionResult Create(int score, string user, int isFinished, int numberOfRolls, int aces, int twos, int threes, int fours, int fives, int sixes, int threeOfAKind, int fourOfAKind, int fullHouse, int smallStraight, int largeStraight, int yahtzee, int chance, long id)
        {
            Game game = new Game()
            {
                Score         = score,
                User          = user,
                IsFinished    = isFinished != 0,
                NumberOfRolls = numberOfRolls,
                Aces          = aces,
                Twos          = twos,
                Threes        = threes,
                Fours         = fours,
                Fives         = fives,
                Sixes         = sixes,
                ThreeOfAKind  = threeOfAKind,
                FourOfAKind   = fourOfAKind,
                FullHouse     = fullHouse,
                SmallStraight = smallStraight,
                LargeStraight = largeStraight,
                Yahtzee       = yahtzee,
                Chance        = chance,
            };

            if (id != 0)
            {
                game.Id = id;
            }
            if (game == null)
            {
                return(BadRequest());
            }
            _gameRepository.Add(game);

            return(CreatedAtRoute("GetGame", new { id = game.Id }, game));
        }
Exemplo n.º 7
0
        public void LerArquivo()
        {
            var todasAsLinhas = File.ReadAllLines(@"C:\Users\Bruno-PC\Desktop\games.log.txt");

            foreach (string linha in todasAsLinhas)
            {
                if (linha.Contains(Kill))
                {
                    var palavras = linha.Split();

                    var playerQueMatou = _playerService.ObterPlayerPeloNome(palavras[6], players);
                    var playerMorto    = _playerService.ObterPlayerPeloNome(palavras[8], players);

                    game.TotalKills++;

                    if (EPlayerWorldQueMatou(playerQueMatou.Name))
                    {
                        playerMorto.Kills--;
                    }
                    else
                    {
                        playerQueMatou.Kills++;
                    }
                }
            }
            _gameRepository.Add(game);
        }
Exemplo n.º 8
0
        public void GenerateNewGame(Guid gameId)
        {
            var  domainEventChannel = Maybe <IDomainEventChannel> .Nothing;
            Game game = (Game)gameBuilder.Create(domainEventChannel);

            gameRepository.Add(gameId, game);
        }
Exemplo n.º 9
0
        public async Task GetFromFIBA(string url)
        {
            string result = "";

            client = new HttpClient();
            string gameId = GetGameIdFromUrl(url);

            var dataUrl = new Uri("http://www.fibalivestats.com/data/" + gameId + "/data.json");

            using (HttpClient client = new HttpClient())
                using (HttpResponseMessage response = await client.GetAsync(dataUrl).ConfigureAwait(false))
                    using (HttpContent content = response.Content)
                    {
                        result = await content.ReadAsStringAsync();
                    }

            JObject            resultJson            = JObject.Parse(result);
            IList <JToken>     firstTeamData         = resultJson["tm"]["1"].Children().ToList();
            IList <JToken>     firstTeam             = resultJson["tm"]["1"]["pl"].Children().ToList();
            IList <JToken>     secondTeamData        = resultJson["tm"]["2"].Children().ToList();
            IList <JToken>     secondTeam            = resultJson["tm"]["2"]["pl"].Children().ToList();
            List <Performance> firstTeamPerformance  = GetPerformanceFromJson(firstTeam);
            List <Performance> secondTeamPerformance = GetPerformanceFromJson(secondTeam);
            Game game = GetGameData(firstTeamData, secondTeamData);

            game.Performances = AddPerformances(firstTeamPerformance, secondTeamPerformance);
            gameRepository.Add(game);
        }
Exemplo n.º 10
0
        public IGameInfo CreateGameForUser(GameSettings settings, User user)
        {
            var game = _gameFactory.CreateNewSinglePlayerGame(settings, user);

            _gameRepository.Add(game);
            return(_gameInfoFactory.CreateFromGame(game, user.Id));
        }
Exemplo n.º 11
0
        public Models.MVC.Game.Game Create(int userId, Models.MVC.Game.Player player, Level gameLevel)
        {
            #region Create or Update Player
            var existPlayer = _playerService.FindById(player.Id);
            if (existPlayer == null)
            {
                existPlayer = _playerService.Create(player, userId);
            }
            else
            {
                _playerService.Update(player);
            }
            #endregion


            var computerPlayer = _playerService.GetComputerPlayer(player.GameSideEnum == GameSideEnum.Crosses ? GameSideEnum.Zeros : GameSideEnum.Crosses);


            _gameRepository.Add(new Game
            {
                PlayerId         = existPlayer.Id,
                ComputerPlayerId = computerPlayer.Id,
                LevelId          = (int)gameLevel.LevelEnum
            });
            _gameRepository.SaveChanges();

            var currentGame = CurrentGame(existPlayer);
            if (player.GameSideEnum == GameSideEnum.Zeros)
            {
                MakeComputerMove(currentGame.Id);
            }
            return(currentGame);
        }
Exemplo n.º 12
0
        public void addGame(String userId, String gameName, float gamePrice, String gameDescription, String Image, int gameStock, string category)
        {
            Guid userIdGuid = Guid.Empty;

            if (!Guid.TryParse(userId, out userIdGuid))
            {
                throw new Exception("Invalid Guid Format");
            }
            var admin = adminRepository.GetAdminByAdminId(userIdGuid);

            if (admin == null)
            {
                throw new EntityNotFoundException(userIdGuid);
            }

            gameRepository.Add(new Game()
            {
                Id          = Guid.NewGuid(),
                Admin       = admin,
                Name        = gameName,
                Price       = gamePrice,
                Description = gameDescription,
                ImageFile   = Image,
                Stock       = gameStock,
                Category    = category
            });
        }
Exemplo n.º 13
0
        public Task <bool> Handle(CreateGameCommand request, CancellationToken cancellationToken)
        {
            try
            {
                if (!request.IsValid())
                {
                    var error = request.ValidationResult.Errors[0];

                    throw new GameScopeException(error.ErrorCode, error.ErrorMessage);
                }

                var game = new Game
                {
                    Name        = request.Name,
                    UserId      = request.UserId,
                    Description = request.Description,
                    ReleaseDate = request.ReleaseDate,
                    CreatedDate = request.CreatedAt,
                    UpdatedDate = request.UpdatedAt
                };

                _gameRepository.Add(game);

                return(Task.FromResult(_gameRepository.SaveChanges() > 0));
            }catch (Exception ex)
            {
                return(Task.FromResult(false));
            }
        }
Exemplo n.º 14
0
        public async Task <IActionResult> UpdateUser(string name, PointsDto body)
        {
            var pointsFromRequest = body.Points;
            var player            = await _repo.GetPlayer(name);

            if (player == null)
            {
                player = new Player {
                    Username = name, Points = pointsFromRequest
                };
                _repo.Add(player);
            }
            else if (player.Points == pointsFromRequest)
            {
                return(NoContent());
            }

            player.Points = body.Points;
            if (await _repo.SaveAll())
            {
                return(NoContent());
            }

            throw new Exception($"Updating player {name} failed on save");
        }
Exemplo n.º 15
0
        public ActionResult <Game> PostGame(Game game)
        {
            _gameRepository.Add(game);
            _gameRepository.SaveChanges();

            return(CreatedAtAction(nameof(GetGame), new { id = game.Id }, game));
        }
Exemplo n.º 16
0
        private async Task <int> CreateGame(string name, int botNumber)
        {
            var game = new Game();

            game.Id = await _gameRepository.Add(game);

            return(game.Id);
        }
Exemplo n.º 17
0
        public async Task <IActionResult> NewGame()
        {
            var player = User.Identity.Name;
            var game   = new Game(player);
            await gameRepository.Add(game).ConfigureAwait(false);

            return(Created(new Uri(game.Id.ToString(), UriKind.Relative), null));
        }
Exemplo n.º 18
0
        public static int CreateGameTable(IGameRepository games, string tableName)
        {
            int       newIdentifier  = games.Get().Count;
            GameTable generatedTable = GenerateNewGameTable(newIdentifier, tableName);

            games.Add(generatedTable);
            return(generatedTable.Identifier);
        }
Exemplo n.º 19
0
 public void Logic()
 {
     _game.Logic();
     if (_game.GameOver)
     {
         _gameRepository.Add(_game);
         _game = _factory.Create(0, _gameHeight, _snakeLength);
     }
 }
 public void Handle(CreateGameCommand Message)
 {
     if (Message != null)
     {
         var game = _mapper.Map <Game>(Message);
         game.CreationDate = DateTime.Now;
         _gameRepository.Add(game);
     }
 }
Exemplo n.º 21
0
 public GameResponse Create(GameRequest request)
 {
     if (request == null)
     {
         throw new ArgumentNullException("entity");
     }
     _repository.Add(Mapper.Map <Game>(request));
     _unitOfWork.Commit();
     return(Mapper.Map <GameResponse>(request));
 }
Exemplo n.º 22
0
        public async Task <bool> Handle(CreateGameCommand request, CancellationToken cancellationToken)
        {
            var entity = Game.Create(request.Id, request.Name, request.LaunchYear, request.Platform);

            _repository.Add(entity);

            await _repository.UnitOfWork.SaveAsync(cancellationToken);

            return(true);
        }
Exemplo n.º 23
0
        /// <summary>
        /// 添加游戏
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public GameAddOutput Add(GameAddInput input)
        {
            _gameRepository.Add(input.Entity);

            return(new GameAddOutput()
            {
                IsSuccess = true,
                ErrMessage = ""
            });
        }
Exemplo n.º 24
0
        private void CreateGame(int homeTeam, int awayTeam, int pouleId)
        {
            Game game = new Game
            {
                PouleId    = pouleId,
                HomeTeamId = homeTeam,
                AwayTeamId = awayTeam
            };

            _gameRepository.Add(game);
        }
        public async Task <GameDto> Handle(CreateBoardCommand request, CancellationToken cancellationToken)
        {
            var game = new Game(request.BoardX, request.BoardY);
            await _gameRepository.Add(game);

            await _gameRepository.UnitOfWork.SaveChangesAsync(cancellationToken);

            var gameDto = _mapper.Map <GameDto>(game);

            return(gameDto);
        }
Exemplo n.º 26
0
        public async Task <HttpResponseMessage> NewGame()
        {
            var player = Thread.CurrentPrincipal.Identity.Name;
            var game   = new Game(player);
            await gameRepository.Add(game).ConfigureAwait(false);

            var response = new HttpResponseMessage(HttpStatusCode.Created);

            response.Headers.Location = new Uri(game.Id.ToString(), UriKind.Relative);
            return(response);
        }
Exemplo n.º 27
0
        public Game CreateGame(DateTime date)
        {
            var game = new Game()
            {
                Date = date
            };

            _gameRepository.Add(game);

            return(game);
        }
Exemplo n.º 28
0
        private async Task <Game> CreateGame(List <Player> players)
        {
            var game = new Game
            {
                Date       = DateTime.Now,
                IsFinished = false
            };
            await _gameRepository.Add(game);

            return(game);
        }
Exemplo n.º 29
0
        public async Task <ValidationResult> Handle(RegisterNewGameCommand request, CancellationToken cancellationToken)
        {
            if (!request.IsValid())
            {
                return(request.ValidationResult);
            }

            var game = new Game(Guid.NewGuid(), request.Name);

            _gameRepository.Add(game);

            return(await Commit(_gameRepository.UnitOfWork));
        }
Exemplo n.º 30
0
        public async Task <IActionResult> AddMove(MoveForAddMoveDto dto)
        {
            Move newMove = _mapper.Map <Move>(dto);

            _repo.Add(newMove);
            Piece movedPiece = await _repo.GetPiece(dto.PieceId);

            var moveAttempt = movedPiece.IsLegalMove(newMove, dto.isWhite);

            if (moveAttempt.Item1)
            {
                movedPiece.X = newMove.EndX;
                movedPiece.Y = newMove.EndY;
                int code = await _repo.SaveAll();

                return(Ok(code));
            }
            else
            {
                return(BadRequest(moveAttempt.Item2));
            }
        }