Ejemplo n.º 1
0
        public async Task <GetGameDefinitionResponse> GetGameDefinitionAsync(GetGameDefinitionRequest request)
        {
            var response = ServiceMessageFactory <GetGameDefinitionResponse> .CreateFrom(request);

            response.GameDefinition = cache.FirstOrDefault(i => i.Id == request.GameDefinitionId);
            return(await Task.FromResult(response));
        }
Ejemplo n.º 2
0
        public async Task <ValidateUserInputResponse> ValidateAsync(ValidateUserInputRequest request)
        {
            var response = ServiceMessageFactory <ValidateUserInputResponse> .CreateFrom(request);

            var cleaned = request.Input.Trim().ToUpperInvariant();

            if (string.IsNullOrWhiteSpace(cleaned))
            {
                response.ValidationResult = new ValidationResult(NoInputFoundError);
                return(response);
            }

            var tilesRequest = ServiceMessageFactory <FindTilesRequest> .CreateFrom(request);

            tilesRequest.Filter = tile => tile.GameSessionId == request.GameSessionId;
            var tileResponse = await tileAccess.FindTilesAsync(tilesRequest);

            var targetTile = tileResponse.Tiles.FirstOrDefault(i => i.Address == cleaned);

            if (targetTile == null)
            {
                response.ValidationResult = new ValidationResult(AddressNotFoundError);
                return(response);
            }

            response.ValidationResult = targetTile.IsEmpty
                                ? ValidationResult.Success
                                : new ValidationResult(AddressAlreadyPlayedError);

            return(response);
        }
Ejemplo n.º 3
0
        public async Task <FindTilesResponse> FindTilesAsync(FindTilesRequest request)
        {
            var response = ServiceMessageFactory <FindTilesResponse> .CreateFrom(request);

            response.Tiles = cache.Where(request.Filter).ToArray();
            return(await Task.FromResult(response));
        }
Ejemplo n.º 4
0
        public async Task <ValidateGamePlayAddressResponse> ValidateAsync(ValidateGamePlayAddressRequest request)
        {
            var response = ServiceMessageFactory <ValidateGamePlayAddressResponse> .CreateFrom(request);

            var gameSessionRequest = ServiceMessageFactory <GetGameSessionRequest> .CreateFrom(request);

            gameSessionRequest.GameSessionId = request.GameSessionId;

            var gameSessionResponse = await gameSessionAccess.GetGameSessionAsync(gameSessionRequest);

            if (gameSessionResponse.HasErrors)
            {
                response.Errors          += gameSessionResponse.Errors;
                response.ValidationResult = new ValidationResult(GameSessionNotFoundError);
            }
            else if (gameSessionResponse.GameSession == null)
            {
                response.ValidationResult = new ValidationResult(GameSessionNotFoundError);
            }
            else
            {
                response.ValidationResult = ValidationResult.Success;
            }

            return(response);
        }
Ejemplo n.º 5
0
        public async Task <GetPlayerResponse> GetPlayerAsync(GetPlayerRequest request)
        {
            var response = ServiceMessageFactory <GetPlayerResponse> .CreateFrom(request);

            response.Player = cache.FirstOrDefault(i => i.Id == request.PlayerId);
            if (response.Player == null)
            {
                response.Errors = "Unable to find player.";
            }
            return(await Task.FromResult(response));
        }
Ejemplo n.º 6
0
        public async Task <GetGamesResponse> GetGamesAsync(GetGamesRequest request)
        {
            var response = ServiceMessageFactory <Interface.GetGamesResponse> .CreateFrom(request);

            var gameDefinitionRequest = ServiceMessageFactory <Access.GameDefinition.Interface.GetGameDefinitionsRequest> .CreateFrom(request);

            var gameDefinitionResponse = await gameDefinitionAccess.GetGameDefinitionsAsync(gameDefinitionRequest);

            response.GameDefinitions = gameDefinitionResponse.GameDefinitions.Convert();

            return(response);
        }
