Trying to randomly place "ships" on a matrix for a game of battleship, running a loop to stop ships from overlapping but it continually tells me "index exceeds matrix dimensions", any pointers on how to execute the loop properly would be appreciated

3 vues (au cours des 30 derniers jours)
function M = AddShip( Matrix, length1)
M=Matrix;
%SHIP1--CRUISER(22)
loop_on=0;
while loop_on==0
%%%generate randomn number, gives either vert or horiz direction%%%
direction=rand(1);
if direction <=0.5
direction='vertical';
elseif direction>0.5
direction='horizontal';
end
%%%Generate randomn starting point for SHIP1-Destroyer(22)%%%
StartRow1=randi(10);
StartCol1=randi(10);
%%%if the sum of the numbers on the matrix is greater than 0 there is
%%%already a ship there, so code must run again until a suitable place is
%%%found %%%
if strcmp(direction,'vertical')==1 && sum(M( StartRow1, StartCol1:StartCol1+1 ))>0
elseif strcmp(direction,'horizontal')==1 && sum(M( StartRow1:StartRow1+1, StartCol1))>0
loop_on=0;
else loop_on=1;
end
while loop_on==1
if strcmp(direction,'vertical')==1 %if vertical add to the column
M( StartRow1, StartCol1:StartCol1+1 )=22;
elseif strcmp(direction,'horizontal')==1 %if horizontal add to the row
M( StartRow1:StartRow1+1, StartCol1)=22;
end
end
end
%%%repeat for the other 4 ships%%%

Réponses (0)

Catégories

En savoir plus sur Matrices and Arrays dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by