Exemplo n.º 1
0
        public async Task <CreateGameResponse> Handle(CreateGameCommand request, CancellationToken cancellationToken)
        {
            var owner = new GamePlayer
            {
                Name    = "Quiz Master",
                IsOwner = true
            };

            var joinCode = await _gameCodeService.CreateUniqueCodeAsync();

            var game = new Domain.Entities.Game
            {
                Name              = request.Name ?? joinCode,
                JoinCode          = joinCode,
                Status            = GameStatus.Lobby,
                QuestionsPerRound = 20,
                NumberOfRounds    = 5,
                QuestionTypes     = QuestionType.All,
                Difficulty        = Difficulty.Easy | Difficulty.Average | Difficulty.Hard,
                Categories        = _context.Categories.Where(c => c.IsDefault).ToList()
            };

            game.Players.Add(owner);

            _context.Games.Add(game);
            await _context.SaveChangesAsync(cancellationToken);

            return(new CreateGameResponse
            {
                GameClientId = game.ClientId,
                PlayerClientId = owner.ClientId,
                PlayerId = owner.Id
            });
        }
Exemplo n.º 2
0
 public GameViewModel(Domain.Entities.Game game, IEnumerable <Side> sides, IEnumerable <Move> moves)
 {
     Id     = game.Id;
     Fen    = game.Fen;
     Status = FromGameStatus(game.Status);
     Sides  = sides;
     Moves  = moves;
 }
Exemplo n.º 3
0
        public Domain.Entities.Game CreateGame(string username1, string username2, List<string> letters, List<string> words)
        {
            bool created_first_user_game = false;
            bool created_second_user_game = false;
            TableServiceContext service_context = _client.GetDataServiceContext();
            Domain.Entities.Game game_for_user1 = null;
            Domain.Entities.Game game_for_user2 = null;
            try
            {
                //create two games for each side of the game
                //this allows scalability better. they have the same guid to allow us to pinpoint this game via pk_rk more quickly on either side of the relationship
                Guid game_guid = Guid.NewGuid();

                game_for_user1 = new Domain.Entities.Game(username1, username2, letters, words, game_guid);
                game_for_user2 = new Domain.Entities.Game(username2, username1, letters, words, game_guid);

                //since they live on separate partitions, we cannot atomically create these two entities and must clean up after ourselves in case of errors
                service_context.AddObject(_table_name, game_for_user1);
                service_context.SaveChanges();
                created_first_user_game = true;
                service_context.AddObject(_table_name, game_for_user2);
                service_context.SaveChanges();
                created_second_user_game = true;
                return game_for_user1;

            }
            catch
            {
                try
                {
                    if (service_context != null)
                    {
                        if (created_first_user_game && game_for_user1 != null)
                        {
                            service_context.DeleteObject(game_for_user1);
                            service_context.SaveChanges();
                        }

                        if (created_second_user_game && game_for_user2 != null)
                        {
                            service_context.DeleteObject(game_for_user2);
                            service_context.SaveChanges();
                        }
                    }
                }
                catch
                {
                }
                throw;
            }
        }