Ejemplo n.º 7
0
        public async Task <IsTileOpenResponse> IsTileOpenAsync(IsTileOpenRequest request)
        {
            var response = ServiceMessageFactory <IsTileOpenResponse> .CreateFrom(request);

            var tileRequest = ServiceMessageFactory <FindTilesRequest> .CreateFrom(request);

            tileRequest.Filter = tile => tile.GameSessionId == request.GameSessionId;
            var tileResponse = await tileAccess.FindTilesAsync(tileRequest);

            response.Value = tileResponse.Tiles.First(i => i.Address == request.Address).IsEmpty;
            return(response);
        }
Ejemplo n.º 8
0
        public async Task <GetGameDefinitionsResponse> GetGameDefinitionsAsync(GetGameDefinitionsRequest request)
        {
            var response = ServiceMessageFactory <GetGameDefinitionsResponse> .CreateFrom(request);

            response.GameDefinitions = cache.ToArray();
            if (!response.GameDefinitions.Any())
            {
                response.Errors = "Unable to find any game definitions.";
                logger.LogError($"Initialization Error!  Unable to find any game definitions.");
            }
            return(await Task.FromResult(response));
        }
Ejemplo n.º 9
0
        public async Task <FindWinnerResponse> FindWinnerAsync(Interface.FindWinnerRequest request)
        {
            var response = ServiceMessageFactory <FindWinnerResponse> .CreateFrom(request);

            var engineRequest = ServiceMessageFactory <FindWinnerRequest> .CreateFrom(request);

            engineRequest.GameSessionId = request.GameSessionId;
            var engineResponse = await gamePlayEngine.FindWinnerAsync(engineRequest);

            response.Player = engineResponse.Player.Convert();
            return(response);
        }
Ejemplo n.º 10
0
        public async Task <PlayTurnResponse> PlayTurnAsync(PlayTurnRequest request)
        {
            var response = ServiceMessageFactory <PlayTurnResponse> .CreateFrom(request);

            var playerRequest = ServiceMessageFactory <GetPlayerRequest> .CreateFrom(request);

            playerRequest.PlayerId = request.PlayerId;
            var playerResponse = await playerAccess.GetPlayerAsync(playerRequest);

            var player = playerResponse.Player.Convert();

            var gameSessionRequest = ServiceMessageFactory <GetGameSessionRequest> .CreateFrom(request);

            gameSessionRequest.GameSessionId = request.GameSessionId;
            var gameSessionResponse = await gameSessionAccess.GetGameSessionAsync(gameSessionRequest);

            var gameSession = gameSessionResponse.GameSession.Convert();

            var tilesRequest = ServiceMessageFactory <FindTilesRequest> .CreateFrom(request);

            tilesRequest.Filter = tile => tile.GameSessionId == request.GameSessionId;
            var tilesResponse = await tileAccess.FindTilesAsync(tilesRequest);

            var tiles = tilesResponse.Tiles;

            Access.Tile.Interface.Tile tile;

            if (player.IsMachine)
            {
                tile          = autoPlayer.PlayTurn(tiles);
                tile.PlayerId = player.Id;
            }
            else
            {
                var address = request.Address.ToUpperInvariant();
                tile          = tiles.First(i => i.Address == address);
                tile.PlayerId = player.Id;
            }

            var updateTileRequest = ServiceMessageFactory <UpdateTileRequest> .CreateFrom(request);

            updateTileRequest.Tile = tile;
            var updateTileResponse = await tileAccess.UpdateTileAsync(updateTileRequest);

            if (updateTileResponse.HasErrors)
            {
                response.Errors += "Tile update error.";
            }
            IncrementPlayer(gameSession);

            return(response);
        }
Ejemplo n.º 11
0
        public async Task <Interface.IsGamePlayableResponse> IsGamePlayableAsync(IsGamePlayableRequest request)
        {
            var response = ServiceMessageFactory <Interface.IsGamePlayableResponse> .CreateFrom(request);

            var engineRequest = ServiceMessageFactory <Engine.GamePlay.Interface.IsGamePlayableRequest> .CreateFrom(request);

            engineRequest.GameSessionId = request.GameSessionId;
            var engineResponse = await gamePlayEngine.IsGamePlayableAsync(engineRequest);

            response.IsPlayable = engineResponse.Value;

            return(response);
        }
