Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Snake Game avoiding using Thread.sleep

I made my first game in Java - Snake, it's main loop looks like this

while (true)
    {
        long start = System.nanoTime();
        model.eUpdate();
        if (model.hasElapsedCycle())
        {
            model.updateGame();
        }
        view.refresh();
        long delta = (System.nanoTime() - start) / 1000000L;
        if (delta < model.getFrameTime())
        {
            try
            {
                Thread.sleep(model.getFrameTime() - delta);
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }

But in my project's requirments there is a responsivity point, so I need to change the Thread.sleep() into something else, but I have no idea how to do this in an easy way. Thanks in advance for any advice.

like image 812
Azathanai Avatar asked Oct 17 '22 11:10

Azathanai


1 Answers

I've done a simple game or two with Java and to handle the main game loop I've used a Swing Timer. The timer will allow you to set an ActionListener to be fired after a provided delay has elapsed. The in-between delay would be derived from your frame rate. The most basic usage would look like:

Timer timer = new Timer(delay, listener);
timer.start();

This would set the initial and in-between delays to the same value. You could also set them to be different values if needed like so:

Timer timer = new Timer(delay, listener);
timer.setInitialDelay(0);
timer.start();

In the above example, the listener will fire ASAP after starting and with a delay in-between thereafter.

like image 75
ChiefTwoPencils Avatar answered Oct 21 '22 09:10

ChiefTwoPencils