I'm working on a game, and in it I want growth to happen exponentially - so, for example, getting from 2 to 3 people might take around the same time as getting from 2 million to 3 million people. However, I would like this growth to be random if possible to make it more realistic. So far I have a method that works well:
if (buildingCount > populationCount && foodCount > populationCount)
for(int i=1;i<populationCount;i++) {
int randomInt = random.nextInt(1000);
if (randomInt == 42) {
Data.main.setPopulationCount(populationCount+1);
}
}
if ((buildingCount < populationCount || foodCount < populationCount)&&populationCount>2)
for(int i=1;i<populationCount;i++) {
int randomInt = random.nextInt(1000);
if (randomInt == 888) {
Data.main.setPopulationCount(populationCount-1);
}
However, I realise this will not be sustainable. It runs approximately 60 times a second (on that magnitude), and once it reaches levels of millions, it may end up running billions of operations per second - a bit much for such a simple check. I'll put it on an interval if I have to, but I'd rather keep it random.
I tried to find an equation for the probability but ended up with:
Σ(99^r/1000^(r+1)) from r=0 to p (where p = probability)
Is there any easy way to change that probability to a test, or a simpler method in Java to accomplish such a purpose.
If it helps I'm using LibGdx as an engine.
It seems that, assuming the distribution of random numbers is uniform, you'll increase the population count by n / 1000
, on average, for a population count of n
.
To emulate this, it might be a good idea to just divide populationCount
by 500
and use ThreadLocalRandom#nextGaussian
to determine how much to increment populationCount
by, allowing you to rid yourself of the for-loop:
if (buildingCount > populationCount && foodCount > populationCount) {
if (populationCount > 1000) {
int randomNum = (int) ((ThreadLocalRandom.current().nextGaussian() / 2 + 0.5) * populationCount / 500);
Data.main.setPopulationCount(populationCount + randomNum);
} else {
// Original for-loop here for populations less than 1000.
}
}
For a population of 10,000
, this would increase the population by an average of 10
(ranges from 0
to 20
in this case, but favors a mean of 10
due to the use of nextGaussian
).