Ejemplo n.º 12
0
        public async Task <ConfirmUsableAccessResponse> ConfirmUsableAddressAsync(ConfirmUsableAddressRequest request)
        {
            var response = ServiceMessageFactory <ConfirmUsableAccessResponse> .CreateFrom(request);

            var validationRequest = ServiceMessageFactory <ValidateUserInputRequest> .CreateFrom(request);

            validationRequest.GameSessionId = request.GameSessionId;
            validationRequest.Input         = request.Address;
            var validationResponse = await validationEngine.ValidateAsync(validationRequest);

            response.ValidationResult = validationResponse.ValidationResult;
            return(response);
        }
Ejemplo n.º 13
0
        public async Task <GetBoardResponse> GetBoardAsync(GetBoardRequest request)
        {
            var response = ServiceMessageFactory <GetBoardResponse> .CreateFrom(request);

            var engineRequest = ServiceMessageFactory <GetGameBoardRequest> .CreateFrom(request);

            engineRequest.GameSessionId = request.GameSessionId;

            var engineResponse = await gameBoardEngine.GetBoardAsync(engineRequest);

            response.GameBoard = engineResponse.GameBoard;

            return(response);
        }
Ejemplo n.º 14
0
        public async Task <StartGameResponse> StartGameAsync(StartGameRequest request)
        {
            var response = ServiceMessageFactory <StartGameResponse> .CreateFrom(request);

            var initializeGameRequest = ServiceMessageFactory <InitializeGameRequest> .CreateFrom(request);

            initializeGameRequest.GameDefinitionId = request.GameDefinitionId;
            initializeGameRequest.NumberOfPlayers  = request.PlayerCount;

            var initializeGameResponse = await gamePlayEngine.InitializeGameAsync(initializeGameRequest);

            response.GameSessionId = initializeGameResponse.GameSession.Id;
            return(response);
        }
Ejemplo n.º 15
0
        public async Task <ApplyTurnResponse> AutoPlayTurn(ApplyTurnRequest request)
        {
            var response = ServiceMessageFactory <ApplyTurnResponse> .CreateFrom(request);

            var autoPlayRequest = ServiceMessageFactory <PlayTurnRequest> .CreateFrom(request);

            autoPlayRequest.IsAutoPlay    = true;
            autoPlayRequest.Address       = request.Address;
            autoPlayRequest.GameSessionId = request.GameSessionId;
            autoPlayRequest.PlayerId      = request.PlayerId;
            var autoPlayResponse = await gamePlayEngine.PlayTurnAsync(autoPlayRequest);

            // ToDo: Add logging.
            return(response);
        }
Ejemplo n.º 16
0
        public async Task <CreateGameSessionResponse> CreateGameSessionAsync(CreateGameSessionRequest request)
        {
            var response = ServiceMessageFactory <CreateGameSessionResponse> .CreateFrom(request);

            if (cache.FirstOrDefault(i => i.Id == request.GameSession.Id) == null)
            {
                cache.Add(request.GameSession);
            }
            else
            {
                response.Errors += "Game session already exists.";
                logger.LogError($"Game session ({request.GameSession.Id}) already exists.");
            }
            response.GameSession = request.GameSession;
            return(await Task.FromResult(response));
        }
Ejemplo n.º 17
0
        public async Task <GetCurrentPlayerResponse> GetCurrentPlayerAsync(GetCurrentPlayerRequest request)
        {
            var response = ServiceMessageFactory <GetCurrentPlayerResponse> .CreateFrom(request);

            var sessionRequest = ServiceMessageFactory <GetGameSessionRequest> .CreateFrom(request);

            sessionRequest.GameSessionId = request.GameSessionId;
            var sessionResponse = await gameSessionAccess.GetGameSessionAsync(sessionRequest);

            var playerRequest = ServiceMessageFactory <GetPlayerRequest> .CreateFrom(request);

            playerRequest.PlayerId = sessionResponse.GameSession.CurrentPlayerId;
            var playerResponse = await playerAccess.GetPlayerAsync(playerRequest);

            response.Player = playerResponse.Player.Convert();
            return(response);
        }
Ejemplo n.º 18
0
        public async Task <GetGameSessionResponse> GetGameSessionAsync(GetGameSessionRequest request)
        {
            var response = ServiceMessageFactory <GetGameSessionResponse> .CreateFrom(request);

            var gameSession = cache.FirstOrDefault(i => i.Id == request.GameSessionId);

            if (gameSession != null)
            {
                response.GameSession = gameSession;
            }
            else
            {
                response.Errors += "Unable to find game session.";
                logger.LogError($"Unable to find game session ({request.GameSessionId}).");
            }
            return(await Task.FromResult(response));
        }
