help with MATLAB battleship program
Ältere Kommentare anzeigen
Hi all, Im working on a battleship assignment for a class. Here is the code I have so far:
clear all
close all
clc
rowdim=input('give me the number of rows on the board: ');
coldim=input('give me the number of columns on the board: ');
GameBoard=zeros(rowdim,coldim); %defined board dimensions
%matlab puts a random ship on the board
battleship_row=randi(rowdim,[1 1]) %random row
battleship_col=randi(coldim,[1 1]) %random column
GameBoard(battleship_row,battleship_col)=0;%%'0' hides the loaction of the battleship (unless it is correct)
%playguess
for guessnum=1:5
rowguess=input('guess what row the battleship is in: ');
colguess=input('guess what column the battleship is in: ');
[winloss]=results(rowguess,colguess,battleship_row,battleship_col);
%assesses the results
if winloss == 1
GameBoard(rowguess,colguess)=3; %marks winning guess with '3' on board
break; %finishes the loop, because you won
GameBoard %displays the winning gameboard
else
disp('try again')
GameBoard(rowguess,colguess)=2; %mark loss with '2' on board if guess is incorrect
GameBoard %displays the gameboard to visualize your loss
end
end
GameBoard
[winloss]=results(rowguess,colguess,battleship_row,battleship_col); %calling subplot
%subfunction from here on
function [winloss]=results(rowguess,colguess,battleship_row,battleship_col)
if (rowguess == battleship_row) && (colguess == battleship_col);
winloss=1;
disp ('You sunk the battleship! You won!');
else
winloss=0;
disp(' ');
end
end
I would like to add more battleships to the game board (there is currently only 1) . What are some ways I can go about doing that?
Akzeptierte Antwort
Weitere Antworten (1)
Image Analyst
am 7 Okt. 2021
You need a function that's called BuildBoard() or something. Then in there call a function called PlaceShip() the required number of times.
function gameBoard = BuildBoard(rows, columns, numberOfShips)
gameBoard = false(rows, columns); % Initialize a blank board.
maxShipLength = 5;
shipSizes = randi(maxShipLength, 1, numberOfShips)
for k = 1 : numberOfShips
gameBoard = PlaceShip(shipSizes(k));
end
Then in PlaceShip() you get a random location and direction. Then see if any of those locations is yet occupied by a prior ship. If none are then set those locations of gameBoard to true, otherwise try a different location until you succeed in placing it.
Kategorien
Mehr zu Board games finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!