Beispiel #1
0
        /// <summary>
        /// Place a ship on the game board
        /// </summary>
        /// <param name="ship">Type of ship to place</param>
        /// <param name="cell">Starting cell</param>
        /// <param name="isHorizontal">Indicates if the ship is horizontal</param>
        public void PlaceShip(ShipType ship, Cell cell, bool isHorizontal)
        {
            if (_placedShips.HasFlag(ship))
            {
                throw new CannotPlaceException("This type of ship has already been placed.");
            }

            var shipLength = GetShipLength(ship);

            Cell[] targetRange = null;

            try
            {
                targetRange = cell.Range(shipLength, isHorizontal).ToArray();
            }
            catch (ArgumentOutOfRangeException ex)
            {
                throw new CannotPlaceException("Ship extends beyond board boundaries.", ex);
            }

            if (targetRange.Any(x => _board[x.ToBoardIndex()] != 0))
            {
                throw new CannotPlaceException("Ships may not overlap.");
            }

            foreach (var targetCell in targetRange)
            {
                _board[targetCell.ToBoardIndex()] = ship.ToString()[0];
            }

            _placedShips = _placedShips | ship;
        }