public async Task ProperEndingShotShipDestroyedGameEndTest()
        {
            object expected = new GameStateResponse(1234)
            {
                GameStatus = GameStatuses.SHOOTING, NextPlayer = 1, Player2Ships = prepareTwoShipsWithOneMissingDamage()
            };
            var mockCache = MockMemoryCacheServiceWithGetAndSet.GetMemoryCache(expected);

            var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >();

            mockConfig.Setup(config => config.Value).Returns(() => prepareConfig());
            var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object);
            var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null);


            ShotRequest request = new ShotRequest()
            {
                GameId = 1234, PlayerId = 1, Coordinate = new Coordinate(2, 2)
            };

            var result     = controller.Shot(request);
            var viewResult = Assert.IsType <ActionResult <GameStateResponse> >(result);

            Assert.Equal(result.Value.NextPlayer, 0);                                       //no more moves
            Assert.Equal(result.Value.GameStatus, GameStatuses.FINISHED);                   //Game finished
            Assert.Equal(result.Value.WinnerPlayer, 1);                                     //winner
            Assert.Equal(result.Value.Message, "Game finished, player 1 has won the game"); //message
        }
        public async Task IncorrectCoordinatesShotTest()
        {
            object expected = new GameStateResponse(1234)
            {
                GameStatus = GameStatuses.SHOOTING, NextPlayer = 1
            };
            var mockCache = MockMemoryCacheService.GetMemoryCache(expected);

            var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >();

            mockConfig.Setup(config => config.Value).Returns(() => prepareConfig());
            var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object);
            var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null);

            List <Coordinate> incorrectCoordinates = new List <Coordinate> {
                new Coordinate(-1, 1),
                new Coordinate(1, -2),
                new Coordinate(0, 1),
                new Coordinate(1, 0),
                new Coordinate(15, 5),
                new Coordinate(5, 15),
                new Coordinate(15, 15)
            };

            foreach (Coordinate c in  incorrectCoordinates)
            {
                ShotRequest request = new ShotRequest()
                {
                    GameId = 1234, PlayerId = 1, Coordinate = c
                };

                var ex = Assert.Throws <InvalidCoordinatesException>(() => controller.Shot(request));
                Assert.Equal("Invalid coordinates supplied, possible values: columns 1-10, rows 1-10", ex.Message);
            }
        }
        public async Task MissedShotTest()
        {
            object expected = new GameStateResponse(1234)
            {
                GameStatus = GameStatuses.SHOOTING, NextPlayer = 1, Player2Ships = prepareTwoShipsWithOneDamage()
            };
            var mockCache = MockMemoryCacheServiceWithGetAndSet.GetMemoryCache(expected);

            var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >();

            mockConfig.Setup(config => config.Value).Returns(() => prepareConfig());
            var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object);
            var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null);


            ShotRequest request = new ShotRequest()
            {
                GameId = 1234, PlayerId = 1, Coordinate = new Coordinate(5, 5)
            };

            var result     = controller.Shot(request);
            var viewResult = Assert.IsType <ActionResult <GameStateResponse> >(result);

            Assert.Equal(result.Value.NextPlayer, 2);                     //swapped players
            Assert.Equal(result.Value.GameStatus, GameStatuses.SHOOTING); //game still going
            Assert.Equal(result.Value.Message, "Missed!");                //message
        }
        public async Task InvalidShipIntegrityPlacingTest()
        {
            object expected  = new GameStateResponse(1234); //status = placing
            var    mockCache = MockMemoryCacheService.GetMemoryCache(expected);

            var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >();

            mockConfig.Setup(config => config.Value).Returns(() => prepareConfig());
            var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object);
            var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null);

            List <ShipPlacement> incorrectShips = prepareValidShipsWithoutOne2Fielded();

            incorrectShips.Add(new ShipPlacement {
                Coordinates = new List <Coordinate> {
                    new Coordinate(8, 8), new Coordinate(10, 8)
                }
            });                                                                                                                           //desintegrated ship

            ShipPlacementRequest request = new ShipPlacementRequest()
            {
                GameId = 1234, PlayerId = 1, Ships = incorrectShips
            };

            var ex = Assert.Throws <InvalidShipIntegrityException>(() => controller.PlaceShips(request));

            Assert.Equal("Each ship needs to have connected coordinates", ex.Message);
        }
