Need help adding a function to a script

1 visualizzazione (ultimi 30 giorni)
Alex Skantz
Alex Skantz il 6 Ott 2021
Commentato: Daniel S il 6 Ott 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

Risposte (1)

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

Accedi per commentare.

Categorie

Scopri di più su Board games in Help Center e File Exchange

Prodotti


Release

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by