Exemplo n.º 1
0
        public UpdateAttempt AddShip(AddShipModel model)
        {
            var grid = this.GetGrid();

            var xBoundary = grid.Dimensions.X;
            var yBoundary = grid.Dimensions.Y;

            if (model.IsOutOfBounds(xBoundary, yBoundary))
            {
                return new UpdateAttempt {
                           Message = "Coorindates are out of bounds"
                }
            }
            ;

            var shipId = 1;

            if (grid.Ships != null && grid.Ships.Any())
            {
                shipId = grid.Ships.Select(ship => ship.Id).Max() + 1;
            }

            var orientation = InputHelpers.MapDirectionInput(model.Orientation);

            if (orientation == null)
            {
                return new UpdateAttempt {
                           Message = "Invalid direction"
                }
            }
            ;
            var shipToAdd = new ShipModel
            {
                Id          = shipId,
                Lost        = false,
                Orientation = orientation.Value,
                Position    = new CoordinateModel
                {
                    X = model.Position.X,
                    Y = model.Position.Y,
                }
            };

            grid.Ships = grid.Ships == null ? new[] { shipToAdd } : grid.Ships.Concat(new[] { shipToAdd });
            var gridJson = JsonConvert.SerializeObject(grid);
            var result   = _dataService.UpdateGrid(gridJson);

            return(result);
        }
    }
}