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 (최근 30일)
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%%%

답변 (0개)

카테고리

Help CenterFile Exchange에서 Matrices and Arrays에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by