Question on dice simulation? (Edit)

1 view (last 30 days)
Tyler Silva
Tyler Silva on 23 Oct 2015
Commented: Walter Roberson on 2 Aug 2022
I have attached my script. I need to Add in code to keep track of the user’s total amount of money (balance). Display the current balance to the user during each round of play. And At the end of each round, the user should be asked if he/she wants to play again. Game play should only continue as long as the user wants to play again and the user still has money left. When the user runs out of money or the user indicates he/she no longer wants to play, the game should stop and the user’s final balance (which could be $0) should be displayed. Im confused on how to keep track of the total balance throughout the game.

Answers (1)

Manas
Manas on 2 Aug 2022
Extending your logic, I added a while loop to repeat the process of betting infinitely until the user wants to quit or has lost all his money.
%% Problem 4
Bank=input('Please enter how much money you have available in your bank')
Bet=input('Please enter how much money you would like to bet')
if Bet>Bank
disp('You do not have enough money to bet that amount')
else
fprintf('Your bet %i \n',Bet)
end
rng('shuffle') % randomize the random function
balance = Bet;
while (1 == 1)
money = input('How much do you wish to bet(should not excede current balance)? $ ');
bet = menu('Place your bet:','Over 7','Under 7','Equals 7');
Dice1 = randi([1 6],1);
Dice2 = randi([1 6],1);
Sum = Dice1 + Dice2;
fprintf('You rolled a %i and a %i for a total of %i \n',Dice1, Dice2, Sum);
switch bet
case 1 % Over 7
if Sum > 7
fprintf('Congratulations! You just won $%0.2f \n',money);
balance = balance + money;
else
fprintf('You Lose! \n');
balance = balance - money;
end
case 2 % Under 7
if Sum < 7
fprintf('Congratulations! You just won $%0.2f \n',money);
balance = balance + money;
else
fprintf('You Lose! \n');
balance = balance - money;
end
case 3 % Equals 7
if Sum == 7
fprintf('Congratulations! Big Winner! You just won $%0.2f \n',4*money);
balance = balance + 4* money;
else
fprintf('You Lose! \n');
balance = balance - money;
end
end
choice = menu('Decide:','Continue','Quit');
if (choice == 2)
fprintf("Quitting")
break;
end
if(balance == 0)
fprintf("You have lost")
break;
end
end
  1 Comment
Walter Roberson
Walter Roberson on 2 Aug 2022
money = input('How much do you wish to bet(should not excede current balance)? $ ');
You do not check that it is at most the current balance. You do not check that it is positive.
What is the point of Bet with a capital B? When do you use it?

Sign in to comment.

Categories

Find more on Loops and Conditional Statements in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!