防止船只在 Matlab 的战舰游戏中被放置在界外

preventing a ship from being placed out of bounds in a battleship game in Matlab

我正在构建一个战舰游戏,我正在使用以下代码编辑一个 6 x 6 的图形来表示放置在其中的船只。

top_left_grid= input(.....)
orientation = input(please enter v or h for vertical or horizontal)

if top_left_grid == 1
if orientation == 'v'
% write code to make changes on figure

else 
%write code to make changes on figure
end
end

now sometimes when a specific top_left-grid and orientation are entered the ship would be out of bounds, for example when grid 6 and h are chosen, the ship will be out of bound.

那么如何让程序允许用户在输入 6 和 h 后重试。

我正在尝试,

if top_left_grid == 6
if orientation == 'v'
% write code to make changes on figure

while
else
top_left_grid= input('try again')
end

end

end

但是没有这样的工作,所以对我能做什么有什么建议

您可以使用“标志”来实现这种尝试直到成功的逻辑,例如

validChoice = false; % set flag up front, false so we enter the loop at least once
while ~validChoice
    top_left_grid = input('Enter top-left grid square number','s');
    top_left_grid = str2double( top_left_grid );
    orientation = input('Enter v or h for vertical or horizontal','s');

    if (top_left_grid==6 && strcmpi(orientation,'h'))
        % This is invalid
        disp( 'Invalid choice, cannot fit ship in chosen location, try again...' );
    else
        % Input is OK, set the flag to true so the loop exits
        validChoice = true; 
    end
end
% To get this far there must be a valid choice
% Do whatever you want with "top_left_grid" and "orientation" now...

您可以在内部 if-elseif-else 块中包括额外的有效性测试。