Beispiel #5
0
        public async Task NewGame_ReturnsEmptyBoard()
        {
            var expectedGameState = new GameStateResponse("{[_,_,_,_,_,_,_,_,_]}");
            var response          = await PostNewGameRequest();

            await AssertResponse(response, expectedGameState);
        }
        public async Task ProperPlacementWaitingForSecondPlayerPlacingTest()
        {
            object expected  = new GameStateResponse(1234); //status = placing
            var    mockCache = MockMemoryCacheServiceWithGetAndSet.GetMemoryCache(expected);

            var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >();

            mockConfig.Setup(config => config.Value).Returns(() => prepareConfig());
            var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object);
            var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null);

            List <ShipPlacement> correctShips = prepareValidShipsWithoutOne2Fielded();

            correctShips.Add(new ShipPlacement {
                Coordinates = new List <Coordinate> {
                    new Coordinate(8, 8), new Coordinate(9, 8)
                }
            });

            ShipPlacementRequest request = new ShipPlacementRequest()
            {
                GameId = 1234, PlayerId = 1, Ships = correctShips
            };

            var result     = controller.PlaceShips(request);
            var viewResult = Assert.IsType <ActionResult <GameStateResponse> >(result);
            GameStateResponse expectedNewGame = new GameStateResponse(1234);

            Assert.Equal(result.Value.NextPlayer, 0);                    //still waiting for second player to place ships
            Assert.Equal(result.Value.GameStatus, GameStatuses.PLACING); //still waiting for second player to place ships
            Assert.True(result.Value.Player1Ships.Count > 0);            //ships placed by first player
        }
        public async Task IncorrectCoordinatesShipsPlacingTest()
        {
            object expected  = new GameStateResponse(1234); //status = placing
            var    mockCache = MockMemoryCacheService.GetMemoryCache(expected);

            var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >();

            mockConfig.Setup(config => config.Value).Returns(() => prepareConfig());
            var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object);
            var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null);

            List <ShipPlacement> incorrectShips = new List <ShipPlacement> {  // INCORRECT COORDINATE 1,12
                new ShipPlacement {
                    Coordinates = new List <Coordinate> {
                        new Coordinate(1, 12), new Coordinate(1, 2)
                    }
                },
                new ShipPlacement {
                    Coordinates = new List <Coordinate> {
                        new Coordinate(3, 2), new Coordinate(2, 2)
                    }
                }
            };
            ShipPlacementRequest request = new ShipPlacementRequest()
            {
                GameId = 1234, PlayerId = 1, Ships = incorrectShips
            };

            var ex = Assert.Throws <InvalidCoordinatesException>(() => controller.PlaceShips(request));

            Assert.Equal("Invalid coordinates supplied, possible values: columns 1-10, rows 1-10", ex.Message);
        }
        public async Task InvalidShipAmountPlacingTest()
        {
            object expected  = new GameStateResponse(1234); //status = placing
            var    mockCache = MockMemoryCacheService.GetMemoryCache(expected);

            var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >();

            mockConfig.Setup(config => config.Value).Returns(() => prepareConfig());
            var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object);
            var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null);

            List <ShipPlacement> incorrectShips = new List <ShipPlacement> { //ONLY 2 SHIPS
                new ShipPlacement {
                    Coordinates = new List <Coordinate> {
                        new Coordinate(1, 1), new Coordinate(1, 2)
                    }
                },
                new ShipPlacement {
                    Coordinates = new List <Coordinate> {
                        new Coordinate(3, 2), new Coordinate(2, 2)
                    }
                }
            };
            ShipPlacementRequest request = new ShipPlacementRequest()
            {
                GameId = 1234, PlayerId = 1, Ships = incorrectShips
            };

            var ex = Assert.Throws <InvalidShipAmountException>(() => controller.PlaceShips(request));

            Assert.Equal("Provided ships do not conform to the configured amounts, which is: [{\"Size\":5,\"Amount\":1},{\"Size\":4,\"Amount\":2},{\"Size\":3,\"Amount\":3},{\"Size\":2,\"Amount\":4}]", ex.Message);
        }
        public async Task CollidingShipsPlacingTest()
        {
            object expected  = new GameStateResponse(1234); //status = placing
            var    mockCache = MockMemoryCacheService.GetMemoryCache(expected);

            var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >();

            mockConfig.Setup(config => config.Value).Returns(() => prepareConfig());
            var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object);
            var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null);

            List <ShipPlacement> incorrectShips = new List <ShipPlacement> {  // COLLISION!
                new ShipPlacement {
                    Coordinates = new List <Coordinate> {
                        new Coordinate(1, 1), new Coordinate(1, 2)
                    }
                },
                new ShipPlacement {
                    Coordinates = new List <Coordinate> {
                        new Coordinate(1, 2), new Coordinate(2, 2)
                    }
                }
            };
            ShipPlacementRequest request = new ShipPlacementRequest()
            {
                GameId = 1234, PlayerId = 1, Ships = incorrectShips
            };

            var ex = Assert.Throws <CollidingShipsLogError>(() => controller.PlaceShips(request));

            Assert.Equal("Provided ships are colliding as they share coordinates", ex.Message);
        }
