0

I'm currently tasked with making a battleships game for college. So for, I've managed to get the ships down within the confines of the grid. My only problem now is validating the ship layout with regards to the ships colliding with other ships. I've read around, and presumably the best course of action is a two pass connected component algorithm, but I'm not entirely sure how I would go about implementing that.

This is what I currently have within my PlaceShips method:

public void placeShips(){
    for(int iter = 0; iter < 5; iter++){
        size = shipSizes[iter];
        rotation = randNum.nextInt(2)+1;
        while(!valid){
            rows = randNum.nextInt(10)+1;
            cols = randNum.nextInt(10)+1;
            if(rotation ==1){
                if (cols > mGame.getmColumns()- size){
                    valid = false;
                }
                else{
                    //assumed that the connected component algorithm needs to go here
                    valid = true;
                }
            }
            else if(rotation == 2){
                if (rows > mGame.getmRows() - size){
                    valid = false;
                }
                else{
                    //assumed that the connected component algorithm needs to go here
                    valid = true;
                }
            }
        }
        valid = false;
        //Draw ships
        for(int i = 0; i < size; i++){
            if(rotation == 1){
                gridPos[cols-1][rows-1] = 1;
                cols = cols + 1;
            }
            else if(rotation == 2){
                gridPos[cols-1][rows-1] = 1;
                rows = rows + 1;
            }
        }
    }
}

}

  • 1
    Not sure of the difficulty of this... why don't you just check the grid at each space the ship is trying to occupy and see if it isn't already occupied? This is more a general programming question than Android related btw :) – Wildcopper Feb 25 '15 at 15:46
  • A quick way would be to keep a boolean array of spaces that are occupied. Then if the random assignment puts it over an occupied space, try another random location and orientation until it fits in an unoccupied area and then update the location array. – Jay Snayder Feb 25 '15 at 15:52
  • You should also mind the rule that ships can't touch each other. So there has to be at least 1 square of distance inbetween 2 ships. – Phantômaxx Feb 25 '15 at 16:10

0 Answers0