Ejemplo n.º 19
0
        public async Task <UpdateTileResponse> UpdateTileAsync(UpdateTileRequest request)
        {
            var response = ServiceMessageFactory <UpdateTileResponse> .CreateFrom(request);

            var cachedTile = cache.FirstOrDefault(i => i.Id == request.Tile.Id);

            if (cachedTile != null)
            {
                cachedTile.PlayerId = request.Tile.PlayerId;
                response.Tile       = cachedTile;
            }
            else
            {
                response.Errors = "Unable to find the tile to update.";
            }
            return(await Task.FromResult(response));
        }
Ejemplo n.º 20
0
        public async Task <UpdateGameSessionResponse> UpdateGameSessionAsync(UpdateGameSessionRequest request)
        {
            var response = ServiceMessageFactory <UpdateGameSessionResponse> .CreateFrom(request);

            var gameSession = cache.FirstOrDefault(i => i.Id == request.GameSession.Id);

            if (gameSession != null)
            {
                gameSession.CurrentPlayerId = request.GameSession.CurrentPlayerId;
                response.GameSession        = gameSession;
            }
            else
            {
                response.Errors += "Unable to find game session to update.";
                logger.LogError($"Unable to find game session ({gameSession.Id}) to update.");
            }
            return(await Task.FromResult(response));
        }
Ejemplo n.º 21
0
        public async Task <GetTurnPromptResponse> GetTurnPromptAsync(GetTurnPromptRequest request)
        {
            var response = ServiceMessageFactory <GetTurnPromptResponse> .CreateFrom(request);

            var gameSessionRequest = ServiceMessageFactory <GetGameSessionRequest> .CreateFrom(request);

            gameSessionRequest.GameSessionId = request.GameSessionId;
            var gameSessionResponse = await gameSessionAccess.GetGameSessionAsync(gameSessionRequest);

            var gameDefinitionRequest = ServiceMessageFactory <GetGameDefinitionRequest> .CreateFrom(request);

            gameDefinitionRequest.GameDefinitionId = gameSessionResponse.GameSession.GameDefinitionId;

            var gameDefinitionResponse = await gameDefinitionAccess.GetGameDefinitionAsync(gameDefinitionRequest);

            response.Prompt = gameDefinitionResponse.GameDefinition.TurnPrompt;
            return(response);
        }
Ejemplo n.º 22
0
        public async Task <CreatePlayersResponse> CreatePlayersAsync(CreatePlayersRequest request)
        {
            var response = ServiceMessageFactory <CreatePlayersResponse> .CreateFrom(request);

            var list = new List <Interface.Player>();

            foreach (var player in request.Players)
            {
                cache.Add(player);
                list.Add(player);
            }
            response.Players = list.ToArray();

            if (!cache.IsProperSupersetOf(request.Players))
            {
                response.Errors = "Unable to create all of the players.";
            }
            return(response);
        }
Ejemplo n.º 23
0
        public async Task <CreateTilesResponse> CreateTilesAsync(CreateTilesRequest request)
        {
            Contract.Assert(request.Tiles.Any(), "No tiles input to create.");
            var response = ServiceMessageFactory <CreateTilesResponse> .CreateFrom(request);

            try
            {
                var firstTile = request.Tiles.First();
                foreach (var tile in request.Tiles)
                {
                    if (cache.FirstOrDefault(i => i.Id == tile.Id) == null)
                    {
                        cache.Add(tile);
                    }
                }
                response.Tiles = cache.Where(i => i.GameSessionId == firstTile.GameSessionId).ToArray();
            }
            catch (Exception ex)
            {
                response.Errors = "Unable to add tiles.";
            }
            return(await Task.FromResult(response));
        }
