/// <inheritdoc/> public void Fill(IEnumerable <int> shipLengths, IFillableBoard board) { foreach (var shipLength in shipLengths) { PlaceShip(shipLength, board); } }
private static void PlaceShip(int shipLength, IFillableBoard board) { // We try to randomly place ship 1000 times. If we cannot find a place, // we assume that there is not enough space for this ship on the board. var rand = new Random(); for (var attemptsLeft = 1000; attemptsLeft > 0; attemptsLeft--) { var direction = rand.Next(2) == 0 ? Direction.Horizontal : Direction.Vertical; if (board.TryPlaceShip(new BoardIndex( rand.Next(10 - (direction == Direction.Horizontal ? shipLength - 1 : 0)), rand.Next(10 - (direction == Direction.Vertical ? shipLength - 1 : 0))), shipLength, direction)) { // We found a spot return; } } throw new BoardTooOccupiedException(); }