Need help adding a function to a script

1 view (last 30 days)
Alex Skantz
Alex Skantz on 6 Oct 2021
Commented: Daniel S on 6 Oct 2021
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

Answers (1)

Daniel S
Daniel S on 6 Oct 2021
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 Comments
Alex Skantz
Alex Skantz on 6 Oct 2021
Dumb question but how do I call the function? I literally have no idea what im doing.
Daniel S
Daniel S on 6 Oct 2021
call a function generally as follows:
[out1, out2, ...] = functionName(arg1, arg2, ...)

Sign in to comment.

Categories

Find more on Board games in Help Center and File Exchange

Products


Release

R2021a

Community Treasure Hunt

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

Start Hunting!