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()

Respuestas (1)

Jan
Jan el 28 de Abr. de 2021
Editada: Jan el 28 de Abr. de 2021
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().

Categorías

Más información sobre Entering Commands en Centro de ayuda y File Exchange.

Productos

Versión

R2020b

Preguntada:

el 28 de Abr. de 2021

Editada:

Jan
el 28 de Abr. de 2021

Community Treasure Hunt

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

Start Hunting!

Translated by