Beispiel #10
0
        public ActionResult <ApiResponse <GameStateResponse> > GameState(
            [FromHeader(Name = Defaults.SessionIdHeader)] Guid sessionId)
        {
            try
            {
                var state = gameControlService.GetCurrentGameState(sessionId);

                var transitions = state.Transitions
                                  .Select(t => new Transition
                {
                    Key          = t.Key,
                    TextAssetKey = t.TextAssetKey,
                    IsEnabled    = t.IsEnabled,
                    IsVisible    = t.IsVisible
                })
                                  .ToList();
                var response = new GameStateResponse
                {
                    TextAssetKey  = state.TextAssetKey,
                    ImageAssetKey = state.ImageAssetKey,
                    Transitions   = transitions
                };

                return(Ok(ApiResponse <GameStateResponse> .MakeSuccess(response)));
            }
            catch (Exception ex)
            {
                return(ApiError(ApiResponse <GameStateResponse> .MakeError(ex)));
            }
        }
        /// <summary>
        /// Players upgrade request processing
        /// </summary>
        /// <param name="clientID"></param>
        /// <param name="request"></param>
        public void ProcessUpgradeRequest(int clientID, UpgradeRequest request)
        {
            Player player = PlayersManager.GetPlayer(clientID);

            if (player == null)
            {
                Console.WriteLine($"Can't find player {clientID}");
                return;
            }
            if (player.CurrentMatch == null)
            {
                Console.WriteLine($"Player {player.ClientID} is not in the game");
                return;
            }

            GameMatch match       = player.CurrentMatch;
            Field     playerField = match.Player1 == player ? match.Field1 : match.Field2;
            Field     enemyField  = match.Player1 == player ? match.Field2 : match.Field1;
            Player    enemy       = match.Player1 == player ? match.Player2 : match.Player1;

            FieldManager.RefreshDurationEffects(playerField);
            FieldManager.RefreshDurationEffects(enemyField);
            FieldManager.RefreshGlobalEffects(playerField, player);
            FieldManager.RefreshGlobalEffects(enemyField, enemy);

            UpgradeRequestResponse upgradeResponse = UpgradeManager.ProcessUpgradeRequest(match, player, request.UpgradeBlockType);

            switch (upgradeResponse)
            {
            case UpgradeRequestResponse.Ok:
                break;

            case UpgradeRequestResponse.NotEnoughMana:
                SendError(player, ErrorType.NotEnoughMana);
                return;

            default:
                throw new ArgumentOutOfRangeException();
            }

            GameStateResponse response = new GameStateResponse
            {
                GameState = GetPlayer1MatchStateData(match),
                Effects   = new EffectData[0],
            };

            Server.SendDataToClient(match.Player1.ClientID, (int)DataTypes.GameStateResponse, response);

            if (match.GameMode == GameMode.Practice)
            {
                return;
            }

            response = new GameStateResponse
            {
                GameState = GetPlayer2MatchStateData(match),
                Effects   = new EffectData[0]
            };
            Server.SendDataToClient(match.Player2.ClientID, (int)DataTypes.GameStateResponse, response);
        }
 public void UpdateActions(GameStateResponse state, GameActions?action)
 {
     ActionHistory ??= new Dictionary <int, GameActions>();
     if (action.HasValue)
     {
         ActionHistory[state.Turn] = action.Value;
     }
 }