Ejemplo n.º 24
0
        public async Task <ApplyTurnResponse> ApplyTurnAsync(ApplyTurnRequest request)
        {
            var response = ServiceMessageFactory <ApplyTurnResponse> .CreateFrom(request);

            var playerRequest = ServiceMessageFactory <GetPlayerRequest> .CreateFrom(request);

            playerRequest.PlayerId = request.PlayerId;
            var playerResponse = await playerAccess.GetPlayerAsync(playerRequest);

            var playTurnRequest = ServiceMessageFactory <PlayTurnRequest> .CreateFrom(request);

            playTurnRequest.GameSessionId = request.GameSessionId;
            playTurnRequest.PlayerId      = request.PlayerId;
            playTurnRequest.Address       = request.Address;
            playTurnRequest.IsAutoPlay    = playerResponse.Player.IsMachine;

            var playTurnResponse = await gamePlayEngine.PlayTurnAsync(playTurnRequest);

            if (playTurnResponse.HasErrors)
            {
                logger.LogError($"{InstanceId}: {playTurnResponse.Errors}");
            }
            return(response);
        }
Ejemplo n.º 25
0
        public async Task <GetGameBoardResponse> GetBoardAsync(GetGameBoardRequest request)
        {
            var response = ServiceMessageFactory <GetGameBoardResponse> .CreateFrom(request);

            var gameSessionRequest = ServiceMessageFactory <GetGameSessionRequest> .CreateFrom(request);

            gameSessionRequest.GameSessionId = request.GameSessionId;
            var gameSessionResponse = await gameSessionAccess.GetGameSessionAsync(gameSessionRequest);

            if (gameSessionResponse.HasErrors)
            {
                response.Errors = "Unable to get the selected game board.  Session error.";
                return(response);
            }

            var gameSession = gameSessionResponse.GameSession;

            // Board for Tic-Tac-Toe
            var players = new List <Player>();

            foreach (var playerId in gameSession.PlayerIds)
            {
                var playerRequest = ServiceMessageFactory <GetPlayerRequest> .CreateFrom(request);

                playerRequest.PlayerId = playerId;
                var playerResponse = await playerAccess.GetPlayerAsync(playerRequest);

                players.Add(playerResponse.Player);
            }

            response.GameBoard = new DataTable();
            response.GameBoard.Columns.Add(new DataColumn(" "));
            response.GameBoard.Columns.Add(new DataColumn("A"));
            response.GameBoard.Columns.Add(new DataColumn("B"));
            response.GameBoard.Columns.Add(new DataColumn("C"));

            var tileRequest = ServiceMessageFactory <FindTilesRequest> .CreateFrom(request);

            tileRequest.Filter = tile => tile.GameSessionId == request.GameSessionId;
            var tileResponse = await tileAccess.FindTilesAsync(tileRequest);

            var tiles = tileResponse.Tiles;

            if (tileResponse.HasErrors)
            {
                return(response);
            }

            var dataRow = response.GameBoard.NewRow();

            dataRow[0] = 1;
            dataRow[1] = (tiles[0].PlayerId == Guid.Empty ? " " : players.First(i => i.Id == tiles[0].PlayerId).GamePiece);
            dataRow[2] = (tiles[3].PlayerId == Guid.Empty ? " " : players.First(i => i.Id == tiles[3].PlayerId).GamePiece);
            dataRow[3] = (tiles[6].PlayerId == Guid.Empty ? " " : players.First(i => i.Id == tiles[6].PlayerId).GamePiece);
            response.GameBoard.Rows.Add(dataRow);

            dataRow    = response.GameBoard.NewRow();
            dataRow[0] = 2;
            dataRow[1] = (tiles[1].PlayerId == Guid.Empty ? " " : players.First(i => i.Id == tiles[1].PlayerId).GamePiece);
            dataRow[2] = (tiles[4].PlayerId == Guid.Empty ? " " : players.First(i => i.Id == tiles[4].PlayerId).GamePiece);
            dataRow[3] = (tiles[7].PlayerId == Guid.Empty ? " " : players.First(i => i.Id == tiles[7].PlayerId).GamePiece);
            response.GameBoard.Rows.Add(dataRow);

            dataRow    = response.GameBoard.NewRow();
            dataRow[0] = 3;
            dataRow[1] = (tiles[2].PlayerId == Guid.Empty ? " " : players.First(i => i.Id == tiles[2].PlayerId).GamePiece);
            dataRow[2] = (tiles[5].PlayerId == Guid.Empty ? " " : players.First(i => i.Id == tiles[5].PlayerId).GamePiece);
            dataRow[3] = (tiles[8].PlayerId == Guid.Empty ? " " : players.First(i => i.Id == tiles[8].PlayerId).GamePiece);
            response.GameBoard.Rows.Add(dataRow);

            return(response);
        }
