number placment for battleship game
1 次查看(过去 30 天)
显示 更早的评论
Hi all
Im making a Battleship game on Matlab and this is my code so far
BSgrid=zeros(10);
BSgrid(randi(numel(BSgrid)))=1
BSgrid(randi(numel(BSgrid)))=2
BSgrid(randi(numel(BSgrid)))=3
BSgrid(randi(numel(BSgrid)))=4
BSgrid(randi(numel(BSgrid)))=5
A=1;
B=2;
C=3;
D=4;
E=5;
F=6;
G=7;
H=8;
I=9;
J=10;
%enter only capital letters!
l=input('enter letter coordinate')
n=input('enter number coordinate')
The way i want to place the ships is by adding numbers that equal the ships length. For example, if the ships length is 4 units, Then u want to place 4 fours on the grid besides each other and diagonal to each other at random when the code runs
I know how to place a single number on the matrix as seen in the code BSgrid(randi(numel(BSgrid)))=4 but i dont know how to add the other fours besides it randomly as well
Can anyone help me with this?
thanks in advance
3 个评论
Rik
2020-3-18
I assume those BSgrid(randi(numel(BSgrid)))=1 lines are intended to put in the ships. As John suggested, this is a multi-step process.
- generate a random coordinate for the bow (or stern) of the ship
- generate a direction for the ship (up, down, left, or right)
- check if this combination of coordinate and direction will fit on your board and if it doesn't overlap an already placed ship
If it doesn't fit, undo everything and go back to step 1, otherwise you can mark all coordinates with the ship index.
You can use find to convert a logical matrix to row and column indices, and you can use sub2ind and ind2sub to convert back and forth between subscripts and linear indices.
%another hint:
L=false(5,5);L(randi(numel(L)))=true;
[r,c]=find(L);
r=r+(0:3);
L(r,c)=true
回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!