问题
In my .NET game my rand function that are determining how much damage each out of the players five characters should take, however the 1st one always seems to be at the bottom of the scale and the last one at the top. So in my Character[0]
the damage is rarely more than 1 more than the minimum rand value, and for each Character
on higher index the damage taken is only randomized from higher up the scale.
public int GetDamage(int low, int high)
{
Random r = new Random();
int rand = r.Next(low, high);
return rand;
}
This is the randomizer I use. Then I update the health left like this:
int Damage = GetDamage(3, 10);
Characters[Target].Health = Characters[Target].Health - Damage;
In this example dmg is divided like this:
Number 1: 3-4
Number 2: 4-6
Number 3: 5-7
Number 4: 7-8
Number 5: 8-9
回答1:
You have to reuse the same random instance otherwise you won't get really random values since it is created with the current time as seed. If you call GetDamage
very fast(e.g. in a loop) you will get always the same values.
So either use a field/property in the class of GetDamage
or pass the random instance to the method.
private Random _rnd = new Random();
public int GetDamage(int low, int high)
{
int rand = _rnd.Next(low, high);
return rand;
}
MSDN
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated. One way to produce different sequences is to make the seed value time-dependent, thereby producing a different series with each new instance of Random. By default, the parameterless constructor of the Random class uses the system clock to generate its seed value, while its parameterized constructor can take an Int32 value based on the number of ticks in the current time. However, because the clock has finite resolution, using the parameterless constructor to create different Random objects in close succession creates random number generators that produce identical sequences of random numbers. This problem can be avoided by creating a single Random object rather than multiple ones.
回答2:
You need to make your Random
instance static, this seeds it once and thereafter you will get a more random looking number.
static Random r = new Random();
public int GetDamage(int low, int high)
{
int rand = r.Next(low, high);
return rand;
}
回答3:
You need to seed the random number generator.
See: How do I seed a random class to avoid getting duplicate random values
Literally hundreds of this question on here, have a look around.
来源:https://stackoverflow.com/questions/15949417/random-number-behaves-weird-not-fully-random