Eclipse Development J2ME program sixth talk about making graphical mobile games

Source: Internet
Author: User
Tags win32
   Introduction

Now the mobile phone as an entertainment electronic communication equipment, has already exceeded the original call, short message and other basic communication functions, more and more entertainment, leisure software such as mobile phone games, e-books, music editing, photography and image processing are also popular in today's various brands of mobile phones. Among them, the game software occupies a very large proportion. Since we have mastered the development process of mobile phone software, why not develop a personalized mobile phone game. This article will introduce a simple image of the mobile phone game-"Flower skin cat vs." The production process of the rogue Rabbit. Flower skin Cat is naturally the author of the Love of cats, interested readers can also make their favorite puppy play the protagonist of the game, fully display the charm of DIY.

   the design of the game

The development of mobile games requires the planning of the overall process and the specific rules of the game (or the game script), and then the implementation of specific coding according to this script. Limited by the length of the article, the game script design can not be too complicated. First of all, the game is positioned as a human-machine game, the program run began to show the game's cover screen, after a few seconds automatically transferred to the role selection screen, after the player chooses a role to start the game. The game starts with a random decision on which party is first. The man-machine alternately lazi in a checkerboard grid of 3 by 3 size (the two pieces have a different pattern), and only allows the sub-grid in the empty mesh without falling. As long as there is one side of the pieces in the horizontal, vertical, oblique any side of the total up to three to win. If the board is filled, both sides do not reach three pieces in the above direction, the board is a draw. Regardless of the outcome, the results of the administration and the total score are displayed at the end of each inning. Players can opt out or start the new game again. The above is the main frame of the game and the basic rules of the game, the subsequent coding work is based on this.

   the construction of the game frame


Figure 1

First build the project and create a new MIDlet TicTacToe to join, continue adding choosepiecescreen, Gamescreen, and game three classes to the project. As a game, if still take the text to make the software cover seems too unprofessional. If you want to use a picture in a J2ME program, you must convert it to a PNG image and then click the right mouse button on the item and select the File menu item from the new menu to pop up the dialog box as shown above. The bottom half of the first part is hidden and needs to be displayed by clicking the Advanced button. Select the link to a file in the file system and specify the path to the picture you want to add by using the Browse dialog box. Finally, enter the file name of the picture in the File Name field and click Done to add the picture to the project. Just load the picture in Startapp () with the following code and display it through the message box:

Image logo = null;
try {
Logo = Image.createimage ("/logo.png");
}catch (IOException e) {}
Alert SplashScreen = new alert (NULL, "Langrui 2004 for/n Copyright (c)/n2004--2005", logo, alerttype.info);
Splashscreen.settimeout (4000); 4 seconds delay


Fig. 2 Fig. 3 Fig. 4 Fig. 5

Enter the role selection interface (Figure 3) after continuing to display the figure 2 four seconds:

Choosepiecescreen = new Choosepiecescreen (this);
Display.getdisplay (This). Setcurrent (SplashScreen, Choosepiecescreen);

This task is implemented in the Choosepiecescreen class, with the main features being the load display of the role icon, confirmation of the selected role, and so on. In its constructor, you first specify the current interface as the list selection method, and then use append () to correlate the loaded image with the corresponding list text. Finally, in response to the user's input selection, you must also call Setcommandlistener () to detect the occurrence of the keystroke event and to implement the confirmation of the selected role in the Commandaction () method:

Super ("Please select:", list.implicit); Set list selection
This.midlet = MIDlet;
Append (Cat_text, LoadImage ("/cat.png")); Add Image options to List
Append (Rabbit_text, LoadImage ("/rabbit.png"));
Setcommandlistener (this); Listen for key response
......
public void Commandaction (Command arg0, displayable arg1) {
if (arg0 = = List.select_command) {
Detect if the button response is a list
Detect User-selected options
Boolean isplayercat = GetString (Getselectedindex ()). Equals (Cat_text);
Midlet.choosepiecescreendone (ISPLAYERCAT); Enter the game screen
}
}

This is done by detecting the text of the list item selected by the user to determine whether the player chooses a flower skin cat or a rogue rabbit and identifies it by a variable isplayercat, in Choosepiecescreendone () method, create a new Gamescreen object and use it as the current display interface to start a game. The Gamescreen class is responsible for the rendering of the game interface, such as the drawing of the chessboard and the two pieces, and the processing of the cursor movement.

   Game Interface Programming

The main interface of chess game is the drawing of chess and chess. This first calculates the checkerboard grid spacing and the size of the pieces according to the screen size:

ScreenWidth = GetWidth ();//Get screen size
ScreenHeight = GetHeight ();
if (ScreenWidth > ScreenHeight) {//Calculate grid size
Boardcellsize = (screenHeight-2)/3;
Boardleft = (ScreenWidth-(Boardcellsize * 3))/2;
Boardtop = 1;
}else{
Boardcellsize = (screenWidth-2)/3;
Boardleft = 1;
Boardtop = (screenheight-boardcellsize * 3)/2;
}

When you draw the board, first empty the entire canvas with the background color and then draw the black grid by row and column, respectively:

G.setcolor (white);
G.fillrect (0, 0, screenwidth, screenheight);
G.setcolor (BLACK);
for (int i = 0; i < 4;i++) {
G.fillrect (Boardleft, Boardcellsize*i+boardtop, (boardcellsize*3) +2,2);
G.fillrect (boardcellsize * i + boardleft, Boardtop, 2, boardcellsize * 3);
}

