Need help adding a function to a script

1 次查看(过去 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

回答(1 个)

Daniel S
Daniel S 2021-10-6
There are a few issues here:
  1. You don't call the function anywhere in your code. You need to call it where the orignial code you're replacing was.
  2. 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.
  2 个评论
Alex Skantz
Alex Skantz 2021-10-6
Dumb question but how do I call the function? I literally have no idea what im doing.
Daniel S
Daniel S 2021-10-6
call a function generally as follows:
[out1, out2, ...] = functionName(arg1, arg2, ...)

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 Board games 的更多信息

产品


版本

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by