Clear Filters
Clear Filters

How to write code for battle ship

4 views (last 30 days)
Amanda on 3 Dec 2022
Reopened: John D'Errico on 3 Dec 2022
I have a 6 by 6 grid and now I want to place my ships on the grid. I want to write this so if the player chooses the correct square it changes colors and says hit or miss
h = image([0.5 5.5], [0.5 5.5], ones(6,6,3));
xticks(0:6); xticklabels([]);
yticks(0:6); yticklabels([]);
grid on
text(0.5:5.5, 6.5*ones(1,6), string(1:6).')
text(-0.5*ones(1,6), 0.5:5.5, string(1:6).')

Answers (1)

Fifteen12 on 3 Dec 2022
I'm guessing you want a list of indices where your ships are located. This list would have as many entries as the total sum of all the length of your ships. Note that MATLAB can do 1D indexing on multi-dimensional arrays, so if you have a 2x2 grid, you can get the parameters by calling a single index, e.g.:
a = magic(2);
for i = 1:numel(a)
disp(strcat("i: ", string(i), ", a(i): ", string(a(i))));
i: 1, a(i): 1 i: 2, a(i): 4 i: 3, a(i): 3 i: 4, a(i): 2
If you assign each ship to a spot in your 6x6 grid, then you can save a vector of all the indexes where your ships are located. Then, when in your gui someone selects a specific point, you can check if that point is in your list and do any following actions.
N = 6;
ships_at = [1, 2, 3, 9, 15, 21, 27];
clicked_on = [4, 3]; %row column of click
index = clicked_on(1)*N + clicked_on(2);
hit = sum(ships_at == index) == 1;
if hit
% Do something if a ship gets hit here


Find more on Just for fun in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!