How do you get a function to return true or false to the script where the function was called?

8 Ansichten (letzte 30 Tage)
I have 2 scripts for a simple game of blackjack. The first script called 'blackjack.m' gives the user initial options like learn the rules and place wages, while the second script 'play_blackjack' deals the players and dealers hands and uses several if loops to determine who wins. On each of these if loops Ive added a game=true/false depending on who the winner is. Back in the first script, when I write 'if game==true' or 'game==false', it doesnt recognise that I have determined these variables in the play_blackjack function and gives the error message. Ive tried initialising the variable 'game' and that didnt do anything. Ive also tried using 1 and 0 instead of true/false and still no changes. Note in the first script I have written simple disp commands 'WIN' and 'LOSE'. These are just temporary so I can finally see if its working or not. Ive been trying to figure this out for a while.

Antworten (1)

chicken vector
chicken vector am 26 Apr. 2023
Bearbeitet: chicken vector am 26 Apr. 2023
the file play_blackjack.m is not a script, but a function.
In blackjack.m change the line:
play_blackjack
To:
game = play_blackjack;
Side tip.
Instead of doing
if game == true
fprintf("WIN")
end
if game == false
fprintf("LOSE")
end
Do:
if game
fprintf("WIN")
else
fprintf("LOSE")
end
Or:
if game
fprintf("WIN")
end
if ~game
fprintf("LOSE")
end
  2 Kommentare
Steven Lord
Steven Lord am 26 Apr. 2023
I'd also consider giving that variable a more descriptive name. The name "game" doesn't scream to me that it's a logical variable indicating whether or not the player won. Perhaps use a name like "playerWon", in which case the code is fairly self-explanatory even for people who may not be familiar with MATLAB code.
if playerWon
fprintf("YOU WIN")
else
fprintf("YOU LOSE")
end
If I showed that to my mother (who is most definitely not a programmer) and told her "fprintf prints a message to the screen" she likely could understand and explain that code segment.
Callum
Callum am 26 Apr. 2023
Thank you so much! Literally saved me from an F! Thanks for your advice on the variable name and the side tip. Ive still got a bunch of formatting to do but thats a good start.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Number games finden Sie in Help Center und File Exchange

Produkte


Version

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by