Пример #1
0
        public async Task AttackShip_ShouldReturn_SuccessfulAttack(string hpos, string vpos, string orientation, string length)
        {
            //Arrange
            await _battleshipService.CreateBoard();


            var request = new ShipAddRequest
            {
                HorizontalStartingPoint = hpos,
                VerticalStartingPoint   = vpos,
                Orientation             = "vertical",
                Length = length
            };

            //Add Ships.
            var resultAddShip = await _battleshipService.AddShip(request);


            var attackRequest = new AttackRequest
            {
                HorizontalPosition = hpos,
                VerticalPosition   = vpos,
            };

            //Act
            var result = await _battleshipService.AttackShip(attackRequest);

            var remainingLength = _battleshipBoardGame.Ships[0].ShipPosition.Where(x => x.Hit == false).Count();

            Assert.IsTrue(result);

            Assert.That(remainingLength == (Convert.ToInt32(length) - 1));
        }
        public async Task <IActionResult> Post([FromBody] ShipAddRequest request)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
                else
                {
                    var result = await battleshipService.AddShip(request);

                    if (result)
                    {
                        return(Ok(response.Message));
                    }
                    else
                    {
                        return(BadRequest(response.Message));
                    }
                }
            }
            catch (System.Exception ex)
            {
                logger.LogError(ex.Message, ex.StackTrace);
                return(StatusCode(500, "Internal server error"));
            }
        }
        public async Task <bool> IsShipPlacementHorizontallyPossible(ShipAddRequest request, List <List <Cell> > grid)
        {
            int.TryParse(request.VerticalStartingPoint, out int verticalPos);
            int.TryParse(request.HorizontalStartingPoint, out int horizontalPos);
            int.TryParse(request.Length, out int Length);


            for (int i = 0; i < Length; i++)
            {
                if (horizontalPos > 9)
                {
                    response.Message = ResponseMessages.SHIP_OUTOF_BOUNDS;
                    return(false);
                }

                if (grid[verticalPos][horizontalPos].OccupiedStatus == OccupiedStatus.Occupied)
                {
                    response.Message = ResponseMessages.SHIP_OVERLAPPING;
                    return(false);
                }
                //increment vertical index.
                horizontalPos++;
            }

            //Good to add the ship.
            return(true);
        }
        public async Task <bool> IsRequestValid(ShipAddRequest request)
        {
            int h = -1, v = -1, l = -1;
            var serializeRequest = JsonConvert.SerializeObject(request);


            //check if the coordinates are valid
            if (!int.TryParse(request.VerticalStartingPoint, out v))
            {
                response.Message = ResponseMessages.INVALID_REQUEST;
                return(false);
            }
            else if (!int.TryParse(request.HorizontalStartingPoint, out h))
            {
                response.Message = ResponseMessages.INVALID_REQUEST;
                return(false);
            }
            else
            {
                if (v > 9 || v < 0)
                {
                    response.Message = ResponseMessages.INVALID_REQUEST;
                    return(false);
                }
                if (h > 9 || h < 0)
                {
                    response.Message = ResponseMessages.INVALID_REQUEST;
                    return(false);
                }
            }
            if (!int.TryParse(request.Length, out l))
            {
                response.Message = ResponseMessages.INVALID_REQUEST;
                return(false);
            }
            else if (l <= 0)
            {
                response.Message = ResponseMessages.INVALID_REQUEST;
                return(false);
            }
            if (string.IsNullOrEmpty(request.Orientation))
            {
                response.Message = ResponseMessages.INVALID_REQUEST;
                return(false);
            }
            else
            {
                if (request.Orientation.ToLower() == nameof(Orientation.Horizontal).ToLower() ||
                    request.Orientation.ToLower() == nameof(Orientation.Vertical).ToLower()
                    )
                {
                    //All good...
                    logger.LogInformation($"Valid request for Ship: {serializeRequest}");
                    return(true);
                }
            }

            response.Message = ResponseMessages.INVALID_REQUEST;
            return(false);
        }
        public async Task <bool> AddShipHorizontally(ShipAddRequest request, Board board)
        {
            int.TryParse(request.VerticalStartingPoint, out int verticalPos);
            int.TryParse(request.HorizontalStartingPoint, out int horizontalPos);
            int.TryParse(request.Length, out int Length);


            var serializeRequest = JsonConvert.SerializeObject(request);

            logger.LogInformation($"Starting horizontal addition for Ship:{serializeRequest}");
            //bool result = false;

            var boardGrid = board.BoardGrid;

            //check if addition possible
            if (await IsShipPlacementHorizontallyPossible(request, boardGrid.Grid))
            {
                logger.LogInformation("Initiating Addition for Ship: " + serializeRequest);

                //Initialize the BattleShip
                var ship = new BattleShip
                {
                    LengthOfShip = Length,
                    Orientation  = Orientation.Horizontal
                };


                var cells = new List <Cell>();
                //get the all the cells for the ship starting from head to end.
                for (int i = 0; i < Length; i++)
                {
                    //1. Mark the grid cells occupied.
                    boardGrid.Grid[verticalPos][horizontalPos].OccupiedStatus = OccupiedStatus.Occupied;

                    //2. Add cells to Cell list for the ship.
                    cells.Add(new Cell
                    {
                        HIndex         = horizontalPos,
                        VIndex         = verticalPos,
                        OccupiedStatus = OccupiedStatus.Occupied
                    });

                    //change the horizontal index
                    horizontalPos++;
                }
                //Assign the list to
                ship.ShipPosition = cells;
                battleshipBoardGame.Ships.Add(ship);

                //Add Successful.
                logger.LogInformation($"Ship : {serializeRequest} was added successfully!");

                return(true);
            }

            logger.LogInformation($"Ship : {serializeRequest} was not added!");
            return(false);
        }
