简体   繁体   中英

Generating a random number every time in a specific time interval in java

I have a method, that draws textures at runtime.

I generate a random number, that changes the height of the texture.

The problem is, that during runtime, all possible random numbers are being created and that the texture is shown with all kind of heights.

I generate a random number with:

Random r = new Random();
int low = 0;
int high = 30;
int result1 = r.nextInt(high-low) + low;

Here's my drawTower() method:

private void drawTower() {

    batcher.draw(AssetLoader.texture1, tower1.getX(), tower1.getY() + tower1.getHeight() - result1, 
           tower1.getWidth(), midPointY - (tower1.getHeight()));    
}

You can see that there is result1 , which is the randomly generated number.

Now the problem : In my method render() I use that drawTower() method, which is the reason why all possible random numbers are being created.

How can I fix this issue? I thought about generating a random number and after specific time interval, a new random number is being generated. But I don't know how it's done.

public void render(float runTime) {

    Wizard wizard = myWorld.getWizard();

    // Fill the entire screen with black, to prevent potential flickering.
    Gdx.gl.glClearColor(0, 0, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    // Begin ShapeRenderer
    shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);

    // Draw Background color
    shapeRenderer.setColor(55 / 255.0f, 80 / 255.0f, 100 / 255.0f, 1);
    shapeRenderer.rect(0, 0, 136, midPointY + 66);

    // End ShapeRenderer
    shapeRenderer.end();

    // Begin SpriteBatch
    batcher.begin();      
    batcher.enableBlending(); 

    batcher.draw(AssetLoader.texture0,
            wizard.getX(), wizard.getY(), wizard.getWidth(), wizard.getHeight());

    // Draw Tower
    drawTower();

    // End SpriteBatch
    batcher.end();

}

You can create an object that provides a new randomly generated value at your desired interval and assign this object as a field in the class that contains the drawTower method. Note that this generator object needs to properly synchronized because one thread will be accessing the randomly generated value while another thread will be updating it:

public class TimedRandomNumberGenerator {

    private final AtomicInteger value = new AtomicInteger();
    private final Timer valueUpdater;

    public TimedRandomNumberGenerator(long updateRateInMs) {
        valueUpdater = new Timer();
        valueUpdater.schedule(createTimerTask(), 0, updateRateInMs);
    }

    private TimerTask createTimerTask() {
        return new TimerTask() {
            public void run() {
                value.set(generateNewValue());
            }
        };
    }

    private static int generateNewValue() {
        Random r = new Random();
        int low = 0;
        int high = 30;
        return r.nextInt(high-low) + low;
    }

    public int getValue() {
        return value.intValue();
    }
}

In the class that contains the drawTower method (note that for this example, the update rate it set to 1000 milliseconds, but can be changed to whatever your desired period is):

public class SomeClass {

    private final TimedRandomNumberGenerator generator = new TimedRandomNumberGenerator(1000);

    private void drawTower() {
        batcher.draw(
            AssetLoader.texture1,
            tower1.getX(), 
            tower1.getY() + tower1.getHeight() - generator.getValue(),
            tower1.getWidth(), midPointY - (tower1.getHeight())
        );    
    }
}

The synchronicity of TimedRandomNumberGenerator is captured in the use of AtomicInteger . This protects the randomly generated value from multiple readers and multiple writers (one writer in this case: The TimedRandomNumberGenerator itself). The createTimerTask method is just a convenience method, as the TimerTask class is not a functional interface (and therefore cannot be replaced with a lambda expression). The valueUpdater.schedule method call in the constructor is what schedules the random number to be updated once the desired period of time has expired.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM