MV [YEP_BuffStatesCore] Need some help with a custom state

Hello! First of all, thanks for reading and trying to help.

Turns out I'm trying to create a state, with the help of YEP Buff & States Core. The state, called "Hot Potato", lasts 5 turns, with the following behavior: At the end of each turn, the state is transferred to another living character who does not already have that state, carrying the same number of turns remaining for it as the person who transferred it had. When the state expires due to its turns reaching 0, the user loses 1/3 of his maximum health, and if they are not defending (using "Guard"), the "Burn" status is also applied.

I was trying to look at some ready-made Tips & Tricks for inspiration (specifically, Roaming Mend), and came up with this:

JavaScript:
<Custom Turn End Effect>
var potatoId = 73;
// Create an empty array.
var members = [];
// Loop through each of the target's alive allies.
for (var i = 0; i < target.friendsUnit().aliveMembers().length; ++i) {
  // Set the potential variable to the current looped ally.
  var potential = target.friendsUnit().aliveMembers()[i];
  // If the ally doesn't exist, move onto the next.
  if (!potential) continue;
  // If the ally is the same as the target, move onto the next.
  if (potential === target) continue;
  // If the ally is already affected by a different Potato effect, move onto the next.
  if (potential.isStateAffected(potatoId)) continue;
  // If the ally's HP is at zero (hence dead), move onto the next.
  if (potential.hp <= 0) continue;
  // Now that all checks have been cleared, put the potential ally into the members array.
  members.push(potential);
}
// Get a random member of the members array.
var member = members[Math.floor(Math.random() * members.length)];
// Check if the random member exists.
if (member) {
  // Play an animation on that random member.
  member.startAnimation(3);
  // Move the Potato state onto that random member.
  member.addState(potatoId);
  var turns = user.stateTurns(potatoId);
  member.setStateTurns(potatoId, turns);
  user.removeState(potatoId)
}
</Custom Turn End Effect>


<Custom Leave Effect>
var dmg = Math.floor(user.mhp / 3);
user.gainHp(-dmg);
user.startDamagePopup();
user.clearResult();
if (user.isDead()) {
  user.performCollapse();
} else {
  user.performDamage();
}
userisActor() ? SoundManager.playActorDamage() : SoundManager.playEnemyDamage();
var burnId = 18;
if (!user.isStateAffected(2)) {
  user.addState(burnId);
  user.startAnimation(67);
}
<Custom Leave Effect>

The thing is that the effects are totally inconsistent. Sometimes I see how the state is applied and instantly removed from all characters upon passing the first turn; other times it is transferred to another character, but with a lower number of turns remaining than it should be; and other times, whether it has been transferred previously or not, it stays on the same character even though the remaining turns decrease...

I suspect this is because, as the code stands, when the status is transferred to someone at the end of the turn, they re-execute their own Turn End Effect, therefore, it is transferred to another character and removed from the current one, and so on and so forth, and maybe the seemingly random behavior is because of different timings?...

How could we fix this? By adding some failsafes? Or I'm just approaching this wrong? I'm not very good at JavaScript. Is there any way to do what I'm looking for? Many thanks again.
I suspect this is because, as the code stands, when the status is transferred to someone at the end of the turn, they re-execute their own Turn End Effect, therefore, it is transferred to another character and removed from the current one, and so on and so forth, and maybe the seemingly random behavior is because of different timings?...
sounds about right. I usually get around it by adding a flag to show that the initial iteration has already happened and prevent it from running again if it has.

only problem i have right now is that I cant get a battler to both pass and receive the state in the same turn if theres multiple potatoes floating around in the same unit. Even though the state doesnt jump if there isnt a valid target to jump to, the second applied one just disappears into the aether if it goes into something that's already passed it that turn.

