Esempio n. 1
0
        public void PlaceShips()
        {
            Random rand = new Random(Guid.NewGuid().GetHashCode());

            foreach (var ship in Ships)
            {
                bool isOpen = true;
                while (isOpen)
                {
                    var startColumn = rand.Next(1, 11);
                    var startRow    = rand.Next(1, 11);
                    int endRow      = startRow;
                    int endColumn   = startColumn;
                    var orientation = rand.Next(1, 101) % 2;

                    if (orientation == 0)
                    {
                        for (int i = 1; i < ship.Length; i++)
                        {
                            endRow++;
                        }
                    }
                    else
                    {
                        for (int i = 1; i < ship.Length; i++)
                        {
                            endColumn++;
                        }
                    }

                    if (endRow > 10 || endColumn > 10)
                    {
                        isOpen = true;
                        continue;
                    }

                    var affectedCells = Ocean.CellsInRange(startRow, startColumn, endRow, endColumn);
                    if (affectedCells.Any(cell => cell.IsOccupied))
                    {
                        isOpen = true;
                        continue;
                    }

                    foreach (var cell in affectedCells)
                    {
                        cell.OccupationType = ship.OccupationType;
                    }
                    isOpen = false;
                }
            }
        }