Selection algorithm of random probability in game development
- 2021-07-18 08:55:47
- OfStack
The implementation code is ultra simple, and the specific implementation method is as follows:
Sometimes when our game characters encounter enemies, we need my monster to choose the processing method randomly according to the probability, as follows:
1. 50% chance of friendly greetings
2, 25% chance to walk away
3, 20% chance to attack immediately
4, 5% chance of giving money as a gift
The following algorithm is to follow the probability array and return the selected probability index number.
int Choose(float[] Probability array )
{
float total=0;
// First, the total value of probabilities is calculated, which is used to calculate the random range
for(int i=0;i< Probability array .length;i++)
{
total+= Probability array [i];
}
Random rd = new Random();
float Random value =rd.Next(0,total);
for(int i=0;i< Probability array .length;i++)
{
if( Random value < Probability array [i])
{
return i;
}
else
{
Random value -= Probability array [i];
}
}
return Probability array .length-1;
}
The above is the whole content of this article, I hope you like it.