Question on dice simulation? (Edit)

조회 수: 3 (최근 30일)
Tyler Silva
Tyler Silva 2015년 10월 23일
댓글: Walter Roberson 2022년 8월 2일
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.

답변 (1개)

Manas
Manas 2022년 8월 2일
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
Walter Roberson
Walter Roberson 2022년 8월 2일
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?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by