MATLAB Answers

I want to randomly plot battleships on my board, but no outputs are present?

11 views (last 30 days)
Gabriella Lazzara
Gabriella Lazzara on 28 Oct 2020 at 15:27
Edited: Gabriella Lazzara 10 minutes ago
This question was flagged by Gabriella Lazzara
%Board
size = 10 %A-J on regular battleship and 1-10
board = zeros(size);
axis([0,10,0,10]);
title('Battleship')
letters = {'A';'B';'C';'D';'E';'F';'G';'H';'I';'J'};
set(gca,'xtick',[1:10],'xticklabel',letters);
grid on
disp(board);
%ship lengths
destroyer = [2,2];
submarine = [31,31,31];
cruiser = [32,32,32];
battleship = [4,4,4,4]
carrier = [5,5,5,5,5]
x1 = randi(10,1);
y1 = randi(1,10);
x2 = x1 + length(submarine) - 1;
col2 = y1;
board(x1:x2, y1) = submarine(1);

  0 Comments

Sign in to comment.

Answers (1)

Cris LaPierre
Cris LaPierre on 28 Oct 2020 at 15:38
You are taking two approaches simultaneously in your code. You create a plot where I suspsect you want to visualize the ships, but then you are populating a matrix with the values. In order for the ships to appear on your axes, you must plot them somehow (plot, scatter, line, etc).
If you want to display board instead, perhaps somethink like heatmap will work?
%Board
size = 10 %A-J on regular battleship and 1-10
size = 10
board = zeros(size);
%ship lengths
destroyer = [2,2];
submarine = [31,31,31];
cruiser = [32,32,32];
battleship = [4,4,4,4];
carrier = [5,5,5,5,5];
x1 = randi(10,1);
y1 = randi(1,10);
x2 = x1 + length(submarine) - 1;
board(x1:x2, y1) = submarine(1)
board = 10×10
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 31 0 0 0 0 0 0 0 0 0 31 0 0 0 0 0 0 0 0 0 31 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
figure
heatmap(board)
title('Battleship')
letters = {'A';'B';'C';'D';'E';'F';'G';'H';'I';'J'};
set(gca,'XDisplayLabels',letters);
colorbar off

  0 Comments

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!