Presentation is loading. Please wait.

Presentation is loading. Please wait.

Java 2D Training. Basic Tools Java SDK 1.4x Wireless Toolkit 2.x NetBeans IDE + mobility pack Global Code editor Text Comparer Tools Graphics Editor Sprite.

Similar presentations


Presentation on theme: "Java 2D Training. Basic Tools Java SDK 1.4x Wireless Toolkit 2.x NetBeans IDE + mobility pack Global Code editor Text Comparer Tools Graphics Editor Sprite."— Presentation transcript:

1 Java 2D Training

2 Basic Tools Java SDK 1.4x Wireless Toolkit 2.x NetBeans IDE + mobility pack Global Code editor Text Comparer Tools Graphics Editor Sprite and Game Editor

3 Basic Tools Java SDK You will need the Java SDK, to be able to compile your mobile applications and run J2ME emulators. Keep in mind that only Java 1.4 is compatible with the Wireless Toolkit; any other version, older or newer will not work. To download the Java SDK + NetBeans, access the link below: Wireless Toolkit 2.2 The Wireless Toolkit allows you to compile and run J2ME applications. The WTK provides you with the libraries needed for a mobile applications (the CLDC and MIDP libraries) and with an emulator on which you will run the application. To download the Wireless Toolkit, access the link below: NetBeans IDE + mobility pack For the training purpose, you will need NetBeans. Netbeans is a free IDE recommended by Sun. The mobility pack allows you to develop J2ME applications using NetBeans. To download the Mobility Pack, access the link below:

4 Basic Tools Global Code editor After finishing the training, for development in Gameloft, you will not use NetBeans anymore, you will use a text editor that can highlight any kind of syntaxes (C++, Java, html, xml, batch etc.). I strongly recommend NotePad++. It’s a free, flexible and powerful tool. To download NotePad++, access the link below: Text Comparer Tools As you work in different project, you feel the need to compare different files. E.g.: compare a file with a newer version of that file. For this purpose we use Beyond Compare To download Beyond Compare, access the link below: This tool requires license, Gameloft has a world license for Beyond Compare. You can find it in the tools folder of the training program.

5 J2ME basics JAR & JAD JVM problems: Emulator vs. phone. CLDC 1.0 / 1.1 MIDP 1.0 / 2.0

6 The MIDlet lifecycle

