Help with battleship program hit and miss?
2 次查看(过去 30 天)
显示 更早的评论
So the goal of my code is to get the computer to basically run against itself and play the game battleship. I have the randomize ship assignments, the board the title which I didn't include. I am getting stuck during the t=1:50 where I start trying to get the computer to guess random spaces and display either a 'hit' or a 'miss'. It says ginput is not supported with the heatmap, but I am not sure how else to code it.
I need a starting point on how to get the computer to guess places and show either "hit" or "miss"
Thanks
size = 10; %A-J on regular battleship and 1-10
board = zeros(size);
%all ships are X by 1 or 1 by X
dest = 2;
sub = 3;
cruze = 3;
bship = 4;
carry = 5;
ships = [dest, sub, cruze, bship, carry];
names = [1, 2, 3, 4, 5]; %give ships numbers
for i = 1:1:numel(names)
shipsize = ships(i);
ship = "not placed";
while ship == "not placed"
column = randi(10); %pick a start column to try to place
row = randi(10); %pick a start row
orient = randi(2); %1 = horiz, 2 = vert
if board(row, column) == 0 %we can start to check
lastcolumn = 0;
lastcolumn = column + shipsize;
lastrow = row + shipsize;
score = 0;
if orient == 1
if lastcolumn > size
%do nothing - while will try again
else
for j = 1:1:shipsize
if board(row, column+(j-1)) == 0
%OK
if j == shipsize && score == 0
board(row, column:column+(ships(i)-1)) = names(i);
ship = "placed";
end
else
score = 1;
end
end
end
end
if orient == 2
if lastrow > size
%do nothing - while will try again
else
for j = 1:1:shipsize
if board(row+(j-1), column) == 0
%OK
if j == shipsize && score == 0;
board(row:row+ships(i)-1, column) = names(i);
ship = "placed";
end
else
score = 1;
end
end
end
end
end
end
end
heatmap(board)
for t=1:50
a = ginput()
a(1)=ceil(a(1));
a(2)=ceil(a(2));
if board(a(1),a(2)) == 1
%disp('Hit!');
hit=hit+1;
plot(a(1),a(2), 'rx', 'MarkerSize',34,'LineWidth',5);
if hit == 0
W=msgbox('You Win!');
end
else
%disp('Miss!');
plot(a(1),a(2),'bo','MarkerSize', 24, 'LineWidth',5);
end
end
2 个评论
Cris LaPierre
2020-10-28
编辑:Cris LaPierre
2020-10-29
Why use ginput if you want the computer to play against itself?
Image Analyst
2020-10-28
I'm pretty sure there are lots of battleship game questions in the past. Did you look at any of them? Or in the File Exchange?
回答(1 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Data Distribution Plots 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!