Ejemplo n.º 26
0
        public async Task Run()
        {
            //
            // Select Game
            // Initialize players
            // Run Game - Loop
            //   Get Turn Input
            //   ValidateAsync Input
            //   Apply Input
            //   Check Game Status
            //   If Finished
            //     Exit Loop
            // Declare Winner
            //

            // Setup game.
            // This becomes the root message for all that follow.
            // All correlation ids will link back to this message.

            var(gameDefinition, request) = await SelectGame();

            var playerCount = await SelectPlayerCount(gameDefinition);

            var startGameRequest = ServiceMessageFactory <StartGameRequest> .CreateFrom(request);

            startGameRequest.GameDefinitionId = gameDefinition.Id;
            startGameRequest.PlayerCount      = playerCount;

            // Start a game
            var gameSessionResponse = await gameManager.StartGameAsync(startGameRequest);

            Console.WriteLine($"Starting {gameDefinition.Name}");

            var boardRequest = ServiceMessageFactory <GetBoardRequest> .CreateFrom(request);

            boardRequest.GameSessionId = gameSessionResponse.GameSessionId;

            var boardResponse = await gameManager.GetBoardAsync(boardRequest);

            ConsoleHelper.ShowGameBoard(boardResponse.GameBoard);

            bool isGamePlayable;

            do
            {
                var currentPlayerRequest = ServiceMessageFactory <GetCurrentPlayerRequest> .CreateFrom(request);

                currentPlayerRequest.GameSessionId = gameSessionResponse.GameSessionId;
                var currentPlayerResponse = await gameManager.GetCurrentPlayerAsync(currentPlayerRequest);

                if (currentPlayerResponse.Player.IsMachine)
                {
                    var applyTurnRequest = ServiceMessageFactory <ApplyTurnRequest> .CreateFrom(request);

                    applyTurnRequest.PlayerId      = currentPlayerResponse.Player.Id;
                    applyTurnRequest.GameSessionId = gameSessionResponse.GameSessionId;
                    var applyTurnResponse = await gameManager.ApplyTurnAsync(applyTurnRequest);

                    // ToDo: Log any errors.
                }
                else
                {
                    var inputIsInvalid = true;
                    do
                    {
                        Console.WriteLine($"{gameDefinition.TurnPrompt} {currentPlayerResponse.Player.Name} ({currentPlayerResponse.Player.GamePiece}).");
                        var userInput = ConsoleHelper.GetStringInput();
                        var confirmUsableAddressRequest = ServiceMessageFactory <ConfirmUsableAddressRequest> .CreateFrom(request);

                        confirmUsableAddressRequest.Address       = userInput;
                        confirmUsableAddressRequest.GameSessionId = gameSessionResponse.GameSessionId;
                        var validationResultResponse = await gameManager.ConfirmUsableAddressAsync(confirmUsableAddressRequest);

                        if (validationResultResponse.ValidationResult == ValidationResult.Success)
                        {
                            var applyTurnRequest = ServiceMessageFactory <ApplyTurnRequest> .CreateFrom(request);

                            applyTurnRequest.PlayerId      = currentPlayerResponse.Player.Id;
                            applyTurnRequest.GameSessionId = gameSessionResponse.GameSessionId;
                            applyTurnRequest.Address       = userInput;
                            var applyTurnResponse = await gameManager.ApplyTurnAsync(applyTurnRequest);

                            // ToDo: Log any errors.
                            inputIsInvalid = false;
                        }
                        else
                        {
                            Console.WriteLine($"{validationResultResponse.ValidationResult.ErrorMessage}.  Please try again.");
                        }
                    } while (inputIsInvalid);
                }

                var isGamePlayableRequest = ServiceMessageFactory <IsGamePlayableRequest> .CreateFrom(request);

                isGamePlayableRequest.GameSessionId = gameSessionResponse.GameSessionId;
                var isGamePlayableResponse = await gameManager.IsGamePlayableAsync(isGamePlayableRequest);

                // ToDo: Log errors
                isGamePlayable = isGamePlayableResponse.IsPlayable;
            } while (isGamePlayable);

            boardRequest = ServiceMessageFactory <GetBoardRequest> .CreateFrom(request);

            boardRequest.GameSessionId = gameSessionResponse.GameSessionId;
            boardResponse = await gameManager.GetBoardAsync(boardRequest);

            ConsoleHelper.ShowGameBoard(boardResponse.GameBoard);

            var findWinnerRequest = ServiceMessageFactory <FindWinnerRequest> .CreateFrom(request);

            findWinnerRequest.GameSessionId = gameSessionResponse.GameSessionId;
            var findWinnerResponse = await gameManager.FindWinnerAsync(findWinnerRequest);

            ConsoleHelper.ShowWinner(findWinnerResponse.Player.Name, findWinnerResponse.Player.GamePiece);

            ConsoleHelper.ShowExit();
        }