7 J2ME “Hello World” cMidlet.java import javax.microedition.midlet.*; public class cMidlet extends MIDlet { public void startApp() { System.out.println("Hello World"); } public void pauseApp() { } public void destroyApp(boolean unconditional) { }

8 Drawing on screen – Canvas – 1 cMidlet.java import javax.microedition.midlet.*; public class cMidlet extends MIDlet { static cMidlet _midlet; static cGame _game; public cMidlet()‏ { _midlet = this; _game = new cGame(); } public void startApp() { _game.start(); } public void pauseApp() { } public void destroyApp(boolean unconditional) { }

9 Drawing on screen – Canvas - 2 cGame.java import javax.microedition.lcdui.*; public class cGame extends Canvas { public cGame() { Display.getDisplay(cMidlet._midlet).setCurrent(this); } public void start()‏ { repaint(); } public void paint(Graphics g)‏ { g.setColor(0x000000); g.fillRect(0,0,240,320); g.setColor(0x0000FF); g.drawString("Hello World !", 120, 160, Graphics.TOP|Graphics.HCENTER); }

10 Key events & Run loop – part 1 cMidlet – same as on the previous part cGame – part 1 import javax.microedition.lcdui.*; public class cGame extends Canvas implements Runnable { public cGame() { Display.getDisplay(cMidlet._midlet).setCurrent(this); } public void start()‏ { new Thread(this).start(); } int x, y; public void paint(Graphics g)‏ { if ((_keys & 1) != 0)‏ y -= 10; if ((_keys & 2) != 0)‏ y += 10; if ((_keys & 4) != 0)‏ x -= 10; if ((_keys & 8) != 0)‏ x += 10; g.setColor(0x000000); g.fillRect(0,0,240,320); g.setColor(0x0000FF); g.drawString("Hello World !", x, y, Graphics.TOP|Graphics.HCENTER); }

11 Key events & Run loop – part 2 cGame – part 2 public void run()‏ { while (true)‏ { repaint(); UpdateInput(); try { Thread.sleep(100); } catch (Exception e) {} } int _keysTmp; int _keys; public void keyPressed(int keyCode)‏ { _keysTmp = keyCode; } public void UpdateInput()‏ { _keys = 0; if (_keysTmp == -1)‏ _keys |= (1<<0); else if (_keysTmp == -2)‏ _keys |= (1<<1); else if (_keysTmp == -3)‏ _keys |= (1<<2); else if (_keysTmp == -4)‏ _keys |= (1<<3); _keysTmp = 0; }

12 A simple game From now on you will use a simple application that presents some basic features that are present in all the games. MIDlet, Canvas, Runnable Display.getDisplay(), Thread.start()‏ run() & paint()‏ hideNotify(), showNotify()‏ State machine Key events

13 Basic Tasks 1. Fix the ingame menu. 2. Add functionality to 8,4,6,2 - same as directional keys. 3. Add a picture instead of the "-----" in the ingame menu 4. Add sounds to the game. 5. Make the selection on the main menu to return on "new game“ on interrupt. 6. Add a RMS to the game to save the players coordinates. 7. Fix the random crash. 8. Make the game end - add an end to the level.

14 Advanced Tasks 9. Remove the project from Netbeans and create the JAR&JAD using batch files. 10. Use the preprocessor. Break the Java files into.h files. 11. Deploy the game on the phone using GPRS. 12. Read the SVN documentation. Create a SVN with the project. 13. Check if your project respects ergonomic rules.

15 1. A simple bug Description: Enter the game, choose “new game” and press left soft key. The ingame menu will appear. You will notice that you cannot move the selection. Task: Make the ingame menu selection work. Hint: See the code for main menu, understand it’s functionality and use it for the ingame menu.

16 2. Keys Description: The key system let’s you interact with your application. Canvas offers you a set of methods that allow you to intercept the key input. This methods are : keyPressed(int keyCode) – gives you the key code of the last pressed key. keyReleased(int keyCode) – gives you the key code of the last released key. keyRepeated(int keyCode) – gives you the key code of the last repeated key. Using the keyCode value you can determine what key was pressed. Different phones have different key for their keys. This is why we need to use the int getKeyMask(int keyCode) method. This method will receive a key code and return and return a key mask. Key codes differ for each phone, they can be changed from the KEY.java interface, key masks will always remain the same. Using _keysCurrent you can determine what keys were used. UpdateInput() method synchronizes when the input is updated in the game. This method is called once per frame, so this way you are sure that only then the keys state is changed. Task: Make the 8,6,4,2 keys work as directional keys. Hint: Look at the keyPressed(), keyReleased() and getKeyMask() methods. Understand how the directional keys are used.

17 3. Loading and drawing a image Description: Images are the base of any 2D game. In J2ME the images are in PNG (Portable Network Graphics) format, and they are indexed. An indexed images has a palette and a index map. For example if you have a 16 colors PNG the palette will contain 16 colors in RGB format and the index map will contain numbers from 0 to 15. javax.microedition.lcdui.Image is the class that allows you to store and use images. E.g. : Image _img; void load() //the create Image process uses a lot of CPU time, it must execute on loadings { _img = Image.createImage(“\logo.png”); } javax.microedition.lcdui.Graphics is the class that allows you to draw images. E.g. : void paint(Graphics g)‏ { g.drawImage(_img, 0, 0, Graphics.HCENTER | Graphics.VCENTER); } javax.microedition.lcdui.Graphics also gives support for basic image processing: flipping, rotations, clipping etc. Read the documentation for more information. You will find the documentation at “\docs\api\midp\index.html” in your WTK folder. Task: The selection in main menu and ingame menu is drawn as “-----”. Replace the “-----” with a image of your choice.

18 4. Sounds Description: All mobile games must have sounds. The current one lacks all the sounds. The sound are the most problematic part of any mobile game, it’s very probably to have sound issues on any project. Sound problems are: small freezes caused by sounds, crashes, too loud volume, too low volume etc. Fixes differ from phone to phone. There are 4 basic ways to play a sound. You can use one player object for all the sounds, use as many players as sounds and you can play them on the main thread or on a separate thread. Task: Implement 2 players objects that contain 2 sounds, that play on the main thread for your game. First sound should be the title sound that is played when the splash screen is shown, the second should be a colision sound that is played when the Main Character hits a wall. Hint: You will find everything you need in the documentation at e.g. WTK22\docs\api\midp\index.html. Read about the Manager class and the Player class.

19 5. Interrupts Description: A important difference between a normal computer game and a mobile game are the interrupts. Interrupts happen when a call, SMS Bluetooth message is received, when the red key is pressed or when the time alarm is triggered. How does an interrupt behave in the code? When an interrupt occurs 4 things can determine that: Canvas.hideNotify() is called at the beginning of the interrupt and Canvas.showNotify() is called when the application is resumed. Midlet.pauseApp() is called at the beginning of the interrupt and Midlet.startApp() is called when the application is resumed. The Canvas’ main display object becomes null so there for the paint() callback will not call void paint(Graphics g), it will do nothing. This is the reason why the state machine is recommended to be in the paint() method and not in run(), so that it stops running while the interrupt occurs. Displayable.isShown() will return false. Usualy most of the games have to display the ingame menu after an interrupt to pause the game and let the user continue the game when he is ready to. Task: When you are in main menu or in the ingame menu, after an interrupt make the selection select the first menu option. Hint: Look at the hideNotify() and showNotify() methods in the code.

20 6. Record Store Description: All the games need to have saves. Save the high scores, the last completed level, etc. For that J2ME uses a RecordStore. A RecordStore is a file kept on the phone’s permanent memory and that can be accessed only by the application that created it. This file can contain any kind of binary data. Task: If a user quits the game, save the user’s coordinates in the RMS. Add a new entry in the main menu called “continue game” this option will activate only when the RMS stores a valid information. The user can continue the game from his last location by selecting “continue game”. Hint: Search the WTK documentation for the RecordStore class.

21 7. A random crash Description: Play the game and observe that at some moment the game will freeze. That is a crash. It apparently happens random. You need to know that when errors happen Java throws exceptions. The exception are of many different types: NullPointer, ArrayIndexOutOfBounds, ArithmeticException, IllegalArgument, etc. By catching an exception you have fixed half of the problem. Many programmers use try{} blocks with empty catch(){} blocks, so if an exception will occur in that block you will not be able to see the error. Try to avoid such mistakes. Task: Track a crash. Does it throw an exception? Where is that coming from? Why does it happen? Fix it. Hint: Look in the documentation for the exception types and when are thrown. If you don’t know anything about the exception system, document yourself, or ask your trainer.

22 8. Add extra features Description: As you can see the game has no finality, you cannot win or loose. Task: Make the game end somehow. You could add an extra tile on the map and treat that tile as the exit from the level. You can also implement collisions with the enemies and when a enemy collision occurs the game is lost. Hint: You should know everything to do this task. If you hadn’t look until now at the tile map, take a look at it now.

23 9. Part 1 - Batch files Batch files are the most basic scripting files. We need batch files to compile the sources, to build the resources and to pack the final archive. Basic batch file: 1 SET JAVA=c:\Java\bin\java.exe 2 if not “%JAVA%”==“” ( 3 if exist “%JAVA%” ( 4 %JAVA% -help 5 ) else ( 6 echo The path does not exist 7 ) ‏ 8 ) else ( 9 echo The path is not valid 10 ) ‏ On line 1 the variable JAVA is given a value. On lines 2 and 3 there are 2 if statements that check if variable JAVA is not empty and if it’s value is a valid path. On line 4 the a command is executed calling the java help. Notices: - the batch files are sensitive to extra spaces and new lines. For example if instead of SET JAVA=c:\Java\bin\java.exe was SET JAVA= c:\Java\bin\java.exe then the variable JAVA was empty. - ) else ( is writable only in this way if you add a new line between else and ( the command will not work - to call a batch file from inside a nother batch file use the call command for example : set batch_name=config.bat call %batch_name% For more documentation search the web or ask your lead programmer.

24 9. Part 2 – Building a package To build a JAR and JAD you need to do the following steps: Let’s say you have all the.java sources in the “\src” folder, and all your resources in the “\res” folder. 1.Compile the sources To compile the sources you need to use javac.exe. From.java files you will obtain.class files. Put the.class files into a new folder “\compiled” 2.Obfuscate the sources Obfuscation is the process that replaces all you variables and methods names with very simple names. For example the getPlayerCoords() function will be renamed something like a2(). This process has 2 advantages: first, your final package will be smaller; second, your files will be almost impossible to decompile and modify. All Gameloft project require obfuscation. The standard tool is proguard.jar. After obfuscation output the obfuscated classes into “\obfuscated” folder. 3.Preverify the sources The CLDC standard does not include bytecode verification at runtime. So we need to preverify the code before we give it to the JVM. For that you need to use preverify.exe found in the \bin folder in your WTK folder. Output the preverified classes into “\preverified” folder. 1.Create the MANIFEST.MF file The MANIFEST.MF is a mandatory file. It contains different information regarding the package. Here is a standard example: Manifest-Version: 1.0 MicroEdition-Configuration: CLDC-1.0 MicroEdition-Profile: MIDP-2.0 MIDlet-Name: Gameloft Mega Hits MIDlet-Icon: /icon.png MIDlet-Vendor: Gameloft SA MIDlet-1: Gameloft Mega Hits, /icon.png, CMIDlet MIDlet-Version: The manifest must always be found in the \META-INF folder inside the JAR: \META-INF\MANIFEST.MF Pack the sources, the resources and the MANIFEST.MF into a JAR file You need to add in an archive the content of the “\src” folder “\res” folder, and \META-INF\MANIFEST.MF. The archive is a zip archive. The standard tool for this is “jar.exe” it can be found in the \bin folder in your java SDK. 1.Create the JAD file The JAD (java application descriptor) is pretty similar to the manifest. Here is an example, the red fields are only needed for the JAD. MIDlet-Name: Gameloft Mega Hits MIDlet-Icon: /icon.png MIDlet-Vendor: Gameloft SA MIDlet-1: Gameloft Mega Hits, /icon.png, CMIDlet MIDlet-Version: MIDlet-Jar-URL: DemoMegaHitsNokia6600EN001.jar MIDlet-Data-Size: 500 MIDlet-Jar-Size: MIDlet-Description: Play Gameloft’s best games !

25 9. Part 3 – Building with batch files Task: Using the batch files create a project with the following folders: -\src – contains the java sources -\res – contains the resources -\build – contains make.bat (a batch that builds the project) and run.bat (a batch that runs the jar). -\#release – contains the final JAR&JAD -\tools – contains all the tools required for the project From now on you will not be using NetBeans and you will start using a simple text editor like UltraEdit. Hints: make.bat – should do the steps presented at part 2 of this section. To build the JAR&JAD you need proguard.jar and UpdateJad.exe (to update the JAR size in the JAD), you will find them in the tools folder, in the original project. run.bat – will execute the game using the emulator. You can use the standard java emulator which you can find in the \bin folder of your wireless toolkit or you can use the GLemulator.

26 10.Part 1 - Preprocessing Java does not give support for preprocessing. Gameloft mobile projects require preprocessing. Why? Here is an example: You have the same sources for 2 phones, the first is a Nokia the second is a Samsung. Everything is the same on both of the phones the only difference is at sounds. Nokia uses the standard MIDP2 Player and Samsung uses AudioClip. So we need to import 2 different packages to use the Player and AudioClip. We cannot do that using only Java. So we use preprocessing directives. The resulting code will look like this: For samsung we “#define SAMSUNG” #ifdef SAMSUNG import com.samsung.util.AudioClip; #else import javax.microedition.media.*; #endif This way for the Samsung phone only the first import will be considered, for other phone the second import will be used. This code is not compliable with javac so before we can compile the.java files we preprocess them using cpp.exe. So we need to add an new step in the building process: the preprocessing step. The preprocessing step will be the first step, before the compile step.

27 10.Part 2 -.h files All J2ME Gameloft projects use.java and.h files; the.h files are included in the.java files using #include directives. This may seem a little bit weird, but there are 2 good reasons for this: First reason is that after preprocessing has been introduced the.java files started to have lots of #ifdef #else #end blocks, the code became bigger and bigger, because it contained the functionality for more than one project in the same code. The code became hard to follow. The solution was to break the code into modules. First time the code was segmented into many classes, but a very big overhead was created this way. Many mobile phones cannot load more then classes, and 20 small classes use more heap than 3 big classes. The solution was dropped. The second solution was to break the.java files into smaller files,.h files, that will contain certain functionality. For example from cGame.java was created cGame_menu.h containing the menu functions, cGame_sound.h containing the sound functions, cGame_keys.h containing the keys functions, cGame_mainGame.h containing the ingame functions and cGame.java that included the 4.h files. This way the code became easier to follow The second reason for the usage of.h files was that having only a few classes we would have had only 4-5 source files eg: cMidlet.java, cGame.java, DEF.iava and Keys.java. If a team of programmers was working on such a code most of the modification would be done on cGame.java. The modification are hard to follow this way. With the.h system you can easily see if someone modified the menu, the sounds or the game engine, because they would modify only a.h file not the entire main class file.

28 10.Part 3 – Preprocessing and breaking into.h files Task: Break the CGame.java file into.h files. How? For example, remove the sound functions from the java file and copy them into CGame_sound.h. And include in the java file the new.h file, like this: #include CGame_sound.h. After you have finished breaking into.h files update the make.bat script so that before compiling it will do the preprocessing of.java and.h files and output only.java files. The preprocessed java file should be outputted into the “\preprocessed” folder. From that folder they will be compiled. Tips: You will need cpp.exe (that requires cygwin1.dll), you can find it in the “\tools” folder of the orginal project.

29 11. Phone deployment Description: All the games need to be deployed on phones. You can deploy an application in different ways: WAP, GPRS, Bluetooth, Infrared, Data Cable and by using a Memory Card. For all the application, except the embedded projects, it’s mandatory to download via OTA (Over The Air), that means by WAP or GPRS. Task: Deploy the application using GPRS on a 176x220 resolution phone. See if there are any problems on the phone, if find any, fix them.

30 For any questions contact Mihai Popa


Download ppt "Java 2D Training. Basic Tools Java SDK 1.4x Wireless Toolkit 2.x NetBeans IDE + mobility pack Global Code editor Text Comparer Tools Graphics Editor Sprite."

Similar presentations


Ads by Google