How do you get a function to return true or false to the script where the function was called?
12 views (last 30 days)
Show older comments
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.
0 Comments
Answers (1)
chicken vector
on 26 Apr 2023
Edited: chicken vector
on 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 Comments
Steven Lord
on 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.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!