Ejemplo n.º 27
0
        public async Task <FindWinnerResponse> FindWinnerAsync(FindWinnerRequest request)
        {
            var response = ServiceMessageFactory <FindWinnerResponse> .CreateFrom(request);

            var tilesRequest = ServiceMessageFactory <FindTilesRequest> .CreateFrom(request);

            tilesRequest.Filter = tile => tile.GameSessionId == request.GameSessionId;
            var tilesResponse = await tileAccess.FindTilesAsync(tilesRequest);

            var dictionary = tilesResponse.Tiles.ToDictionary(tile => tile.Address, tile => tile.Convert());
            var playerId   = Guid.Empty;

            // Check all possible vectors
            // A Col
            if (IsWinningVector(dictionary["A1"], dictionary["A2"], dictionary["A3"]))
            {
                playerId = dictionary["A1"].PlayerId;
            }

            // B Col
            else if (IsWinningVector(dictionary["B1"], dictionary["B2"], dictionary["B3"]))
            {
                playerId = dictionary["B1"].PlayerId;
            }

            // C Col
            else if (IsWinningVector(dictionary["C1"], dictionary["C2"], dictionary["C3"]))
            {
                playerId = dictionary["C1"].PlayerId;
            }

            // 1 Row
            else if (IsWinningVector(dictionary["A1"], dictionary["A2"], dictionary["A3"]))
            {
                playerId = dictionary["A1"].PlayerId;
            }

            // 2 Row
            else if (IsWinningVector(dictionary["B1"], dictionary["B2"], dictionary["B3"]))
            {
                playerId = dictionary["B1"].PlayerId;
            }

            // 3 Row
            else if (IsWinningVector(dictionary["C1"], dictionary["C2"], dictionary["C3"]))
            {
                playerId = dictionary["C1"].PlayerId;
            }

            // Right Diagonal
            else if (IsWinningVector(dictionary["A1"], dictionary["B2"], dictionary["C3"]))
            {
                playerId = dictionary["A1"].PlayerId;
            }

            // Left Diagonal
            else if (IsWinningVector(dictionary["A3"], dictionary["B2"], dictionary["C1"]))
            {
                playerId = dictionary["A3"].PlayerId;
            }

            var playerRequest = ServiceMessageFactory <GetPlayerRequest> .CreateFrom(request);

            playerRequest.PlayerId = playerId;
            var playerResponse = await playerAccess.GetPlayerAsync(playerRequest);

            response.Player = playerResponse.Player.Convert();

            return(response);
        }
