how to call function based on if loop

Im making a hangman game. Made a player based one (player 1 vs player 2), but im wanting to make computer vs player. Just need help on how to run the player vs player function based on if statement like:
c==1, then the function will run if not itll just run computer vs player.
I tried to make it work with function script but it just said 'too many output arguments'...
Thanks
clc; clear all
words=importdata('words.txt');
fprintf('Would you like to play against a player (enter 1) or computer (enter 2)?\n');
choice=input(' ');
for i=1:choice
if (choice==1)
run(player);
end
end
function []= player()

답변 (1개)

Jan
Jan 2021년 4월 28일
편집: Jan 2021년 4월 28일

0 개 추천

There is no need for a loop:
choice=input(' ');
if choice == 1
player();
end
function []= player()
...
end
The command run starts a script. Scripts are M-files, which do not start with the term "function". Functions have their own workspace (set of visible variables), inputs and outputs. Therefore functions are saver and easier to debug.
As soon as code is written inside functions, there is no need for the Cargo-Cult-Programming technique of "clear all". This command has no benefits, but removes all loaded functions from the memory. Rereading them from the slow disk wastes time. What a pity, that still so many teachers suggests using this killer.
In you code I simply omitted the run() command and call the function directly. I assume you need words inside this function also, so provide it as input argument or import it inside the function player().

카테고리

도움말 센터File Exchange에서 Entering Commands에 대해 자세히 알아보기

제품

릴리스

R2020b

질문:

2021년 4월 28일

편집:

Jan
2021년 4월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by