Make a function loop
1 vue (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Making a function of the game yahtzee that rerolls until 5 of a kind is reached here is my current code
function roll_again = yatzhee(outcome)
%make a vector of zeros
numOfEachOutcome = zeros(1,6);
%counts how many of each number 1-6 and creates a vector with the results
for i = 1:length(outcome)
numOfEachOutcome(outcome(i)) = numOfEachOutcome(outcome(i)) + 1;
end
% assigning commonOutcome to 1.
commonOutcome = 1;
% finding common the outcome.
for i = 2:6
if(numOfEachOutcome(i)>numOfEachOutcome(commonOutcome))
commonOutcome = i;
end
end
roll_again = [];
for i = 1:5
if(outcome(i)~=commonOutcome);
roll_again = [roll_again i];
end
end
%all this give you an answer of which to reroll
rerollResult = ceil(randi([1,6],1,size(roll_again,2)))
for i = 1:size(roll_again,2)
outcome(roll_again(i)) = rerollResult(i);
end
final = true;
for i = 2:5
if outcome(i)~=outcome(1)
final = false;
end
end
if final
return
else
outcome
end
end
current result is
yatzhee([4 5 4 4 4])
rerollResult =
3
outcome =
4 3 4 4 4
ans =
2
ans is the postion it needs to reroll I need that to be named to throwAgain and preferably displayed first
so in its current state the function only rolls again once I need it to roll until 5 of a kind is aceived and to display how many rolls it took.
0 commentaires
Réponses (1)
Geoff Hayes
le 28 Avr 2021
Eris - if you want to keep rolling until you have a Yatzhee, then you probably want to use a while loop.
% set the roll count to one as this will be the initial roll
rollCount = 1;
% may want to add another condition to only allow a maximum number of rolls
% (like the game)
% so we continue looping until the roll_again array is empty
while ~isempty(roll_again)
rerollResult = ceil(randi([1,6],1,size(roll_again,2)))
rollCount = rollCount + 1;
% if not all of the re-rolls match the common outcome, then remove the
% ones that do and start again
if ~all(rerollResult == commonOutcome)
roll_again(rerollResult == commonOutcome) = [];
else
fprintf('It took %d rolls to get a Yatzhee!\n', rollCount);
break;
end
end
The above can be made more efficient. You may also want to remove some of the for loop from your code because I don't think they are all necessary (unless that is required as part of the assignment).
0 commentaires
Voir également
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!