Пример #6
0
        public async Task AddShip_OnSuccessfulAttack_ShouldReturn_NotAdded(string hpos, string vpos, string orientation, string length)
        {
            //Arrange
            await _battleshipService.CreateBoard();


            var request = new ShipAddRequest
            {
                HorizontalStartingPoint = hpos,
                VerticalStartingPoint   = vpos,
                Orientation             = "vertical",
                Length = length
            };

            //Add Ships.
            var resultAddShip = await _battleshipService.AddShip(request);


            var attackRequest = new AttackRequest
            {
                HorizontalPosition = hpos,
                VerticalPosition   = vpos,
            };

            //Act
            var result = await _battleshipService.AttackShip(attackRequest);

            var remainingLength = _battleshipBoardGame.Ships[0].ShipPosition.Where(x => x.Hit == false).Count();

            //Assert if the attack was successful
            Assert.IsTrue(result);
            Assert.That(remainingLength == (Convert.ToInt32(length) - 1));


            //Add ship

            request = new ShipAddRequest
            {
                HorizontalStartingPoint = hpos,
                VerticalStartingPoint   = vpos,
                Orientation             = "vertical",
                Length = length
            };

            //Add Ships.
            resultAddShip = await _battleshipService.AddShip(request);

            Assert.IsFalse(resultAddShip);
            Assert.That(_response.Message == ResponseMessages.SHIP_OVERLAPPING);
        }
Пример #7
0
        public async Task AttackShip_ShouldReturn_SinkShip(string hpos, string vpos, string orientation, string length)
        {
            //Arrange
            await _battleshipService.CreateBoard();


            var request = new ShipAddRequest
            {
                HorizontalStartingPoint = hpos,
                VerticalStartingPoint   = vpos,
                Orientation             = "vertical",
                Length = length
            };

            //Add Ships
            var resultAddShip = await _battleshipService.AddShip(request);


            AttackRequest attackRequest = new AttackRequest();
            bool          attackResult  = false;

            if (orientation == "vertical")
            {
                //Attack Ship : Attempt#1
                attackRequest = new AttackRequest
                {
                    HorizontalPosition = hpos,
                    VerticalPosition   = vpos,
                };

                //Act
                attackResult = await _battleshipService.AttackShip(attackRequest);


                //Attack Ship : Attempt#2
                var newVPos = Convert.ToInt32(vpos);
                attackRequest = new AttackRequest
                {
                    HorizontalPosition = hpos,
                    VerticalPosition   = (++newVPos).ToString(),
                };

                //Act
                attackResult = await _battleshipService.AttackShip(attackRequest);
            }

            //Assert
            Assert.IsTrue(attackResult);
            Assert.That(_response.Message == ResponseMessages.ATTACK_SUNK_SHIP);
        }
Пример #8
0
        public async Task AddShip_ShouldReturn_FalseForAllInvalidRequest(string hpos, string vpos, string orientation, string length)
        {
            //Arrange
            await _battleshipService.CreateBoard();

            var request = new ShipAddRequest
            {
                HorizontalStartingPoint = hpos,
                VerticalStartingPoint   = vpos,
                Orientation             = orientation,
                Length = length
            };

            //Act
            var result = await _battleshipService.AddShip(request);

            Assert.IsFalse(result);
        }
Пример #9
0
        //Poisition a ship
        public async Task <bool> AddShip(ShipAddRequest request)
        {
            bool result = false;
            var  board  = battleshipBoardGame.Board;

            if (board == null)
            {
                response.Message = ResponseMessages.BOARD_NOT_CREATED;
                return(result);
            }


            var serializeRequest = JsonConvert.SerializeObject(request);

            //Sanitize the request.
            if (await serviceHelper.IsRequestValid(request))
            {
                //check Orientation
                if (request.Orientation == nameof(Orientation.Vertical).ToLower())
                {
                    result = await serviceHelper.AddShipVertically(request, board);
                }
                else
                {
                    if (request.Orientation == nameof(Orientation.Horizontal).ToLower())
                    {
                        result = await serviceHelper.AddShipHorizontally(request, board);
                    }
                }
            }
            if (!result)
            {
                logger.LogInformation($"Invalid request for Ship: {serializeRequest}");
            }
            return(result);
        }