Applying a state at random intervals

I want one of my actors to occasionally get distracted. Can I make it so that at the end of every turn, there's like a 5% chance for that actor to get the distracted state? And can I make enemies get states at random, too?
Your can do this via the troop events
Okay, I got it. Thanks!
You can do it with troop events. Set a variable to a random number from 1 to 100 and then check the variable using a conditional branch. If the variable is less than 5 (or greater than 95, up to you) apply the state. You do the same by randomizing another variable containing the state id and applying that random state.

Spoiler: How to add states to enemies using your random variable
Code:
$game_troop.members.each do |member|
  member.add_state(state_id_goes_here) if ($game_variables[random_variable_id_goes_here] > 95)
end

Applying a random state is a little tricky if your states are not adjacent in the states list but it is still doable.
Spoiler: How to add random states to random enemies
To add random states to random enemies you have to generate two different numbers. One if used for the state id, the other for the chance of applying it. In the example listed below I am assuming you want to pick your state from the whole list of states.
Code:
$game_troop.members.each do |member|
  state_id = 1 + rand(number_of_states_goes_here)
  chance = 1 + rand(100)
  member.add_state(state_id) if (chance > 95)
end

If you want to pick the state from a smaller list then you have to create your list like this
Code:
my_states_list = [
  state_id,
  another_state_id,
  a_different_state_id,
  and_so_on,
] # do not remove this

All those lines "state_id" ,"another_state_id", etc. are supposed to be integers. You can add as many state IDs as you want as long as you add a comma at the end of each state. Then you use a slightly different variant of the previous code to pick the state from that list. In the end the code should look like this (I am using random numbers for state IDs).

Code:
my_states_list = [
  3,
  5,
  6,
  9,
  11,
  31,
]
$game_troop.members.each do |member|
  state = rand(my_states_list.length)
  chance = 1 + rand(100)
  member.add_state(my_states_list[state]) if (chance > 95)
end

If you want you can put all your states on the same line like this:
Code:
my_states_list = [3, 5, 6, 9, 11, 31]

I honestly prefer this one but in the previous code I used long names for placeholders so having them on different lines was easier to the eye.
Thanks for your help!

Original thread: https://forums.rpgmakerweb.com/threads/applying-a-state-at-random-intervals.106396/