Exemplo n.º 4
0
        public Task <Question> GetQuestionAsync(Domain.Entities.Game game)
        {
            var seenQuestions = _context.SeenQuestions.Where(s => s.GameId == game.Id);

            var categoryIds = game.Categories.Select(c => c.Id);

            var unseenQuestions = _context.Questions
                                  .Where(q => (q.Type & game.QuestionTypes) == q.Type)
                                  .Where(q => q.Categories.Any(c => categoryIds.Contains(c.Id) && (q.Difficulty & game.Difficulty) == q.Difficulty))
                                  .Where(q => !seenQuestions.Any(s => s.QuestionId == q.Id))
                                  .OrderBy(q => Guid.NewGuid());

            return(unseenQuestions.FirstOrDefaultAsync());
        }
        public async Task Handle_WhenGameWithTurnNumberLessThanMinimal_ShouldOnlyIncrementTurnNumber()
        {
            // arrange
            int gameId  = 5;
            var command = new CheckAndUpdateGameWinConditionsCommand(gameId);
            var handler = new CheckAndUpdateGameWinConditionsCommandHandler(Context);

            // act
            await handler.Handle(command, CancellationToken.None);

            Domain.Entities.Game entity = Context.Games.Find(command.GameId);

            // assert
            entity.ShouldNotBeNull();
            entity.TurnNumber.ShouldBe((byte)4);
        }
        public async Task Handle_WhenNoneOfThePlayersHaveWinConditionTilesButThereArePossibility_ShouldReturnActive()
        {
            // arrange
            int gameId  = 7;
            var command = new CheckAndUpdateGameWinConditionsCommand(gameId);
            var handler = new CheckAndUpdateGameWinConditionsCommandHandler(Context);

            // act
            GameResult result = await handler.Handle(command, CancellationToken.None);

            Domain.Entities.Game entity = Context.Games.Find(command.GameId);

            // assert
            entity.TurnNumber.ShouldBe((byte)6);
            result.ShouldBe(GameResult.Active);
            entity.Result.ShouldBe(GameResult.Active);
        }
        public async Task Handle_WhenNoughtPlayerHasWinConditionTiles_ShouldReturnLoss()
        {
            // arrange
            int gameId  = 8;
            var command = new CheckAndUpdateGameWinConditionsCommand(gameId);
            var handler = new CheckAndUpdateGameWinConditionsCommandHandler(Context);

            // act
            GameResult result = await handler.Handle(command, CancellationToken.None);

            Domain.Entities.Game entity = Context.Games.Find(command.GameId);

            // assert
            entity.TurnNumber.ShouldBe((byte)7);
            result.ShouldBe(GameResult.Loss);
            entity.Result.ShouldBe(GameResult.Loss);
        }
        public async Task <BaseResponse> Handle(UpdateGameCommandRequest request, CancellationToken cancellationToken)
        {
            _logger.LogInformation($"[Begin] - Updating game : { JsonSerializer.Serialize(request) }");

            try
            {
                var validationResult = request.Validate();

                if (!validationResult.IsValid)
                {
                    var validationResultErrors = ValidationResultHelper.GetValidationResultErrors(validationResult);

                    _logger.LogInformation($"[Error] - Request not valid: { validationResultErrors }");

                    return(new BaseResponse(false, "Ocorreu um problema ao atualizar o jogo!", HttpStatusCode.BadRequest, validationResultErrors));
                }

                if (await _gameService.CheckIfGameExists(request.Id))
                {
                    _logger.LogInformation($"[Error] - Request not valid: { request }");

                    return(new BaseResponse(false, "Jogo não existe na base de dados!", HttpStatusCode.NotFound, request));
                }

                if (!await _gameService.CheckIfGameNameIsUnique(request.Name, request.Id))
                {
                    _logger.LogInformation($"[Error] - Request not valid: { request }");

                    return(new BaseResponse(false, "Já existe um jogo cadastrado com o mesmo nome!", HttpStatusCode.BadRequest, request));
                }

                var game = new Domain.Entities.Game(request.Id, request.Name, request.Genre, request.Synopsis, request.Platform, request.LaunchDate, request.IsAvailable, request.IsActive);

                await _repository.Update(game);

                _logger.LogInformation($"[End] - Game successfully updated: { JsonSerializer.Serialize(game) }");

                return(new BaseResponse(true, "Jogo atualizado com sucesso!", HttpStatusCode.OK, game));
            }
            catch (Exception ex)
            {
                _logger.LogInformation($"[Error] - An error occurred while updating the game: { JsonSerializer.Serialize(ex) }");

                return(new BaseResponse(false, "Ocorreu um problema ao atualizar o jogo!", HttpStatusCode.InternalServerError, ex.InnerException.ToString()));
            }
        }
Exemplo n.º 9
0
        public Domain.Entities.Game UpdateGame(Domain.Entities.Game game)
        {
            bool updated_my_side = false;
            bool updated_other_side = false;
            Domain.Entities.Game my_old_game = new Domain.Entities.Game(game.PartitionKey, game.OtherPlayerUsername, game.Letters, game.PossibleWords, Guid.Parse(game.RowKey));
            Domain.Entities.Game other_side_old_game = null;
            TableServiceContext service_context = _client.GetDataServiceContext();
            try
            {

                service_context.UpdateObject(game);
                service_context.SaveChanges();
                updated_my_side = true;
                //also update the other side of it
                var query = service_context.CreateQuery<Domain.Entities.Game>(_table_name);
                Domain.Entities.Game other_side_of_game = (from g in query where g.PartitionKey == game.OtherPlayerUsername && g.RowKey == game.RowKey select game).SingleOrDefault();

                //save the old version in case we have to revert
                other_side_old_game = new Domain.Entities.Game(other_side_of_game.PartitionKey, other_side_of_game.OtherPlayerUsername, other_side_of_game.Letters, other_side_of_game.PossibleWords, Guid.Parse(other_side_of_game.RowKey));

                other_side_of_game.IsOtherPlayerDone = game.AmIDone;
                other_side_of_game.OtherPlayerScore = game.MyScore;
                other_side_of_game.OtherPlayerUsername = game.PartitionKey;
                other_side_of_game.OtherPlayerWordsFound = game.MyWordsFound;
                service_context.UpdateObject(other_side_of_game);
                service_context.SaveChanges();
                updated_other_side = true;

                return game;
            }
            catch
            {
                try
                {
                    if (service_context != null)
                    {
                        //revert on any error if possible
                        if (updated_my_side)
                        {
                            service_context.UpdateObject(my_old_game);
                            service_context.SaveChanges();
                        }

                        if (updated_other_side && other_side_old_game != null)
                        {
                            service_context.DeleteObject(other_side_old_game);
                            service_context.SaveChanges();
                        }
                    }
                }
                catch
                {
                }

                throw;
            }
        }