Beispiel #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);
        }
    }
}
        public ActionResult AddShip(AddShipModel ship)
        {
            if (string.IsNullOrEmpty(ship.Orientation) ||
                ship.Orientation.Length > 1 ||
                !_allowedDirections.Contains(ship.Orientation.ToUpper())
                )
            {
                ModelState.AddModelError("", "Invalid orientation for ship");
            }
            if (!ModelState.IsValid)
            {
                return(Errors());
            }
            var result = _shipTrackingService.AddShip(ship);

            if (result.Success)
            {
                return(this.RenderGrid());
            }
            ModelState.AddModelError("", result.Message);
            return(Errors());
        }