Matmaster
Matmaster

Reputation: 35

How can I place ships for Battleship game?

I have to create 10X10 board and 5 ships each has length of 2,3,3,4,5. Ships shouldn't overlap one another and they should be within the grid(10x10) and they should only be either vertical or horizontal.

I have been working on it for almost two days and the only thing I've been able to do so far is making 4 horizontal and overlapping ships length of 2,3,4,5 on a 10x10 board.

So the part I'm stuck on is as below: 1)I made ships to be within the grid but they are overlapping. 2)I can make 4 ships each length of 2,3,4,5 but can't do 3 to occur twice. 3)I can only do horizontal arrangement not vertical. I want the ship to be either vertical or horizontal randomly.

So the code I've written is as below:

{

matrix = zeros(10,10);
row = randi(size(matrix, 1),1,1); %row number
col = randi(size(matrix, 2),1,1); %column number

for i=2:5
        while  col(1,1)+i-1>10 % Checking if it is within grid
                row = randi(size(matrix, 1),1,1); %row number
                col = randi(size(matrix, 2),1,1); %column number
        end
            matrix(row,col:col+i-1)=i;
            row = randi(size(matrix, 1),1,1); %row number
            col = randi(size(matrix, 2),1,1); %column number


end
matrix

}

I couldn't come up with any solutions. I really appreciate the help in advance.

Upvotes: 3

Views: 1703

Answers (1)

Stack Player
Stack Player

Reputation: 1490

If I am not mistaken, you are having trouble with the approach and not the coding itself.

I would recommend you use a flag (ship ID) for each ship, and enter that ID on every spot occupied by the given ship in the 10x10 matrix (all other spots being 0 for ex).

Now to place a ship:

Randomly select a spot (x,y coordinate) from the free spots of the 10x10 matrix. Let that coordinate represent one end of the ship we are trying to place. Now the ship can only be placed in 4 possible ways (the 4 orientations up/down/left/right starting from this selected coordinate). For each of the 4 possible ways, check (depending on the length of the ship) if:

a) the ship fits and does not go outside the 10x10 matrix

b) the ship does not overlap with an occupied spot

If both are satisfied for 1 or more of the 4 orientations, then pick one at random and place the ship. Otherwise, in a dummy 10x10 matrix, mark this unoccupied spot as a spot that cannot be used to place the current ship, and pick at random another unoccupied spot (which is still plausible, i.e. that is not marked impossible inside our dummy matrix).

Upvotes: 3

Related Questions