create a while loop to simulate yahtzee in matlab

Here's an example of how to simulate Yahtzee using a while loop in MATLAB:

main.m
% Set the initial number of rolls and the score
numRolls = 1;
score = 0;

while numRolls <= 3
    % Roll 5 dice
    dice = randi(6, 1, 5);
    
    % Count the number of occurrences of each value
    counts = histcounts(dice, 1:7);
    
    % Check for a Yahtzee (5 of a kind)
    if any(counts == 5)
        score = 50;
        break;
    end
    
    % Check for a large straight (5 consecutive values)
    if any(counts(2:end-1) == 1) && all(counts(2:end-1) <= 1)
        score = 40;
        break;
    end
    
    % Check for a small straight (4 consecutive values)
    if any(counts(2:end-1) == 1) && numel(find(counts==1)) == 4
        score = 30;
        break;
    end
    
    % Check for 3 of a kind, 4 of a kind, or full house
    numCounts = numel(find(counts>=3));
    if numCounts == 1 % 3 of a kind or 4 of a kind
        score = sum(dice);
        break;
    elseif numCounts == 2 && counts(1) ~= 2 && counts(end) ~= 2 % Full house
        score = 25;
        break;
    end
    
    % If none of the above conditions were met, prompt for the next roll
    numRolls = numRolls + 1;
end

% Display the score
disp(['Final score: ' num2str(score)])
1163 chars
46 lines

This code rolls 5 dice and checks for various Yahtzee combinations. If a combination is found, the loop exits and displays the score. Otherwise, the user is prompted to roll again (up to a maximum of 3 rolls).

gistlibby LogSnag