Example #1
0
        public async Task <IActionResult> PlaceShip(Guid boardId, Guid shipId, PlaceShipRequest placeShipRequest)
        {
            var boardTask       = _boardService.GetBoard(boardId);
            var shipTask        = _shipService.GetShip(shipId);
            var shipsPlacedTask = _shipService.GetShipsPlaced(boardId);

            await Task.WhenAll(boardTask, shipTask, shipsPlacedTask);

            var board       = await boardTask;
            var ship        = await shipTask;
            var shipsPlaced = await shipsPlacedTask;

            if (board == null || ship == null)
            {
                return(NotFound());
            }

            if (shipsPlaced.Any(x => x.Id == shipId))
            {
                return(BadRequest("Ship cannot be placed as requested ship already placed"));
            }

            var isShipToBePlacedWithInBoundaries = IsShipToBePlacedWithInBoundaries(board, ship, placeShipRequest);

            if (isShipToBePlacedWithInBoundaries == false)
            {
                return(BadRequest("Ship cannot be placed as positions should not cross boundaries"));
            }

            var shipPlacedPositions = shipsPlaced.SelectMany(x => x.Positions).ToList();
            var haveShipsAlreadyOccupiedThePosition = HaveShipsAlreadyOccupiedThePosition(ship, shipPlacedPositions, placeShipRequest);

            if (haveShipsAlreadyOccupiedThePosition)
            {
                return(BadRequest("Ship cannot be placed as the positions are occupied with ships"));
            }

            await _shipService.PlaceShip(boardId, ship, placeShipRequest);

            return(NoContent());
        }