The drawing of a piece can be achieved by displaying the mounted image in the specified position. For example, for the drawing of a flower skin cat piece, you can load a pre-prepared image (the size must match the grid) by the following code and then call the DrawImage method to draw at the specified location. For the sketch of the Rogue Rabbit, simply change the image to be loaded:

private void Drawcat (Graphics g, int x, int y) {
Image image = null;
try {//Load image
Image = Image.createimage ("/cat.png");
}catch (Exception e) {}
G.drawimage (image, X + 1, y + 1, 0); Draw an image at the specified location
}

As for the handling of the moving cursor, you can first draw a new black rectangle with four sides attached to the checkerboard grid on the inside of the grid that will be moved, and then redraw the original mesh background to erase the last drawn cursor traces in the original grid position. When erasing the old cursor traces, you first need to determine whether the position is blank or draw a piece pattern, and draw a white rectangle based on the judging result or reload the currently displayed piece image. Figure 4 shows a few rounds after the game screenshot, as long as the game does not end, the above-mentioned drawing module will be repeatedly called execution. If the Intelligent Control section of the program determines that the game has ended and gives a result, the board interface is no longer displayed, but the current record is plotted on the white canvas with a specific font in the following code (see Figure 5).

Font font = Font.getfont (Font.face_system, Font.style_plain, Font.size_medium); Set font
int strheight = Font.getheight ();
int statusmsgwidth = Font.stringwidth (statusmsg);
int tallymsgwidth = Font.stringwidth (tallymsg);
int strwidth = Tallymsgwidth;
if (Statusmsgwidth > Tallymsgwidth)
Strwidth = Statusmsgwidth;
int x = (screenwidth-strwidth)/2; Calculate character Draw Position
x = x < 0? 0:x;
int y = (screenHeight-2 * strheight)/2;
y = y < 0? 0:y;
G.setcolor (white); White Empty Canvas
G.fillrect (0, 0, screenwidth, screenheight);
G.setcolor (BLACK); Black Display Information
g.DrawString (statusmsg, X, y, (graphics.top | Graphics.left));
g.DrawString (Tallymsg, x, (y + 1 + strheight), (Graphics.top | Graphics.left));

When this interface is displayed, if the user presses the exit or start key, the Commandaction method will execute the program exit processing separately or restart the next new game in the following code:

if (arg0 = = Exitcommand)//exit
Midlet.quit ();
else if (arg0 = = Newgamecommand)//Start Game
Initialize ();

   The realization of artificial intelligence

If the framework described above is the skeleton, the interface is flesh, then the next part of the artificial intelligence will be described as the entire program soul. It will conduct both sides of the lazi of legality detection, computer chess intelligent calculation, game end detection and the outcome of the decision-making work. All of these need to have a reasonable design in order to achieve a higher efficiency of game operation. Considering that the rules of the game are always arranged around the arrangement of the two pieces, it is possible to design the checkerboard grid as the main factor. From left to right, from top to bottom, the board's 9 grids are numbered from 0, and the following sets of winning conditions can be obtained: 0,1,2;3,4,5;6,7,8;0,3,6;1,4,7;2,5,8;0,4,8;2,4,6. As long as one party has three pieces in a position that matches any one of them, it can be assumed that the party wins (readers may verify on paper). In the process of implementation, the WINS array is recorded to record the above-mentioned winning conditions, and after each line of chess after the completion of the comparison to determine whether the game has the winner. Confined to space, the following mainly on the computer line chess ideas of artificial intelligence design introduced.

First clear the purpose of the computer game: win, if temporarily unable to win the player will be prevented from winning, if both sides are temporarily unable to win the following some "chess". After calculating the appropriate down position, add it to your own line chess record (replay) for later use. This allows you to write the following code:

int move = Getwinningcomputermove ()//If you can win immediately, you will be in the winning position.
if (move = =-1) {
If the player is about to win, the player will win the position.
move = Getrequiredblockingcomputermove ();
if (move = =-1)//If both parties are temporarily unable to win then chess is handy
move = Getrandomcomputermove ();
}
Computerstate |= bit (move); All locations occupied by the current computer

The Getwinningcomputermove method uses an enumeration of all possible bottom positions (that is, a mesh that has not yet been lazi) and intelligently determines where the next step of the computer can be won:

int move =-1;
for (int i = 0; i < 9;++i) {
if (Isfree (i) && Iswin (computerstate | bit (i))) {
move = i; Break when the winning position is found
Break
}
}

If the loop is still not found to win the position is currently unable to win, you need to further call the Getrequiredblockingcomputermove method to calculate the next round if the other has no chance of winning, The implementation code is exactly similar to Getwinningcomputermove, except that the chess record of the player playerstate the alternative computer computerstate. The above few lines of code constitute the computer chess algorithm, the core of artificial intelligence, it is obvious that artificial intelligence is not as complex and difficult as imagined.

   Summary

Through the introduction of this series of articles, the general development process of J2ME mobile phone application has been introduced to readers in a systematic and comprehensive way. In particular, the introduction of graphic mobile phone game is sure to have a different degree of inspiration to the reader, and the program framework described in this article is completely universal, the reader only need to redesign the game script on this basis to achieve similar mobile games such as "Huarong", "Tetris" and so on. The development environment for this series of articles is:

Windows Professional + SP4;
JAVA2SDK 1.5.0;
J2ME Wireless Toolkits 2.1;
Sonyerisson j2me SDK (WTK 1.0.4);
Sonyerisson T628;
Eclipse 3.0.1-win32;
Eclipseme 0.5.5;
Nlpack-eclipse-sdk-3.0.x-win32

From:http://www.yesky.com/softchannel/72342371878043648/20050409/1933394_1.shtml

Related Article

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.