J2ME game development skills

xiaoxiao2021-03-06  119

Not long ago I used J2ME to develop a colorful game under Motot720 - Gridone. Some experiences have been accumulated during the development process, and now we should write it with you. Use dual buffer avoidance screen scintillation double buffer technology is one of the key technologies to write J2ME gaming programs. In fact, double buffer technology is a traditional technology of computer animation. The main reason for causing screen blinks is that the screen is changing it while the screen is changed, so that the picture flashes. The solution is to open a zone in memory as a background screen, and the program is updated, modified, and then display it after completion. This is always a fully painted image, and the program modified will not be displayed. Of course, there are other methods to solve the screen blinking problem, but use dual buffer technology is a recommended solution. See the following code:

Public Class Blockscanvas Extends Canvas Implements Runnable

{

Graphics BG;

Image buf;

Public blockscanvas ()

{

......

Height = GetHeight ();

Width = getWidth ();

/ / Create a buffer object according to the screen size

BUF = image.createImage (width, height);

// Take the graphics of the buffer object to BG

BG = buf.getgraphics ();

......

}

Public void Run ()

{...

For (i = 0; i

{

For (j = 0; j

{// painting square

Drawblock (x, y);

}

}

Repaint ();

}

Private Void DrawBlock (int block_x, int block_y)

{

// Get the coordinates of the square

INT x = Getleft (block_x);

INT Y = Gettop (Block_Y);

// Get the color of the square

INT C = Board [block_x] [block_y];

Bg.drawImage (IMGS [C], X, Y, Graphics.top | Graphics.Left);

}

Public void Paint (Graphics G)

{

G.drawImage (buf, 0, 0, graphics.top | graphics.Left);

}

}

It can be seen from the above code, and the double buffered idea is reflected in the program to complete the following steps as possible: 1. Define a Graphics object BG and an image object buf, build a buffer object with the screen size to attach the BUF, then get the BUF Graphics object to the BG. Here, the Graphics object can be understood as a buffered screen, and the image object can be used as a picture on the buffer screen. 2. DrawiMage () and DrawString are drawn on a BG (buffer screen), which is equivalent to drawing on the buffer screen. 3. Call the repaint () statement, its function is to inform the system to call Paint () to complete the display of the real screen. It should be noted here that Paint () is a system calling statement that cannot be manually called, and can only be called by a Paint () statement. 4. In the Paint (Graphics G) function, draw the BUF (the picture on the buffer screen) on the real screen. Although the above steps seem to be cumbersome, the effect is still very nice. If you want to display something on the screen, you can draw it on the BG, then call repaint () to display it. Writing your own breakpoint function Figure 1 Breakpoint test In the development J2ME program, the most troublesome problem is that the program is easy to crash. When using JBuilder or CodeWarrior sets the breakpoint function to find the program error, the probability of the crane is even greater. Even if it is not dead, it is also worried that the procedure has been unexpected interference, so it is generally not recommended to use the breakpoint function of the development tool. But sometimes it needs a function to display the value of the current variable to make the correct judgment when you check the error. So I thought of a way to write my own breakpoint function. The specific code is as follows: Public class blockscanvas extends Canvas Implements Runnable

{

Private boolean stopflag = false; // debug logo

......

Public void Run ()

{

// breakpoint position 1

Testfun ("x:" x "Y:" y);

......

// breakpoint position 2

Testfun ("" ");

......

}

Private void testfun (String Str)

{

Stopflag = true;

// Draw a white rectangle

Bg.SETGRAYSCALE (255);

Bg.FillRect (0, 0, fontw, fonth);

// Show the contents of the STR on white rectangle

Bg.SETGRAYSCALE (0);

Bg.drawstring (STR, 0, 0, graphics.top | graphics.Left);

Repaint ();

While (stopflag) {}

}

Public void keypressed (int keycode)

{

STOPFLAG = FALSE;

}

}

First define a Boolean type StopFlag variable to log debug logo. Attack thereof FALSE, entered the TestFun () function, set to True. After the content of the STR is displayed, because the value of Stopflag is True, the While statement enters the dead cycle, the program stopped. At this point, you can carefully see the value of the variable. Then when you press any key, the keypressed () function captures this event and sets StopFlag to false, and the dead cycle is automatically unspected. It is very convenient to use this method, as long as the TestFun () statement is placed in a section that requires breakpoint, a program can place multiple TestFun () statements, and the TestFun () statement can be placed in the loop statement. The program runs to the testfun () statement automatically stops the display variable value, and pressing any keypad to run automatically, and the program will not be accidentally interfered. Figure 1 is a screenshot of debugging. There is also a point in need to explain that the TestFun () statement of this method must be placed in a run () function or the run () function is called in a function, otherwise it will cause keypressed () due to while () occupies all CPU times. The function cannot capture the button event, and finally leads to the crash. This method can use the pause function of the game as long as it is slightly modified, and it is better than the Sleep () method, after all, theoretically, the SLEEP () method cannot be suspended indefinitely. Here is the corresponding code: Public Class Blockscanvas Extends Canvas IMPLEments Runnable

{

Private boolean stopflag = false; // Pause flag

......

Public void Run ()

{...

Testfun ();

......

}

Private void testfun ()

{

While (stopflag) {}

}

Public void keypressed (int keycode)

{

Int action = getGameAction (keycode);

IF (Action == Fire) stopflag =! stopflag;

}

}

The function of the block is that when the user presses the Fire button, the game is suspended; press the Fire button again, the game continues to run. Writing your own tools Because the mobile phone memory and function restrictions, J2ME only provides a partial J2SE tool class for users to call. So sometimes we have to write your own tool class to achieve some special features. The Kset class given below is similar to the functionality of the SET tool class in J2SE. It is used to record the collection of blocks in the game while ensuring that there is no identical element in the collection.

/ **

*

Description: The implementation of the SET class on J2ME

*

Date: 2003.2.28

*

author: tomjava

*

email: tomjava@sohu.com

* /

Public Class Kset

{// implemented with single-link table

Private ksenode head;

Public Kset ()

{

HEAD = NULL;

}

// Clear Kset

Public void clear ()

{

HEAD = NULL;

}

/ / Add elements to Kset

Public Boolean Add (int X, int y)

{

Ksetnode node = new ksetnode (x, y);

Return add (node);

}

/ / Add elements to Kset

Public Boolean Add (Ksetnode Node) {

IF (! Contains (Node))

{

Node.next = head;

HEAD = NODE;

Return True;

Else

{

Return False;

}

}

/ / Judge whether the Kset is empty

Public Boolean ISempty ()

{

IF (head == null)

Return True;

Else

Return False;

}

/ / Pick up the chain head element and return this element

Public Ksetnode getFirst ()

{

Ksetnode P = Head;

HEAD = p.next;

Return P;

}

// Traverse KSET, if you have the same element to return true, otherwise return false

Public Boolean Contains (KsetNode Node)

{

Ksetnode P = Head;

While (p! = null) {

IF (p.equals (node)) Return True;

p = p.ness;

}

Return False;

}

}

// kset elements

Public Class Ksetnode

{

Public Int x, y;

Public ksetnode next;

Public KsetNode (int X, int y)

{

THIS.X = X;

THIS.Y = Y;

Next = NULL;

}

Public Boolean Equals (KsetNode Node)

{

IF (node.x == x && node.y == y)

Return True;

Else

Return False;

}

Public int getX ()

{

Return X;

}

Public int getY ()

{

Return Y;

}

}

The KsetNode class is responsible for record the coordinates of the deleted blocks, which overloads the equals () method to determine if the two blocks are the same. The KSET class is a collection that is not the same element consisting of KsetNode objects, implemented with a single-link table, and provides getFirst (), add (), clear (), iSempty (), contacts (), etc. For other types of calls. Write and use some such tool classes, will greatly speed up the speed of programming, but also make the program clearer. Correction Screen Coordinate Gridone This game is developed specifically for MOTOT720, that is, the size of the game background image and MOTOT720 mobile phones are equal. If it runs on those on the screen than the MOTOT720 big mobile phone, the game background image will display in the upper left corner of the screen, affecting the appearance, then use the screen correction technology to make the game background picture. The correction screen coordinate code is as follows:

Public Class Blockscanvas Extends Canvas Implements Runnable

{

Private final int address; // coordinate correction

PRIVATE FINAL INT Addy;

Private final int screen_x; // screen vertices

PRIVATE FINAL INT SCREEN_Y;

Private final int waitingblock_x; // Waiting for the square vertices

PRIVATE FINAL INT WAITBLOCK_Y;

PRIVATE FINAL INT Score_x; // Score Vertex

PRIVATE FINAL INT score_y;

PRIVATE FINAL INT Star_x; // Pentagon's vertices

PRIVATE FINAL INT STAR_Y;

Public blockscanvas ()

{

/ / Get the height and width of the current mobile phone screen

Height = GetHeight ();

Width = getWidth ();

// coordinate correction

AddX = (width-120) / 2;

Addy = (HEIGHT-142) / 2;

// Initialize the screen parameters

Screen_x = addx 48; // screen vertices

Screen_y = addy 10;

Waitblock_x = addx 19; // Waiting for the top

Waitblock_y = addy 103;

Scores_x = addX 36; // score vertex

Scores_y = addy 34;

Star_x = addX 4; // Pentagon's vertex

Star_y = addy 70;

}

}

First define all the parameters of all the screens to the private final INT variable. The reason here is added to the Final modifier because they do not want to increase the value of the variables, and the reason why they do not add Static modifiers because they want to initialize variables in their functions, not when they define it. Initialized. First use the getHeight () and getWidth () functions to get the height and width of the current mobile phone screen, then calculate the required offset addX and addy, then add it to each screen parameter so that the game content will be displayed. Fig. 2 and FIG. 3 are views of the effect. Figure 2 There is still a point where the correction is corrected, and it is not necessary to pay attention to the use of getHeight () is not the true height of the mobile phone screen, but the height of the mobile phone screen minus the COMMAND tag height, because the screen needs to leave the Command label. Rational use of memory use Java programming is not required to be used, because Java has a waste handling mechanism that it is proud. But in J2ME, the situation has changed, because the phone's memory only has few hundred K, and can no longer be big in J2SE. Otherwise, it will be found that even if the program does not have any syntax and logical errors, it cannot be run in the simulator. Here are several recommendations for reasonable memory: 1. Use local variables to replace classes, reduce the creation of objects, it is best to reuse objects; 2. Don't try to read all forms or canvas objects in memory when you initialize, and you should create it when you need it, although this will have some delays in the display, but the total than the program cannot run or the memory overflow is good; 3. Once the object is not required to use it to null, it can be recycled by the garbage processor. When appropriate, call the system.gc () statement prompt the virtual machine to call the garbage processor; 4. Must keep in mind that Java's memory management is To the side mechanism, don't let the objects you use to point to it, so as to avoid recovery within it; 5. Try to make the picture occupy a small number of bytes, you can use Fireworks to ensure picture quality Reduce the size of the picture; even if you do what you have, you can't guarantee that the program does not have a memory leak, because the phone memory is so few. So I put forward the last suggestion, first complete the body part of the game, so that it can run and do not have memory leaks, slowly expand the game, add the cover and other functions. Once the memory is out of memory, then remove some of the features. Let the game more charmous to write the game, of course, I hope it can be attractive, I think the following places worth paying attention: 1. Pay attention to control the rhythm of the game. When I am cutting the square, I will delete anything, then start a new loop, let the waiting block down. The effect is not very good during actual operation, the faster the above, the faster above, let the player have a feeling of caughtors. Later, when I was deleted square, I paused for a few seconds with an empty loop, so I gave the player a reaction time, and I feel better, and if it is connected, the reaction time will be longer, so that the player is playing There is a relaxed feeling in the game. Later, I changed the empty cycle into the block traversed on the screen, so that the deleted squares made the player can see the deleted square, appreciate their own results, which added the attraction of the game. 2. Use the picture to achieve colorful expression effects in J2ME if you can't control the size of the text and the font, this will make the game's effect is greatly reduced.

However, this problem can be solved by making a variety of special characters into a picture. In some places, we can also replace the text with a picture, making the game more vivid, such as the difficulty of the game with a five-pointer in the level column. Another advantage is to increase the versatility of the game, making the game on different mobile phones substantially the same. In addition, if the font color is displayed in the simulator, it can be solved in this way on the phone. 3. Let the game can automatically adjust the difficulty I use the following functions, making the game difficulty. Private void giveelevel ()

{

IF (Level <= 10)

{

LevelSleep = 600- (Level - 1) * 50;

LevelSleep <200)

Levelsleep = 200;

LevelDeltask = 200 (Level-1) * 100;

IF (LevelDeltask> 1000)

LevelDeltask = 1000;

// Painting Level - Five Corners

Paintstar ();

Else

{

Gamewin ();

}

}

Level represents the game level, LevelSleep represents a waiting time for block drops. LevelDeltask means a number of squares that need to be deleted, and it is also understood that the task that needs to be completed. The above calculation formula ensures that the game will get harder and harder, add the attraction of the game.

转载请注明原文地址:https://www.9cbs.com/read-97684.html

New Post(0)