Exemplo n.º 1
0
    private void GenerateShips()
    {
        Ship ship;

        ShipPart[]     shipParts;
        ShipPart       shipPart;
        CoordsIterator shipCoordsIterator = null;
        int            startRow;
        int            startCol;
        int            shipIndex;
        int            otherShipIndex;
        int            shipPartIndex;
        int            direction;
        int            shipSize;
        bool           valid;

        ships = new Ship[shipsToPlace.Length];
        for (shipIndex = 0; shipIndex < ships.Length; shipIndex++)
        {
            shipSize = shipsToPlace [shipIndex];
            Debug.Log("Find a valid position for ship " + shipIndex);
            // Find a valid start position
            startRow = -1;
            startCol = -1;
            do
            {
                try {
                    startRow           = Random.Range(0, battleFieldHeight);
                    startCol           = Random.Range(0, battleFieldWidth);
                    direction          = Random.Range(0, 4);
                    shipCoordsIterator = CoordsIterator.getIterator(direction, startRow, startCol, shipSize, battleFieldWidth, battleFieldHeight);
                    valid = true;
                    for (otherShipIndex = 0; otherShipIndex < shipIndex; otherShipIndex++)
                    {
                        foreach (Coords shipCoords in shipCoordsIterator)
                        {
                            Debug.Log("Validate Coords: " + shipCoords);
                            valid &= !ships[otherShipIndex].isMyCoord(shipCoords);
                        }
                    }
                }
                catch (System.Exception) {
                    // Not valid star position
                    valid = false;
                }
            } while(!valid);
            Debug.Log("Direction: " + shipCoordsIterator);
            Debug.Log("Start ship coords: (" + startRow + ", " + startCol + ")");
            Debug.Log("Place ship " + shipIndex);
            // Place ship
            ship               = new Ship();
            shipParts          = new ShipPart[shipSize];
            shipPartIndex      = 0;
            shipCoordsIterator = shipCoordsIterator.Reset();
            Debug.Log("Ship size: " + shipSize);
            foreach (Coords shipCoords in shipCoordsIterator)
            {
                Debug.Log("Place Coords: " + shipCoords);
                shipPart = new ShipPart();
                shipPart.setCoords(shipCoords);
                shipPart.setPart(battleField [shipCoords.getRow(), shipCoords.getCol()]);
                shipParts [shipPartIndex] = shipPart;
                shipPartIndex++;
            }
            ship.setShipParts(shipParts);
            ships [shipIndex] = ship;
        }
    }