Beispiel #13
0
        private static async Task AssertResponse(HttpResponseMessage response, GameStateResponse expectedGameState)
        {
            var expectedJson    = JsonConvert.SerializeObject(expectedGameState);
            var responseContent = await response.Content.ReadAsStringAsync();

            Assert.That(response.StatusCode, Is.EqualTo(HttpStatusCode.OK));
            Assert.That(responseContent, Is.EqualTo(expectedJson));
        }
Beispiel #14
0
        public async Task Move_WhenOneMoveWasMade_ReturnsBoardWith_o()
        {
            var expectedGameState = new GameStateResponse("{[o,_,_,_,_,_,_,_,_]}", GameOutcome.OpenOutcome);

            await PostNewGameRequest();

            var response = await PostMoveRequest(0);

            await AssertResponse(response, expectedGameState);
        }
        /// <summary>
        /// Change game state - players, fields etc
        /// </summary>
        /// <param name="data"></param>
        public void ChangeGameState(GameStateResponse data)
        {
            if (Guid.Parse(data.GameState.GameID) != GameID)
            {
                Debug.LogWarning($"Got game state from wrong game: {data.GameState.GameID}");
                return;
            }

            FieldManager.Instance.DeleteFields();

            PlayerManager.Instance.SetPlayerState(data.GameState.MainPlayer);
            PlayerManager.Instance.SetEnemyState(data.GameState.EnemyPlayer);

            FieldManager.Instance.GenerateMainField(data.GameState.MainField);
            FieldManager.Instance.GenerateEnemyField(data.GameState.EnemyField);

            UpgradeManager.Instance.ApplyUpgradeInfo(data.GameState.MainUpgradesInfo);

            foreach (EffectData effect in data.Effects)
            {
                switch (effect.EffectType)
                {
                case EffectType.HealthChanged:
                    PlayerManager.Instance.AnimateHealthEffect(effect);
                    break;

                case EffectType.ManaChanged:
                    PlayerManager.Instance.AnimateManaEffect(effect);
                    break;

                case EffectType.EnergyChanged:
                    PlayerManager.Instance.AnimateEnergyEffect(effect);
                    break;

                case EffectType.BlockShot:
                    FieldManager.Instance.DrawShootEffect(effect);
                    break;

                case EffectType.UniqueEffect:
                    // TODO: temporary
                    FieldManager.Instance.DrawShootEffect(effect);
                    break;

                case EffectType.GlobalEffect:
                    ProcessGlobalEffect(effect);
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
            }
        }
Beispiel #16
0
        private void swapPlayers(GameStateResponse gameState)
        {
            int next;

            if (gameState.NextPlayer == 1)
            {
                next = 2;
            }
            else
            {
                next = 1;
            }
            gameState.NextPlayer = next;
        }
Beispiel #17
0
        public async Task Move_When_o_HasWon_ReturnsGameStateWithOHasWonTrue()
        {
            var expectedGameState = new GameStateResponse("{[o,o,o,x,_,x,_,_,_]}", GameOutcome.OHasWon);

            await PostNewGameRequest();
            await PostMoveRequest(0);
            await PostMoveRequest(3);
            await PostMoveRequest(1);
            await PostMoveRequest(5);

            var response = await PostMoveRequest(2);

            await AssertResponse(response, expectedGameState);
        }
Beispiel #18
0
 public void UpdateState(GameStateResponse state)
 {
     Turn = state.Turn;
     ResidenceBuildings = state.ResidenceBuildings;
     Errors             = state.Errors;
     Funds            = state.Funds;
     Messages         = state.Messages;
     CurrentTemp      = state.CurrentTemp;
     HousingQueue     = state.HousingQueue;
     QueueHappiness   = state.QueueHappiness;
     TotalCo2         = state.TotalCo2;
     TotalHappiness   = state.TotalHappiness;
     UtilityBuildings = state.UtilityBuildings;
 }
Beispiel #19
0
        private void performShot(GameStateResponse gameState, Coordinate coordinate)
        {
            gameState.Message = "";

            List <Ship> ships;

            if (gameState.NextPlayer == 1)
            {
                ships = gameState.Player2Ships;
            }
            else
            {
                ships = gameState.Player1Ships;
            }

            Ship shipBeeingShot = ships.Find(i => i.Placement.Coordinates.Where(j => j.Column == coordinate.Column && j.Row == coordinate.Row).Count() == 1);

            if (shipBeeingShot?.Damages.Coordinates.Where(i => i.Column == coordinate.Column && i.Row == coordinate.Row).Count() > 0)
            {
                gameState.Message = "Do not shoot the same target!";
                swapPlayers(gameState);
                return;
            }
            shipBeeingShot?.Damages.Coordinates.Add(coordinate);

            if (shipBeeingShot != null)
            {
                gameState.Message = "Shot succeeded, Ship not yet destroyed";

                if (shipBeeingShot.checkDestroyed())
                {
                    gameState.Message = "Shot succeeded, Ship destroyed";
                }

                if (ships.Where(i => i.checkDestroyed()).Count() == ships.Count)
                {
                    gameState.WinnerPlayer = gameState.NextPlayer;
                    gameState.GameStatus   = GameStatuses.FINISHED;
                    gameState.Message      = $"Game finished, player {gameState.NextPlayer} has won the game";
                    gameState.NextPlayer   = 0;
                    return;
                }
            }
            else
            {
                gameState.Message = "Missed!";
            }
            swapPlayers(gameState);
        }
Beispiel #20
0
        public async Task Move_WhenGameEndedWithDraw_ReturnsGameStateWithDrwaOutcome()
        {
            var expectedGameState = new GameStateResponse("{[o,x,o,o,x,x,x,o,o]}", GameOutcome.Draw);

            await PostNewGameRequest();
            await PostMoveRequest(0);
            await PostMoveRequest(1);
            await PostMoveRequest(2);
            await PostMoveRequest(4);
            await PostMoveRequest(3);
            await PostMoveRequest(5);
            await PostMoveRequest(7);
            await PostMoveRequest(6);

            var response = await PostMoveRequest(8);

            await AssertResponse(response, expectedGameState);
        }
        public async Task InvalidPlayerIdPlacingTest()
        {
            object expected  = new GameStateResponse(1234); //status = placing
            var    mockCache = MockMemoryCacheService.GetMemoryCache(expected);

            var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >();
            var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object);
            var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null);

            ShipPlacementRequest request = new ShipPlacementRequest()
            {
                GameId = 1234, PlayerId = 15
            };

            var ex = Assert.Throws <InvalidPlayerIdException>(() => controller.PlaceShips(request));

            Assert.Equal("Invalid Player Id. Only Players with Id 1 and 2 are permited", ex.Message);
        }
        public void UpdateState(GameStateResponse state)
        {
            Turn = state.Turn;
            ResidenceBuildings = state.ResidenceBuildings;
            Errors             = state.Errors;
            Funds            = state.Funds;
            Messages         = state.Messages;
            CurrentTemp      = state.CurrentTemp;
            HousingQueue     = state.HousingQueue;
            QueueHappiness   = state.QueueHappiness;
            TotalCo2         = state.TotalCo2;
            TotalHappiness   = state.TotalHappiness;
            UtilityBuildings = state.UtilityBuildings;

            // Custom
            TemperatureHistory ??= new Dictionary <int, double>();
            TemperatureHistory[state.Turn] = state.CurrentTemp;
        }
        public async Task PlacingGameShotTest()
        {
            object expected  = new GameStateResponse(1234); //status = placing
            var    mockCache = MockMemoryCacheService.GetMemoryCache(expected);

            var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >();
            var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object);
            var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null);

            ShotRequest request = new ShotRequest()
            {
                GameId = 1234, PlayerId = 1, Coordinate = new Coordinate(1, 1)
            };

            var ex = Assert.Throws <InvalidGameStatusShootingException>(() => controller.Shot(request));

            Assert.Equal("Game is not in the Shooting mode, current mode: PLACING", ex.Message);
        }
