J2ME Game Development Notes (Integrated edition)
Editor: Rocks Audit: Rocks article source: Gameres Blog
Key words: Game development Publish Date: 2006-02-25 12:11:44 views: 10,616 times
This article copyright to the original author, China's Java mobile phone network included in this article is to allow more people to read this article. Reproduced please indicate the source for the Chinese Java Mobile phone network
From: http://www.cnjm.net/tech/article979.html
by Happyfire
Note: I recorded the development notes on the CSDN blog from September 2004 to August 2005, and published three collated notes on www.j2medev.com. Now sort these notes again.
If someone reprint this article, please include all content, do not revise. My emai:happyfirecn@yahoo.com.cn.
---------------General class Problems------------------
1 j2me table method using trigonometric functions
CLDC and MIDP do not provide trigonometric functions, and there is no floating-point number in the CLDC1.0, so our choice is to check the table. Use the sin and Cos tables with 8-bit fixed-point numbers. The following is the code in the WTK demo, which provides only a limited number of angles, which are used to refine the angle value as needed.
Sines of Angles 0, a, a, m, a, all *256
private static final int[] Sines =
{0, 44, 88, 128, 165, 196, 222, 241, 252, 256};
Angle is in DEGREES/10, i.e. 0..36 to Full Circle
private static int sineTimes256 (int angle)
{
Angle%= 36; 360 degrees
if (angle <= 9)//0..90 degrees
{
return Sines[angle];
}
else if (angle <=)//90..180 degrees
{
return Sines[18-angle];
}
else if (angle <=)//180..270 degrees
{
RETURN-SINES[ANGLE-18];
}
else//270..360 degrees
{
Return-sines[36-angle];
}
}
Angle is in DEGREES/10, i.e. 0..36 to Full Circle
private static int cosineTimes256 (int angle)
{
return sineTimes256 (angle + 9); i.e. add degrees
}
2 random numbers used in J2ME
To generate random numbers between 0~n:
(Ran.nextint () >>>1)%n
Or
(Ran.nextint () &0x7fffffff)%n
To generate random numbers between-n~0:
(Ran.nextint () | 0x80000000)%n
3 Attempt IO optimization
is developing a game, because read the map when doing a picture cutting, so the speed is relatively slow. (When I was developing a game, when I read the map did not load the cut picture, very fast, it seems that the IO operation speed and createimage,drawimage compared is negligible) for IO optimization may not be significantly improved speed, but I have tried.
Analyzed the code, in the original code in order to more easily read various types of data, using DataInputStream socket InputStream. But I took a closer look at the data I read, incredibly byte, and the only one char was manually assembled by me with two byte. This, DataInputStream seems to be unnecessary. So I did an experiment, did not change before reading the map time consuming 1242ms, will datainputstream remove direct use inputstream time 1065ms, although the results of each test are slightly different, but probably saved 200ms or so.
Can you speed it up a little more? Looking at the code again, I found that the data was read in through a number of read operations. Will the IO operations that are too frequent slow down? If you use a byte array as a buffer to read the data in a single time, will you hurry up? Well, give it a try before you know it. But how do I know the size of a stream? InputStream's Avaliable method always returns-1 AH. Open two times and first calculate the size. By the way, there is another method. Writes the file directly before the file size. The map file is generated using your own editor, and it's easy to know the size. So I used two bytes in front of the file to record the size of the file, first read 2 bytes from the stream, get the file size, then use the Read (Byte[],int,int) method to read the entire stream into the buffer. Then, all of my data operations are read from the buffer. Well, experiment, the result is: 1154ms. A? It's nearly 100ms slow. It turns out that this conjecture is wrong. Reason. Perhaps only know the KVM mechanism.
After the speed problem, I felt that the try block was too large to read the file because it was being read while processing the data, so the try block became large. Try block too assembly to increase the size of the class file. So I encapsulate the byte-reading operation with a method, which is declared private, but can be inline, only the compiler and KVM know it. The Try,catch structure is used when reading a byte from the stream inside this method, which causes a large try block to be dispersed into several small try blocks. The test, the time is 1089ms, eh, or a little slow. Speed is now more demanding than space, not to mention that reducing the 10 bytes saved by the try block is largely negligible. So this optimization has failed again.
Summary: When you can use simple flow, do not use complex flow, do not believe in theory, only to try to know.
Note: The test data is Nokia3100 mobile phone's real machine test data, on the Nokia 3300 This data is smaller, the fastest about 800 ms
4 compression or no compression
Do J2me know MIDlet suite capacity is too small, so unavoidably want to do a bit of compression. A few days ago, I tried a compression. My own Map file contains 3 layers of data, of which 2 and 3 have the same value for a contiguous distribution. Alas. I thought, using a simple president coding compression, only to this value for the President encoding, the algorithm is very simple speed and not slow, but can greatly reduce the size of the map file. It looks really good, eh. Said dry, busy for a long time, and then change the map editor, and the game to read the map code. Finally, try it, the original 2.23k of a file was compressed to more than 900 bytes. It seems very good, then I hit a jar bag, but suddenly found that this jar file seems to be no smaller than the original. It seems to be a bit too big. I hastened to find the backup code, sure enough the original jar smaller point. What's going on? It occurred to me that the jar itself was a compressed format. Don't... I quickly opened the jar file two times with WinRAR to observe. ~~~~~. In the original jar, the 2.23k file has a packet size of 185 bytes, and in my current jar, the 900-byte file has a packet size of 216 bytes. That is to say, I compress the files of my own first after packaging is not as small as uncompressed.
It seems that before you do compression, you must first look at the file you want to compress the size of the package inside. And for PNG files, with some tools optimized, the size in the package gets bigger. This is really pay attention to AH ~.
(05.12.31 Note: Some compression algorithms are indeed more efficient than zip compression, can be used, but the side effect is decompression causes loading time to become longer)
5 multiple anomalies at the same time
When the program appears exception, it is captured at an outsourced function, showing an exception in function A, then capturing in a but not capturing success, but the exception still occurs.
The original is another function called in the outsourced function B also produced the same exception.
At the same time there are multiple anomalies-be careful!
----------------development tool Problem-----------------
1 Eclipse Tips
Java mobile network [www.cnjm.net]1. There is a text image on the toolbar button "show source of selected element only". When you edit a member of a class (method or field), press this button, The current window displays only the class members you are editing. Click again to restore.
2. Displays the Java file line number. Select Window->preferences in the menu to open the Preferences window and select Java->editor, the option on the right is shown on the show lines numbers.
Displays the non-Java file line number. Select Workbench->editors->text Editor in the Preferences window, and the same option on the right is selected for show lines numbers.
3. When editing code, press ctrl+/to comment on the current line or selected multiline code, and press atrl+/to display the prompt to complete the code automatically.
4. Select the code and press CTRL+SHIFT+F to format the code
5. Input SYSO, press atrl+/can come out System.out.println ("");
2 running Nokia Simulator one of the considerations
This is an old problem, originally used WTK when there is, in the WTK to start the Nokia Simulator, if the previous has played the package, then the operation is the package of procedures, like that time will often be very depressed why the change did not effect, then develop a habit, the jar installed to the phone after the test to delete.
Today, with the jbuilder when the problem, but also Nokia simulator, if you have established a archive, then the Nokia Simulator is always running the package, hehe, so either will archive from project remove, Or ReBuilder this archive every time.
3 Eclipse integrated Motorola Simulator
Select Run->external Tools in Eclipse's menu/toolbar, open the Panel, select program, and then a new configuration
1 fill in the path of the Moto simulator in location, such as: C:/Program files/motorola/sdk v4.2 for j2me/emulatora.1/bin/ Emujava.exe,moto's different simulators support n different models and need to see the documentation for the Moto SDK.
2 fill in the arguments with the execution parameters, including the Jad path, the model used by the simulator. such as: "${project_loc}/deployed/${project_name}.jad"-devicefile resources/v600.props
I'm letting the simulator execute deployed inside the Jad/jar,${project_loc} is the engineering path, ${project_name} is the project name. The model selected here is V600.
Note: The limitation of this approach is that you can only execute jars, so you must package them before each run. You need to configure a run for no models before you actually use it, because you use a wildcard parameter, so all projects can use a single configuration
Java mobile network [www.cnjm.net] (05.12.31 Note: Some MOTOSDK can now be integrated with Eclipse. )
4 Initial use of JBuilder 7-a few minor issues
(1) Mobileset problem
JBuilder7 need to install another mobileset, Mobileset brought a WTK. If you do not automatically recognize WTK when you do not install the MOBILESET,JB7 configuration jdk, after you install Mobileset, you can add a new WTK by configuring the JDK method
(2) Resource file issues
All of the source files for JBuilder should be placed in the source path, and you can set the source path in the engineering properties, as are the resource files. You can either place the source file in one source path (that is, a folder), or you can place it in another source path. Note that JBuilder only identifies a certain number of suffixes by default, such as PNG, if you use a resource file of other suffixes, such as dat,bin, you need to add the file to the project by adding files, select the file properties, set to copy, The file for this suffix is recognized as a resource file.
(3) Cursor is not a problem
The easiest way-to change the font, I changed to the first font (JB7), the feeling and the default font is no different. The fundamental solution to this problem is discussed online.
(4) Mouse wheel Invalid problem
It is said that this problem only exists in JB7 and the following versions because only j2sdk1.4 supports the wheel, so the JB7 JDK needs to be changed to 1.4. The method is to modify the Jbuilder7/bin/jdk.config file and modify the Javapath and Addpath two lines, for example:
# Javapath. /jdk1.3.1/jre/bin/hotspot/jvm.dll
Javapath Y:/j2sdk1.4.2/jre/bin/server/jvm.dll
# Addpath. /jdk1.3.1/lib/tools.jar
Addpath Y:/j2sdk1.4.2/lib/tools.jar
500 Treasure Box Application compiling and packing matters
1 at compile time, setting the target VM of Javac to 1.1 can be detected by mobile. cannot be implemented in WTK. The following settings can be made in eclipse in Java-compiler-compliance and classfiles:
Java Mobile Network [Www.cnjm.net]compiler Compliance level:1.4
Generated. class Files compatibility:1.1
Source compatibility:1.3
(2005.12.31 Note: There are similar options in JBuilder that if you use the command line or ant, simply set the Javac TARGETVM parameter to target 1.1)
2 confuse the bag with Eclispe. However, the eclipse writing Jad Chinese will appear garbled, so write the correct jad with WTK, and then pack with WTK (note that you cannot overwrite ECLISPE packets), in order to get the correct WTK and jad files with manifest. Unpack the jar out of the elcipse, replace the Mainifest file in the original jar with the mainifest generated by WTK, and then package it with winrar (zip format, optional maximum compression, note that you want to select all the files to package, Do not package the entire directory outside. Finally, change the jar size in Jad to the number of bytes in the latest jar.
(2005.12.31 Note: I do not have eclipse for many years, it is said that the current eclipse me version is not a problem, I used the time of Eclipse me is only 0.4.6)
Another: 1. The name of the game shown in the Nokia s60,se k700 machine is MIDlet-1, and Nokia40 is the name in Midlet-name
2. According to the information provided by SP Nokia 7650 games can not be in Chinese name (in fact, NGAGEQD can)
----------------Model related issues-----------------
1 Nokia S60 IO operation memory leak should be observed
nokia7650,3650
When the game is running, the "Store full" dialog box appears and the location is not fixed.
There are sometimes "application error nullpointerexcept", "Program Closed midpui" dialog box during game run
When the game is running, the dialog box "program has turned off MIDPUI viewsrv 9" is sometimes present, and the position is not fixed.
In fact, this problem is caused by the S60 of the getResourceAsStream method memory leak, because every time you switch maps IO operation to read a large amount of data, memory leakage accumulated to a certain extent caused the "storage is full", screen, panic, which will cause null Pointer anomalies, and so on. The workaround is to minimize the number of IO operations. If the memory is large enough, read the resource at once.
2 NokiaS60 Emulator exits unexpectedly
Symptom (s): The emulator shuts down automatically without prompting any errors
Reason: Using the lighting or vibration control in the Nokia UI API, the Nokia S60 partial models and the corresponding simulators do not support these two features.
3 NokiaS60 UI API bugs
1 after rotation, and clip to the buffer on the map, clip invalid
2 Cannot create transparent muttable Image
These two points, fatal wounds, bring many unchanged
Several problems of Nokia S60 4
(1) Can not call System.GC () per frame, otherwise severely reduce FPS
(2) Nokia S60 machines of different models for translate and setclip processing is not the same. In the Nokia N-gage QD and other models, SetClip is relative to the translate after the coordinates of the calculation, and in the Nokia 6600,6670 and other models, SetClip is not affected by the translate, always relative to the upper left corner of the screen (0,0) point of calculation. So if you're using a translate and setclip method in Nokia6670, you'll get an error. In order to unify the code, do not use the translate in the Nokia S60, namely uses, does not carry on the setclip between the two times translate. The modified picture graph function is:
(3) Some Nokia models (6600,6670, etc.) after the exit error null pointer exception solution
Instead of calling Destroyapp in the main while loop, change to detect a flag, exit the main loop, and then call Destroyapp
Boolean exit;
...
while (!exit) {
...
if (...) {
Exit = true;
}
...
}
Destroyapp (TRUE);
Note: You can call notifydestroyed inside the Destroyapp
5 Nokia "Cannot run Application" error new Solution
Nokia mobile phone running J2ME program when the "Can't run the Application" error, is usually caused by insufficient memory, but today encountered such a mistake, but found to be another reason. That is, when using the Nokia UI Api,directgraphics DrawImage, if the rotation parameters are set incorrectly, an "Cannot run Application" error occurs.
After the application is installed, open the application directory and display the error message:
"Program is turned off Midpui USER9" and the application directory cannot be entered.
After analysis, it turns out that the newly installed application is not in the MAINFEST.MF
The application icon is specified in the Midlet-1 property, causing the program directory to not display the icon.
On the NokiaS40 machine and ngageqd that I saw, if the icon did not specify or specify a
Does not exist, the default icon is displayed.
It is not known whether this bug exists for other versions of 7650 or other models.
Workaround: Use Seleq to delete the directory of the program just installed in 7650C:/SYSTEM/MIDP, and enter the application directory normally.
Use your own application icon in your application and set it up correctly to avoid encountering this bug to the user.
(2) Nokia3100 (v3.10) game directory vibration settings and applications in the use of vibration conflicts with the bug
In Nokia3100 and other models, provides a game directory management game class applications. The directory
You can set the game running in the directory to sound, vibrate and use the network. For
NOKIA3100 (V3.10) If the vibration setting is turned off and the vibration is used in the application, the
An exception is generated. The bug was discovered 10 months ago and it is not clear which is the exception.
It is not known whether this bug exists for other versions of 3100 or other models.
Workaround: Add exception handling where vibrations are used in the application.
7 Motorola Mobile Phone J2ME application problem
(1) Application icon
An icon file must be specified in the Jad file Midlet-icon attribute, and the icon specified in Midlet-1 is invalid
Java mobile network [www.cnjm.net] Moto V-series icon size should be 15*15, other dimensions can not be displayed.
(2) left and right soft key problem
Motorola mobile phone operating system settings are: Right Soft key confirmation, left soft key cancellation. So, our program should be consistent with this habit.
(3) Key Code
Moto V's key code differs from other Midp2.0 machines
Left Soft key: 21
Right Soft key: 22
Medium Key: 20
Up:1
Down:6
Left:2
Right:5
(2005.12.31 Note: In the face of new models, first Test keycode better)
8 MIDP2.0 Canvas Full-screen problem
MIDP2.0 Canvas can call Setfullscreenmode (true) to set the canvas to a perfect screen, but the new canvas width & height is not the same for different phones when the screen is set.
(1) Motov series
When Setfullscreenmode (true) is invoked, the SizeChanged event is triggered, which accepts two parameters from the system, that is, the width & height of the canvas full screen, which can be used to get a new width high.
protected void sizechanged (int w, int h)
{
width = w;
Height = h;
}
Note, however, that this event is not synchronized, that is, if you call Setfullscreenmode (true) immediately after using the new width,height, you may get the wrong result.
(2) SE K700
When Setfullscreenmode (true) is invoked, the sizechanged is not triggered, but the new height is obtained through getwidth and getheight. SE's Setfullscreenmode call is returned immediately, so you can get the correct width & height
Different models respond differently to keyboard events. After my test, Nokia 7210,3100 can only accept one key message at a time. (I wrote a test program, found that if a key is pressed and not released, then the Keypressed event will not be generated, that is, the other keys of the press operation is not valid) so, with the buffer processing control elf movement, if the regulation can only four direction movement. If up is pressed and left is pressed, the wizard's movement direction does not change. However, the key is buffered. Press up, press left not to release, release up---The Genie will move to the right. (The left Keypressed event is created when you release the UP!) is that weird? I didn't do "press" left after I loosened up. The--left key was pressed and not released before the up was released. It seems that the machine has been monitoring the status of keys on the keyboard and has a waiting queue. )
It's different on the WTK standard simulator. It accepts events that are pressed "simultaneously" by multiple keystrokes. So if you use four side-by-side if processing, the sprite can be tilted in motion. If you are handling with if else, if you have pressed one of the arrow keys and then pressed another, whether the direction can be changed by the order in the IF Else statement. That is, if (up) else if, the up key is checked, so if you have pressed left and then press up, you can move up, and vice versa. (This nature:)
Other models I didn't try because there was no machine on hand. That's the way it should be.
2 Multi-model transplant experience talk
Development of the platform is Nokia 40, and then transplanted to Nokia, Moto V, SE, etc., summed up about the need for several versions.
1. Nokia version 40, using the Midp1.0+nokia UI API
2. Nokia version 60, using the Midp1.0+nokia UI API
3. Nokia Midp2.0 version, such as 6600,7610, using Midp2.0
4. Moto v Edition, using Midp2.0
5. Se Edition, using Midp2.0
6. Samsung S100,S200,C100, using Midp2.0
Several development experience:
1. The biggest difference between the models is that the screen size is different. So in the game to be able to adapt to the screen size
2. Do not use Midp2.0 Gameapi will be easier to transplant, as long as their own packaging cut map, rotation and other functions can be. Nokiaui APIs and MIDP2. 0 Support Picture selection. 2.0 support is better. Note that Nokia 60 does not support the creation of variable transparent pictures, so replace them with other methods.
3. There is a problem with the NOkia 6600,7610 UI API (picture rotation), so use the Midp2.0 instead
4. Support MIDP2. 0 of the machine programs are roughly the same, and MOTO,SE,SX are similar. But there are subtle differences. such as SE does not support full-screen. So the Screensizechanged method is invalid.
5. Talk about sound playback. NOkia S40 I firmly do not use the voice, one is the capacity limit, the second is too harsh. Other models can support MIDI and WAV. But no one can play 2 MIDI models at the same time, Moto V and SE can play midi and Wav,nokia at the same time.
3 Transplantation One method
Recently observed some of the game's source code (decompile), found that there is a convenient way to transplant the game. Defines an interface (such as stringtable) that defines the static strings used in the game as constants of the interface. Then, let the classes that use these strings implement the Stringtable interface. This allows you to modify the strings in the interface as soon as you migrate. Of course, for the location of the coordinates of the game, it is best to use getwidth (), GetHeight () and the Font class method Stringwidth, do not set dead. In this way, the transplant work is more relaxed.
4 Test model
In J2ME development, often encountered according to different models do different things, such as Nokia3650 keyboard is more special, Nokia7650 does not support MMAPI, so need to obtain model information.
Here's a simple piece of code
public static void Checkplatform ()
{
String platform = system.getproperty ("Microedition.platform");
String tmp = NULL;
if (Platform.length () ==9)
TMP = platform;
else if (platform.length () >9) {
TMP = platform.substring (0,9);
}
if (tmp!=null) {
if (Tmp.equals ("Nokia3650")) {
is3650 = true;
}
else if (tmp.equals ("Nokia7650")) {
is7650 = true;
}
}
}
Get the model information also includes the version number, and so on, so you want to intercept the previous few character comparisons.
But the resulting model strings are sometimes not insured, as earlier Nokia N-gage were not n-gage, but 3650 and 7650 were still available.
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.