- You don't call the function anywhere in your code. You need to call it where the orignial code you're replacing was.
- You don't pass battleship_col or battleship_row into the function. Unless you pass them into the function, or define them as global (not recommended), they will be undefined in the function scope.
Need help adding a function to a script
2 ビュー (過去 30 日間)
古いコメントを表示
I need some help. We're programming a battleship game in class. This is the script we did together in class so far and it works perfectly:
%This is our basis for our battlehsip game
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
battleship_row=randi(rowdim,[1 1]); %random row
battleship_col=randi(coldim,[1 1]); %random column
GameBoard(battleship_row,battleship_col)=1;
rowguess=input('guess what row the battleship is in: ');
colguess=input('guess what column the battleship is in: ');
if (rowguess == battleship_row) & (colguess == battleship_col)
disp('You sunk the battleship! You won!');
else
disp(' ')
disp('Better luck next time');
end
GameBoard(rowguess,colguess)=2
disp('KEY: battleship location:1 your guess:2');
However he wanted us to turn lines 15-22 (starting with 'rowguess' and ending with 'end' into a function and I'm not sure how to do it. I suck at functions. Can anyone help me?
This is what I have so far but once i run the script it does nothing after I guess what row or column I think the battleship could be in.
%this is our battleship game, functionized
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
battleship_row=randi(rowdim,[1 1]); %random row
battleship_col=randi(coldim,[1 1]); %random column
GameBoard(battleship_row,battleship_col)=1;
rowguess=input('guess what row the battleship is in: ');
colguess=input('guess what column the battleship is in: ');
function [display]= results(rowguess,colguess)
if (rowguess == battleship_row) & (colguess == battleship_col)
disp('You sunk the battleship! You won!');
else
disp('Better luck next time');
end
end
0 件のコメント
回答 (1 件)
Daniel S
2021 年 10 月 6 日
There are a few issues here:
2 件のコメント
Daniel S
2021 年 10 月 6 日
call a function generally as follows:
[out1, out2, ...] = functionName(arg1, arg2, ...)
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!