Timer or new Thread?

Im making a simple game.
And i wonder what you recomend to handle the game loop.
A timer that updates and calls repaint.
Or a new thread?.

The timer im using is javax.swing.
Is there trouble if i use swing timer and other components from awt?

Thanks.

just stick it in a new Thread this way you can change the way you want to pause the loop or skip frames and that sort of thing since your not reliant on the swing timer.


Thread myThread = new Thread(this);
myThread.start();
}

public void run()
{
running = true;

while(running)
   //handle input
   //update game
   //render game
   //do pause

}

Ok so i go with thread.
How do i calculate how long the thread should sleep before updating?
if i just make it sleep a fix value the performance will be different on different systems right?

Well there are lots of ways you can do that, a simple scheme would be to measure how much time passed while you were updating/rendering (i.e. during the current frame) and subtract it from your usual pause time. You could probably find something more advanced if you looked around (or came up with your own :)).

I’ve used a swing Timer for that kind of stuff, and it’s fine! It’s much easier to avoid bugs using a swing Timer than when you write your own multithreading applications, especially if you don’t have loads of experience. However, if you rely on active rendering and that kind of stuff, it might be appropriate with some more control of what threads code is being executed from, and then a swing Timer probably won’t do the job.

How does this look to you?


public void run() {
        while(gameisrunning) {
			
		starttime = System.nanoTime();
			
		//Perform operations
			
		estimatedtime = (System.nanoTime() - starttime) / 1000000;
			
		sleeptime = 15 - estimatedtime;
			
		if(sleeptime > 0) {
			try  { thread.sleep(sleeptime); }
			catch (InterruptedException e) { System.out.println(e); }
		}
	}
}

It is not guaranteed that the game will hold any specified average framerate using the above code. For example, if one particularly expensive “//perform operations” takes longer than sleep time, there will never be any compensation for this, and thus the game will drift out of sync if you’re networking. It’s okay for single player though as far as I can see. I guess it’s fine for what you’re trying to do.

Note that in java, we normally prefer to capitalize identifiers like this: “startTime”, “estimatedTime”, “gameIsRunning”, etc.

Ok. How would you do to compensate for an operation that takes long time?
Its only going to be singleplayer but no reason not to do it correct :slight_smile:

Hi

A fixed framerate would be

int fps = 30; //whatever you want
int timeperframe = 1000/fps;

while(running)
{
long start = System.nanoTime();

Do decisions for this frame, AI
Update all Objects / Move
Check Collisions and stuff
Paint the frame

long end = System.nanoTime();
long duration = (end - start) / 1000000;
long sleeptime = Math.max( timeperframe-duration, 5);
try
{
Thread.sleep(sleeptime);
} catch(Exception e)
{
}
}

This would be a fixed framerate. After each frame it sleeps just as long so that the frames all take
the same time. You must specify your framerate. It should take a minimum sleep time of at least a few ms so that your game loop doesnt starve out other java threads.
When the pc is not fast enough to do the frames in the target time, the game will slow down.

to conquer this, you can make a dynamic framerate with

long timesincelastframe = lastframestart - thisframestart;

and do all updating based on this time. If more time passed, things will move a greater distance.
be sure to make a good collision detection, because fast things might jump quite some distance if the fps is low,
and they might just overjump each other while they should have collided.

If you have very expensive tasks, either make another thread, let them run there and use the results when its done, or
divide it into small packages and do one package per frame until all are done.
pathfinding for example might be restricted to search 100 tiles per frame. you wont notice when it takes 3 or 4 frames to make
a path.

-JAW

What I meant was that the logical framerate must be held constant in order to make a network game. Not perfectly constant, but as hours pass, computers must not drift away from each other. The graphical framerate may, of course, vary freely.

I would store the amount of frames executed since the beginning of the game. Think of each frame as predestined to be executed “reasonably close” to the time [frame count] * [time per frame] . You will just have to call Thread.sleep such that the sleep time aims toward this number (instead of the per-frame time). When the timer is “late”, i.e. when the last update took too long, you can always perform the next update without e.g. drawing, thus conserving time and eventually (if the computer is not an 80286) keep up with any other computer without desyncing issues.

You don’t have to do any of this though.