Beispiel #24
0
        public void PlaceShips(ShipPlacementRequest request, GameStateResponse gameState)
        {
            if (gameState == null)
            {
                throw new InvalidGameIdException(request.GameId);
            }

            if (gameState.GameStatus != GameStatuses.PLACING)
            {
                throw new InvalidGameStatusPlacingException(gameState.GameStatus);
            }

            if (request.PlayerId != 1 && request.PlayerId != 2)
            {
                throw new InvalidPlayerIdException();
            }

            validateShipPlacement(request);
            performPlacement(request, gameState);
        }
        public async Task NoShipsPlacingTest()
        {
            object expected  = new GameStateResponse(1234); //status = placing
            var    mockCache = MockMemoryCacheService.GetMemoryCache(expected);

            var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >();

            mockConfig.Setup(config => config.Value).Returns(() => prepareConfig());
            var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object);
            var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null);

            ShipPlacementRequest request = new ShipPlacementRequest()
            {
                GameId = 1234, PlayerId = 1
            };

            var ex = Assert.Throws <NoShipsProvidedException>(() => controller.PlaceShips(request));

            Assert.Equal("No ships provided in placement", ex.Message);
        }
        public async Task IncorrectPlayerGameShotTest()
        {
            object expected = new GameStateResponse(1234)
            {
                GameStatus = GameStatuses.SHOOTING, NextPlayer = 1
            };
            var mockCache = MockMemoryCacheService.GetMemoryCache(expected);

            var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >();
            var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object);
            var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null);

            ShotRequest request = new ShotRequest()
            {
                GameId = 1234, PlayerId = 2, Coordinate = new Coordinate(1, 1)
            };

            var ex = Assert.Throws <InvalidTurnPlayerException>(() => controller.Shot(request));

            Assert.Equal("Not your turn! Wait for player 1 to shot next", ex.Message);
        }
        public async Task FinishedGamePlacingTest()
        {
            object expected = new GameStateResponse(1234)
            {
                GameStatus = GameStatuses.FINISHED
            };
            var mockCache = MockMemoryCacheService.GetMemoryCache(expected);

            var mockConfig = new Moq.Mock <IOptions <BattleshipConfiguration> >();
            var mockEngine = new Moq.Mock <GameEngine>(mockConfig.Object);
            var controller = new BattleShipController(mockCache, mockConfig.Object, mockEngine.Object, null);

            ShipPlacementRequest request = new ShipPlacementRequest()
            {
                GameId = 1234, PlayerId = 1
            };

            var ex = Assert.Throws <InvalidGameStatusPlacingException>(() => controller.PlaceShips(request));

            Assert.Equal("Game already started thus it's no longer possible to place ships, current mode: FINISHED", ex.Message);
        }
