Small design question: Worms

Hi,

I rewrote an example from the good book “Killer Game Programming in Java” and now have a question about design.

The main setup is as follows:

There is JPanel implementing the interface runnable. The method run looks like this:


		while (running) {
			gameUpdate();
			gameRender(); // render the game to a buffer

			paintScreen(); // draw the buffer on-screen

Then follow some rather sophistiacted techniques for sleeping and skipping frames

			if (sleepTime > 0) { // some time left in this cycle
				try {
					// sleep a bit,
					Thread.sleep(sleepTime / 1000000L); // nano -> ms
				} catch (InterruptedException ex) {
				}
				overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
			} else { // sleepTime <= 0; the frame took longer than the period
				excess -= sleepTime; // store excess time value
				overSleepTime = 0L;

				// count the frames with no delays and yield
				if (++noDelays >= NO_DELAYS_PER_YIELD) {
					Thread.yield(); // give another thread a chance to run
					noDelays = 0;
				}
			}

			beforeTime = System.nanoTime();
			int skips = 0;
			while ((excess > period) && (skips < MAX_FRAME_SKIPS)) {
				excess -= period;
				gameUpdate(); // update state but don't render
				skips++;
			}
			framesSkipped += skips;

I added a KeyListener to the JPanel and in the gameUpdate() method I added

			if (keyPressed) {
					worm.moveLeft()

It works, but somehow some keyEvents are not processed. When I press ‘down’ the worm moves down, but every third time or so it doesn’t move.

How can I solve this? What is the principle design pattern?

Should I add some message coming from the worm saying moving was performed successfully?
I’ll provide more code if necessary.

Thx for any help.

strange choice of code you wanted us to see… sleeping techniques that are totally irrelevant you put but not adding key listener or complete code for moving the worm. From code you gave your worm can only move left if any key is pressed (or moveLeft() actually moves him down which would be incredibly stupid :stuck_out_tongue: ). Post whole code for moving the worm as the problem is probably there, in the way you determine if down is pressed.
Also note that keyboard can’t handle some keys pressed at the same time, did you test it with only down pressed?

Yes you’re right. I didn’t pose my question very well. I think I have solved my original issue.