Distribute value across array w/ nested loop

Get help using Construct 2

Post » Sat Jun 20, 2015 3:59 pm

My player has 9 weapons and each one has its own energy which is stored in an array. There are pickups to restore energy. If the currently selected weapon is full, but others are low, I want to distribute the restored energy to them evenly.

My idea was to loop through the energy array as many times as the energy refill. If an energy is lower than max, 1 is added to it and 1 is added to a local var counter. If that counter is equal to the energy refill, the loop is stopped. This way, if there's only 1 weapon with low energy, then it'll get 1 energy with each loop until it's over. If multiple weapons are low on energy, they'll each get 1 until the refill amount is met, at which point the loop is stopped.

I dunno if it's my code or the method as a whole but it doesn't quite work - too much energy is being restored. Any other ideas or examples floating around?
Posts: 1,787
Reputation: 18,685

Post » Sat Jun 20, 2015 6:54 pm

This should do it I think.
"energy" is the amount of energy to add
"slot" is the selected weapon
"num_full" is the number of weapons with full energy, so the loop knows when to stop. To make it work when you don't have some weapons just keep the weapons you don't have with full energy.

Code: Select all
variable slot=0
variable energy=10
variable num_full=0

Array.At(slot) + energy <= 100
---> set array at slot to Array.At(slot) + energy
---> set energy to 0
---> array: set at slot to 100
---> set energy to Array.At(slot) + energy -100
---> set num_full to 1

------> set num_full to 0
--- array: for each x
------ array.curValue < 100
------ energy > 0
---------> set array at array.curX to Array.At(array.curX) + 1
---------> subtract 1 from energy
------ array.curValue = 100
---------> add 1 to num_full
Posts: 5,234
Reputation: 67,754

Return to How do I....?

Who is online

Users browsing this forum: Apollo14, ivanski1983, KTML5 and 4 guests