Beispiel #28
0
        private void performPlacement(ShipPlacementRequest request, GameStateResponse gameState)
        {
            if (request.PlayerId == 1)
            {
                gameState.Player1Ships = request.Ships.Select(i => new Ship
                {
                    Placement = new ShipPlacement
                    {
                        Coordinates = i.Coordinates
                    },
                    Damages = new ShipPlacement
                    {
                        Coordinates = new List <Coordinate>()
                    }
                }).ToList();
            }
            else if (request.PlayerId == 2)
            {
                gameState.Player2Ships = request.Ships.Select(i => new Ship
                {
                    Placement = new ShipPlacement
                    {
                        Coordinates = i.Coordinates
                    },
                    Damages = new ShipPlacement
                    {
                        Coordinates = new List <Coordinate>()
                    }
                }).ToList();
            }

            if (gameState.Player1Ships.Count() > 0 && gameState.Player2Ships.Count() > 0)
            {
                gameState.GameStatus = GameStatuses.SHOOTING;
                gameState.NextPlayer = 1;
            }
        }
Beispiel #29
0
        public void Shot(ShotRequest request, GameStateResponse gameState)
        {
            if (gameState == null)
            {
                throw new InvalidGameIdException(request.GameId);
            }

            if (gameState.GameStatus != GameStatuses.SHOOTING)
            {
                throw new InvalidGameStatusShootingException(gameState.GameStatus);
            }

            if (gameState.NextPlayer != request.PlayerId)
            {
                throw new InvalidTurnPlayerException(gameState.NextPlayer);
            }

            if (request.Coordinate.Row < 1 || request.Coordinate.Row > _config.Value.MatrixHeight || request.Coordinate.Column < 1 || request.Coordinate.Column > _config.Value.MatrixWidth)
            {
                throw new InvalidCoordinatesException(_config.Value.MatrixWidth, _config.Value.MatrixHeight);
            }

            performShot(gameState, request.Coordinate);
        }
        /// <summary>
        /// Players skill using request processing
        /// </summary>
        /// <param name="clientID"></param>
        /// <param name="request"></param>
        public void ProcessUseSkillRequest(int clientID, UseSkillRequest request)
        {
            Player player = PlayersManager.GetPlayer(clientID);

            if (player == null)
            {
                Console.WriteLine($"Can't find player {clientID}");
                return;
            }

            if (player.CurrentMatch == null)
            {
                Console.WriteLine($"Player {player.ClientID} is not in the game");
                return;
            }

            GameMatch         match       = player.CurrentMatch;
            Field             playerField = match.Player1 == player ? match.Field1 : match.Field2;
            Field             enemyField  = match.Player1 == player ? match.Field2 : match.Field1;
            Player            enemy       = match.Player1 == player ? match.Player2 : match.Player1;
            List <EffectData> effectsData = new List <EffectData>();

            FieldManager.RefreshGlobalEffects(playerField, player);
            FieldManager.RefreshGlobalEffects(enemyField, enemy);

            FieldManager.RefreshDurationEffects(playerField);
            FieldManager.RefreshDurationEffects(enemyField);

            if (request.SkillID != 0 && request.SkillID != 1)
            {
                SendError(player, ErrorType.ImpossibleTurn);
                return;
            }

            int   playerUserIndex = match.Player1 == player ? 1 : 2;
            Skill skill           = player.ActiveSkills[request.SkillID];

            if (!player.TrySpendEnergy(skill.Cost))
            {
                SendError(player, ErrorType.NotEnoughEnergy);
                return;
            }
            else
            {
                EffectData hData = new EffectData();
                hData.EffectType     = EffectType.EnergyChanged;
                hData.Data           = new Dictionary <string, object>();
                hData.Data["Target"] = player.InGameID;
                hData.Data["Value"]  = -skill.Cost;
                effectsData.Add(hData);
            }

            effectsData.AddRange(SkillsManager.ApplySkillEffect(match, playerUserIndex, skill.Name));

            GameStateResponse response = new GameStateResponse
            {
                GameState = GetPlayer1MatchStateData(match),
                Effects   = effectsData.ToArray(),
            };

            Server.SendDataToClient(match.Player1.ClientID, (int)DataTypes.GameStateResponse, response);

            if (match.GameMode == GameMode.Practice)
            {
                FieldManager.SetDefaultState(playerField);
                FieldManager.SetDefaultState(enemyField);

                if (CheckForGameEnd(match, out GameEndResponse gameEndResponseDebug))
                {
                    GiveMatchReward(match, gameEndResponseDebug.PlayerWon);
                    RecalculateRating(match, gameEndResponseDebug.PlayerWon);
                    PlayersManager.UpdatePlayer(match.Player1);

                    MatchManager.DropMatch(player.CurrentMatch);

                    gameEndResponseDebug.PlayerStats = match.Player1.GetStatsData();
                    Server.SendDataToClient(match.Player1.ClientID, (int)DataTypes.GameEndResponse, gameEndResponseDebug);
                }
                return;
            }

            response = new GameStateResponse
            {
                GameState = GetPlayer2MatchStateData(match),
                Effects   = effectsData.ToArray(),
            };
            Server.SendDataToClient(match.Player2.ClientID, (int)DataTypes.GameStateResponse, response);

            FieldManager.SetDefaultState(playerField);
            effectsData.AddRange(FieldManager.ClearDestroyedBlocks(playerField, match, player));
            FieldManager.SetDefaultState(enemyField);
            effectsData.AddRange(FieldManager.ClearDestroyedBlocks(enemyField, match, enemy));

            if (CheckForGameEnd(match, out GameEndResponse gameEndResponse))
            {
                GiveMatchReward(match, gameEndResponse.PlayerWon);
                RecalculateRating(match, gameEndResponse.PlayerWon);
                PlayersManager.UpdatePlayer(match.Player1);
                PlayersManager.UpdatePlayer(match.Player2);

                MatchManager.DropMatch(player.CurrentMatch);

                gameEndResponse.PlayerStats = match.Player1.GetStatsData();
                Server.SendDataToClient(match.Player1.ClientID, (int)DataTypes.GameEndResponse, gameEndResponse);

                gameEndResponse.PlayerStats = match.Player2.GetStatsData();
                Server.SendDataToClient(match.Player2.ClientID, (int)DataTypes.GameEndResponse, gameEndResponse);

                return;
            }
        }