Filter löschen
Filter löschen

for a battleship program:how to place a ship of given unit length randomly on a matrix of 10x10?

1 Ansicht (letzte 30 Tage)
i have to make a program for the game battleship (computer vs user) and i made a matrix and ships of different unit lengths:
play_board=zeros(10); disp(play_board) destroyer=[2,2]; submarine=[31,31,31] cruise=[32,32,32] battleship=[4,4,4,4] aircraft_carrier=[5,5,5,5,5]
now i would like to randomly place these on the matrix and i dont know how...i am an absolute beginner and would appreciate help!thankyou

Akzeptierte Antwort

Image Analyst
Image Analyst am 26 Nov. 2013
Bearbeitet: Image Analyst am 26 Nov. 2013
You need to know the starting (upper left) row and column (row1 and col1), and the direction. Maybe you can get it like this:
row1 = randi(size(play_board, 1),1,1);
col1 = randi(size(play_board, 2),1,1);
direction = randi(2, 1, 1); % 1 for vertical, 2 for horizontal.
Of course you need to make sure it fits within the play board for the type of ship you're trying to place, and need to make sure it does not cross any existing ships.
For vertical placement of a submarine:
row2 = row1 + length(submarine) - 1;
col2 = col1;
play_board(row1:row2, col1) = submarine(1);
For horizontal placement of a battleship:
col2 = col1 + length(battleship) - 1;
row2 = row1;
play_board(row1, col1:col2) = battleship(1);
  4 Kommentare
Image Analyst
Image Analyst am 26 Nov. 2013
The first lines just get a random location to try to put one end of the ship. For example, 6,3 or whatever. And it gets a direction, 1 or 2, that says how you should decide whether the ship is vertical or horizontal. Now the other end of the ship is at a different location, right? OK, so how should you decide where that other end is? If we're lying totally in row 3, and one end is at column 5 and the length was 3, then it should occupy columns 5,6, & 7, right? So 5+5-1 = 7, and that is the second column. Then when you say array(row1, col1:col2) = someNumber, it will set all elements in row1 going from col1 to col2 (inclusive) to a value of "someNumber". The number I set it to was the number you assigned to the ship. Does that explain it? Of course there is still stuff left for you to do, for example decide which ship you're going to place, and then once all the ships are placed, how to guess a location and keep track of hits and misses.
Andrés Leonardo Mogollón Benavides
Hi, i have a same project and i wonder. after the program place a random ship into the matrix, how to make sure that the second ship not cross the last one.
i'll apreciate any tip

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Marine and Underwater Vehicles finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by