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

Time:01-03

Im am building a game of battleship and im using the following code to edit a 6 by 6 figure to represent ships being placed in it.

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.

so how can I make the program allow the user to try again after entering 6 and h.

I was trying things like,

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

but nothing like this worked, so any suggestions on what I could do

CodePudding user response:

You can use a "flag" to achieve this sort of try-until-success logic, for example

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...

You could include additional validity tests within the inner if-elseif-else block.

  • Related