Below is what i have so far and it works for single, but Id either have to figure out another approach to allow a battler to both pass and get the state in the same turn, or take the easy way out and make battlers ineligible for getting it on turns they pass it.
Spoiler
Code:
<Custom Apply Effect>
user._potato = user._potato || 5;
user.setStateCounter(stateId, user._potato);
</Custom Apply Effect>

<Custom Turn End Effect>
if (!user._potatoPass){
    user._potato -= 1;
    user.setStateCounter(stateId, user._potato);
    if (user._potato <= 0){
        user.gainHp(-Math.floor(user.mhp / 3));
        user.startDamagePopup();
        user.clearResult();
 
        if (user.isDead()) user.performCollapse();
        else {
            user.performDamage();
            user.isActor() ? SoundManager.playActorDamage() : SoundManager.playEnemyDamage();
            if (!user.isStateAffected(2)) {
                user.addState(18);
                user.startAnimation(67);
            }
        }
        user.removeState(stateId);
    } else { 
        var choice = user.friendsUnit().aliveMembers().filter(member => !member.isStateAffected(stateId));
        choice = choice[Math.randomInt(choice.length)];
        console.log(choice.name());
 
        if (choice) {
            choice.startAnimation(3);
            choice._potatoPass = true;
            choice._potato = user._potato;
            choice.addState(stateId);
            user.removeState(stateId);
        }
        else user.setStateCounter(stateId, user._potato);
    }
}
</Custom Turn End Effect>

<Custom Turn Start Effect>
delete user._potatoPass;
</Custom Turn Start Effect>

<Custom Remove Effect>
delete user._potatoPass;
delete user._potato;
</Custom Remove Effect>
Thank you so much!! It works as you described!

Well, realistically, in this battle, there isn't much of a chance to get two potatoes at the same time (it's possible, but unlikely), let alone three or four... Yeah, it would be cool, both conceptually and in gameplay, to have multiple potatos bouncing around and behaving like they should. But if you can't find a way, it's ok, you already helped a lot! 🙂

I also customized the way the counter is shown, to make it look just like the actual "remaining turns counter", by putting in these tags:

<Counter Alignment: right>
<Counter Buffer X: -3>
<Counter Buffer Y: -6>
<Hide Turns>

And added the other effects I suggested, inside a <Custom Leave Effect>. The only other thing I can't seem to get, is to check if the user is not guarding. I tried
JavaScript:
if (!user.isStateAffected(2)) {
  user.addState(burnId);
  user.startAnimation(67);
}
...but it always returns true, so the user burns regardless if he was defending or not. I also tried !user.isGuard() and !user.isGuarding(), but to no avail. 🤔

EDIT: Whoops! I didn't realize that @Robro33 already included the effects I talked about in their <Custom Turn End Effect>. That was my bad. Still, I couldn't get the "if the user is guarding, don't burn them" part to work... Until I tried to replace <Custom Turn End Effect> for <Custom Regenerate Effect>, and then the check for not guarding was indeed !user.isGuard(). That part works now too!

My guess is that user.isGuard() always return false at the <Custom Turn End Effect> point, because the user is already not guarding at that moment. But the <Custom Regenerate Effect> does apply BEFORE that. Timings are important! And it seems nothing breaks in the functionality of the state. So now, only the issue that you said remains. Maybe you could do something with those different timings of the Regenerate and Turn End Effects? (I hope I'm not saying something stupid). Anyways, thanks once again!
...but it always returns true, so the user burns regardless if he was defending or not. I also tried !user.isGuard() and !user.isGuarding(), but to no avail. 🤔
Ah, right. i forgot my guard state doesnt last a turn, it lasts till the user's next action, so i completely missed that. Any time that code is ran, the user's guard state would have already fallen off. You could either make the effect happen a bit earlier as a regenerate effect instead of a turn end one, or do a similar thing where guarding doesnt necessarily end when the turn does.

Original thread: https://forums.rpgmakerweb.com/threads/yep_buffstatescore-need-some-help-with-a-custom-state.167822/