Ejemplo n.º 28
0
        public async Task <InitializeGameResponse> InitializeGameAsync(InitializeGameRequest request)
        {
            var response = ServiceMessageFactory <InitializeGameResponse> .CreateFrom(request);

            var gameDefinitionRequest = ServiceMessageFactory <GetGameDefinitionRequest> .CreateFrom(request);

            gameDefinitionRequest.GameDefinitionId = request.GameDefinitionId;

            var gameDefinitionResponse = await gameDefinitionAccess.GetGameDefinitionAsync(gameDefinitionRequest);

            // Create Players
            var players = new List <Player>();

            for (var idx = 0; idx < gameDefinitionResponse.GameDefinition.GamePieces.Length; idx++)
            {
                var name      = $"Player {idx + 1}";
                var gamePiece = gameDefinitionResponse.GameDefinition.GamePieces[idx];
                var isMachine = request.NumberOfPlayers <= idx;

                var player = PlayerFactory.Create(name, gamePiece, isMachine);
                players.Add(player);
            }

            var createPlayersRequest = ServiceMessageFactory <CreatePlayersRequest> .CreateFrom(request);

            createPlayersRequest.Players = players.Convert();
            var createPlayerResponse = await playerAccess.CreatePlayersAsync(createPlayersRequest);

            if (createPlayerResponse.HasErrors)
            {
                logger.LogError($"{createPlayerResponse.Errors}");
            }


            var playerIds   = players.Select(i => i.Id).ToArray();
            var gameSession = GameSessionFactory.Create(request.GameDefinitionId, playerIds);

            var gameSessionRequest = ServiceMessageFactory <CreateGameSessionRequest> .CreateFrom(request);

            gameSessionRequest.GameSession = gameSession.Convert();

            var gameSessionResponse = await gameSessionAccess.CreateGameSessionAsync(gameSessionRequest);

            if (!gameSessionResponse.HasErrors)
            {
                response.GameSession = gameSessionResponse.GameSession.Convert();
            }
            else
            {
                response.Errors += "Unable to create game session.";
                logger.LogError($"Unable to create game session ({response.GameSession.Id}).");
            }

            var tilesRequest = ServiceMessageFactory <CreateTilesRequest> .CreateFrom(request);

            var tiles = TicTacToeBoardFactory.Create(gameSession.Id, new[] { "A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3" });

            tilesRequest.Tiles = tiles.Convert();

            var tilesResponse = await tileAccess.CreateTilesAsync(tilesRequest);

            if (!tilesResponse.HasErrors)
            {
                return(response);
            }

            response.Errors += "Unable to create game tiles.";
            logger.LogError($"Unable to create game tiles for game session ({response.GameSession.Id}).");

            return(response);
        }
Ejemplo n.º 29
0
        public async Task <IsGamePlayableResponse> IsGamePlayableAsync(IsGamePlayableRequest request)
        {
            var response = ServiceMessageFactory <IsGamePlayableResponse> .CreateFrom(request);

            var tilesRequest = ServiceMessageFactory <FindTilesRequest> .CreateFrom(request);

            tilesRequest.Filter = tile => tile.GameSessionId == request.GameSessionId;
            var tileResponse = await tileAccess.FindTilesAsync(tilesRequest);

            var tiles = tileResponse.Tiles;

            if (tiles.All(i => i.IsEmpty))
            // New Game
            {
                response.Value = true;
            }
            else if (tiles.All(i => !i.IsEmpty))
            // No empty spaces.
            {
                response.Value = false;
            }

            // Check all possible vectors
            var dictionary = tiles.ToDictionary(tile => tile.Address, tile => tile.Convert());

            // A Col
            if (IsWinningVector(dictionary["A1"], dictionary["A2"], dictionary["A3"]))
            {
                response.Value = false;
            }
            else

            // B Col
            if (IsWinningVector(dictionary["B1"], dictionary["B2"], dictionary["B3"]))
            {
                response.Value = false;
            }
            else

            // C Col
            if (IsWinningVector(dictionary["C1"], dictionary["C2"], dictionary["C3"]))
            {
                response.Value = false;
            }
            else

            // 1 Row
            if (IsWinningVector(dictionary["A1"], dictionary["A2"], dictionary["A3"]))
            {
                response.Value = false;
            }
            else

            // 2 Row
            if (IsWinningVector(dictionary["B1"], dictionary["B2"], dictionary["B3"]))
            {
                response.Value = false;
            }
            else

            // 3 Row
            if (IsWinningVector(dictionary["C1"], dictionary["C2"], dictionary["C3"]))
            {
                response.Value = false;
            }
            else

            // Right Diagonal
            if (IsWinningVector(dictionary["A1"], dictionary["B2"], dictionary["C3"]))
            {
                response.Value = false;
            }
            else

            // Left Diagonal
            if (IsWinningVector(dictionary["A3"], dictionary["B2"], dictionary["C1"]))
            {
                response.Value = false;
            }
            else
            {
                response.Value = true;
            }
            return(response);
        }