The game engine has a lot of structure, but it's basically implemented in a game master loop. The main loop inside the program contains the most important structure of the program framework. J2ME programs typically contain two class files, one is MIDlet, and the other is displayable. I usually put the main code of the game in displayable this class. This class is an event-driven program that has three main corresponding functions void paint (Graphics g), void keypressed (int keycode), void keyreleased (int keycode).
1, the use of runnable and create a thread of the main loop
The general subject's approach is to let displayable this class implement runnable this interface, and then create a thread in its constructor, start its run () function, and the run function contains the main loop of the game. Here is my snippet code inside the Paladin.
public class Gamemidlet extends MIDlet {
static gamemidlet instance;
Display display;
Gamedisplayable displayable = null;
Public Gamemidlet () {
Instance = this;
display = Display.getdisplay (this);
displayable = new Gamedisplaya BLE ();
}
public void startApp () {
display.setcurrent (displayable);
}
public void Pauseapp () {
}
public void Destroyapp (Boolean unconditional) {
Displayable.running = false;}
public static void Quitapp () {
Instance.destroyapp (true);
instance.notifydestroyed ();
Instance = nul L
}
}
public class Gamedisplayable extends Fullcanvas implements Runnable {
/** main control thread */
Thread Mainthr EAD = null;
/** Game clock interval millisecond per unit */
public static long timeinterval =
public static Boolean isstable = true;
/* For Games The clock's variable */
public static long timeold = 0;
Public-static long TimeNow = 0;
Public long interval = 0;
Public s Tatic Long Frames_per_second = 0;
int count = 0;
Long second = 0;
public static Boolean running = TRUE;
Public gamedisplayable () {
//start main thread
Thread mainthread = new Thread (this);
Mainthread.start ();
}
public void Run () {
while (running) {
TimeNow = System.currenttimemillis ();
Interval = Timenow-ti Meold;
if (interval >= timeinterval) {
Timeold = TimeNow;
Game_process ();
if (second!= (System.currenttimemillis ()/1000)) {
Second = System.currenttimemillis ()/1000;
frames_per_s Econd = count;
Count = 1;
}
Else
count++;
}
Lib.sleep (30);
}
}
The code to control the speed of the main cycle can not, but Lib.sleep (30) must be retained, because on the Nokia 60 phone, if the sleep (30), then the game will not be able to switch back. At the same time, in the game in any one of the internal loop, you must also join the sleep (30) This wait, in order to allow the game to switch back, as to why this, I am not clear yet. 30ms is a number that I've tested for no problem, and maybe a smaller value than 30ms is no problem.
At the same time, in Moto's mobile phone, the game must be the main loop in a thread, the game can switch back, but can not add the above sleep (30) delay.