MATLAB Answers

Variable from function to change value

18 views (last 30 days)
Fredrik Preus Dovland
Fredrik Preus Dovland on 24 Sep 2020 at 9:28
Answered: Steven Lord on 24 Sep 2020 at 12:48
I am making the game 10 000, where you roll 6 dices and can choose to keep a set of dices wich gives you points. I am almost done, but i have one problem.
For each dice-roll, I can pick x number of dices to keep. When i say wich dices to keep, these become the input values for my function. In the function I run the rules of points, where you get so much points for ones and so on. My problem is that within the function I have to define the points variable as zero, so each time the function is run the score resets to zero. The function is run for each time I choose to keep x number for dices from the dice-roll.
I need the variabe to change its value for each time the function is run so the points add to eachother. A shortened version of what I have so far, is displayed underneath. Here the poeng_kast is the variable that sends the points back to the script. The "terningkast" is the input-values of the x number of dices chosen.
function poeng_kast = poeng(terningkast)
poeng_kast = 0;
Sum1 = sum(terningkast(:) == 1);
Sum5 = sum(terningkast(:) == 5);
if ismember(1,terningkast) == 1
if Sum1 == 1
poeng_kast = poeng_kast + 100;
end
end
if ismember(5,terningkast) == 1
if Sum5 == 1
poeng_kast = poeng_kast + 50;
end
end
end

  0 Comments

Sign in to comment.

Answers (1)

Steven Lord
Steven Lord on 24 Sep 2020 at 12:48
What's the purpose of your function? Is it simply to score the set of dice (meaning that it's some other function, perhaps its caller, that is intended to accumulate or track the game's running score?) Or is it your function's job both score this set of dice and track the running score?
If it is the responsibility of the function that calls your poeng function to track the score, that function should probably be adding whatever your function returns to that running score. Or it should be calling your poeng function with the current score as an additional input, leaving your poeng function to change that current score and return it.
If it is the responsibility of your poeng function to track the score, you may want to use a persistent variable.

  0 Comments

Sign in to comment.

Categories

Community Treasure Hunt

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

Start Hunting!

Translated by