Beispiel #1
0
        private Ship GenerateShipFor(
            ShipType shipType,
            ref Dictionary <string, string> takenCoordinates)
        {
            var coordinates = new List <(Column, int)>();

            var tries = 0;

            while (coordinates.Count != shipType.NrOfBoxes() && tries < MaxTriesPerShip)
            {
                tries++;
                coordinates.Clear();

                var startingRow    = _random.Next(1, GameConstants.MaxRowCount - shipType.NrOfBoxes());
                var startingColumn = _random.Next(1, GameConstants.MaxColumnCount - shipType.NrOfBoxes());

                if (takenCoordinates.ContainsKey(CoordinateKey.Build(startingColumn, startingRow)))
                {
                    continue;
                }

                var direction = (Direction)_random.Next(2);

                var startingCount = direction switch
                {
                    Direction.Horizontal => startingColumn,
                    Direction.Vertical => startingRow,
                    _ => throw new Exception("Passed ship direction does not exist!")
                };

                for (var index = startingCount; index < startingCount + shipType.NrOfBoxes(); index++)
                {
                    var column = direction == Direction.Horizontal ? index : startingColumn;
                    var row    = direction == Direction.Vertical ? index : startingRow;

                    if (!TryAddCoordinateForBox(column, row, ref takenCoordinates))
                    {
                        continue;
                    }

                    coordinates.Add(((CoordinatesHelper.Column)column, row));
                }
            }

            if (coordinates.Count == shipType.NrOfBoxes())
            {
                return(new Ship(shipType, coordinates));
            }

            return(GenerateShipInASweepingFashion(ref takenCoordinates, shipType));
        }