"While" statement issues
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Hi MATLABers,
I'm coding a version of craps (as part of a research project) to account for the number of rolls before a "7 out" accounting for (a) total rolls, (b) wins (pass line bet and (c) losses. Essentially, I want the first loop to repeat until a "point" number is established (so there could be multiple rolls/7/11/2/3/12 before the next loop takes over). Then the second loop (point cycle) continues until either (a) a point is established, then you go back to the beginning loop or (b) a 7 is rolled, which ends the hand.
M = 100000;
lost = 0; win = 0; gamelength = zeros(1,M);
data = zeros(100000,6);
for k=1:M
curr_gamelength = 1;
sevenout = 0;
while (x==7) || (x==11) || (x==2) || (x==3) || (x==12)
x = sum(round(rand(1,2)*6+0.5));
if (x==7) || (x==11)
win = win+1;
elseif (x==2) || (x==3) || (x==12)
lost = lost+1;
else
point = x;
end
end
while point
curr_gamelength = curr_gamelength+1;
p = sum(round(rand(1,2)*6+0.5));
if (p==7)
lost=lost+1; sevenout = 1;
elseif (p==point)
win = win+1;
end
%%
end
gamelength(k) = curr_gamelength;
end
6 commentaires
Steven Lord
le 2 Juil 2019
If you roll 7, 11, 2, 3, or 12 initially the current game ends. You only want to run the code to handle the point case if you rolled a different number. So why not move the code that handles the point case into the else where you set the point? That way the "win or lose on first throw" cases never see it.
By the way, craps is a straightforward enough game with pretty basic rules, but I encourage you to develop the habit of commenting your code. In this case, starting with a skeleton of comments outlining the "workflow" of a game of craps (before even writing a line of code) might be useful in planning out and keeping track of exactly what steps to execute when.
% First throw
% If first throw is a 7 or 11, win
% If first throw is a 2, 3, or 12, lose
% Otherwise the point is equal to the first throw
% Keep throwing until you get 7 or the point
% If you threw a 7, lose
% If you threw the point, win
The words "if", "otherwise", and "keep" in the description kind of imply if, else, and while by their meanings, don't they?
Then you'd wrap those with more comments:
% Start off with 0 losses and 0 wins
% Play 100000 games of craps
% Each game of craps:
% First throw
...
Translating from comments like that into code can be easier than keeping the whole design of your program in (your) memory. It can also help you identify if there are pieces of code you run frequently that may be useful helper functions.
Réponses (0)
Voir également
Catégories
En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!