Java Snake Game avoiding using Thread.sleep

蹲街弑〆低调 提交于 2021-01-27 05:54:20

问题


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.


回答1:


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.




回答2:


A better idea is to use a Timer as suggested above which will allow you to trigger after a specified delay without calling sleep().

if you want it a little more complicated but self-made start a new Thread to handle the sleeps. You can put pooling mechanism with some pooling frequency to avoid thread.sleep.Put your condition in while loop and wait for some tine if condition is not met.And wait time should be less so it will poll with small interval.

//more code here It is a sample code
    synchronized(this) {
         while (delta < model.getFrameTime()) {
          this.wait(500);
         }
       //more code 


来源:https://stackoverflow.com/questions/44478582/java-snake-game-avoiding-using-thread-sleep

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!