Java mobile game programming MIDP graphics design

xiaoxiao2021-03-06  73

Introduction

This article briefly describes the MIDlet graphic programming by a simple MIDlet gaming program, in order to help developers deeply understand the MIDP graphics programming and develop complex mobile games.

One. MIDlet graphics

1, MIDlet graphic

Mobile Information Device Profile (MIDP) defines a set of application programming interfaces (APIs) for MIDlet applications running in the MIDP container. This set of APIs itself is based on the Connected Limited Device Configuration, CLDC application programming interface. The MIDP user interface application programming interface class is not based on the Java Abstract Window Toolkit, AWT. They are designed for small mobile information devices such as mobile phones and envelopes, and such devices are characterized by only small screens and keyboards. When a programmer is writing the MIDP graphics application, he may only use the MIDP or CLDC application programming interface.

The center of MIDP is the screen. The meaning of this sentence is that the MIDP user interface design is screen-based (screen-based). That is, the Screen class encapsulates the device-specific graphics and user interactions, all user interface components are on the screen and only one screen is displayed at a time, and can only browse or use the entries on this screen. All user interface events are processed by the screen. And only send advanced events to your application. The reason why this screen-oriented, mainly because the display screen of mobile devices and the keyboard are too much type, and almost every manufacturer is small. 1 is some examples of the screen-based MIDP graphical user interface.

Figure 1: Screen-based MIDP graphical user interface

The MIDP application programming interface has advanced user interface classes and low-level user interface classes. Advanced User Interface classes (such as Form, List, TextBox, TextField, Alert, and Ticker) can be adapted to the device: support image, text, text input field, radio button, etc. Low-level user interface classes (CANVAS classes) allow developers to draw arbitrary graphics as needed. MIDlet can run on a variety of different sizes of colors, different grades or black and white screens. Advanced User Interface Class is an abstraction of a general user interface element, which is to improve the portability of MIDLET across different devices and can use the appearance of the local equipment. Low-level application programming interfaces can control display content more directly, but the MIDlet designer should ensure that it is portable in different devices (display size, keyboard, color, etc.). The above example is used in both the advanced application programming interface and the low-level application programming interface.

All MIDP graphical user interface classes are part of the javax.microedition.lcdui package.

2, MIDlet screen

MIDP has two main screen types:

A Advanced Screen

It includes a simple advanced screen class, such as List and TextBox. Users cannot add additional graphical user interface components to this type of screen. The screen used by the Nine-Town Midlet sample program is inherited to the list class named choosepiecescreen, which is used to select a chess piece when the player starts at the start of the game.

The general FORM screen class and the List class are very similar, but it allows additional graphic elements, such as images, read-only text domains, editable text domains, editable data fields, ruler, and option groups. The Form entry can be arbitrarily added or deleted. There is no FORM class in the Jiuguan Rig.

B low-level screen

The Canvas screen (and Graphics, Image classes) can be used to write a user interface based on a low-level application programming interface. These classes give MIDLET programmers to a large extent of painting flexibility. Programmers can draw various types of graphical elements, such as lines, arcs, rectangles, rounded rectangles, circles, text (different colors, fonts, sizes), bitmap clips, etc. Most game MIDlets are written using the main graphical user interface elements based on the canvas screen class. A MIDLET user interface typically contains one or more screens. Because only one screen can be displayed each time, the MIDlet has a well-designed structure that is very important, so it can handover the contents between the screens between the screens.

The following code segment illustrates the method of switching the screen in a MIDLET, based on the screen class and the corresponding MIDlet callback.

Code segment 1:

Class Mymidlet Extends MIDLET

{

PRIVATE FIRSCREEN FIRSCREEN

Private secondscreen secondscreen

Public mymidlet ()

{

...

}

Public void startApp ()

{

Displayable current = display.getdisplay (this) .getcurrent ();

IF (current == null)

{

Firstscreen = New firstscreen (this, ...);

Display.getdisplay (this) .SetCurrent (FirstScreen);

// Display the first user interface screen of the application

}

Else

{

Display.getdisplay (this) .SetCurrent (current);

}

}

// firstscreen callback switch to the next screen

Public void firstscreenDone ()

{

...

Secondscreen = new secondscreen (this, ...);

Display.getdisplay (this) .SetCurrent (Secondscreen);

}

// Secondscreen callback termination application

Public void secondscreenquit ()

{

...

DESTROYAPP (FALSE);

NotifyDestroyed ();

}

...

}

This MIDlet uses two screen classes (FirstScreen and Secondscreen as the user interface. When you start executing MIDlet, it sets the current display screen for Firstscreen. When you need to switch from Firstscreen to Secondscreen, FirstScreen calls the parent MIDlet method firstScReendone (see the code below). The firstScreenDone method creates and sets SecondScreen as the current displayed screen.

Code segment 2: FirstScreen example containing MIDlet callbacks

Class firstscreen extends form imports commandlistener {

Private mymidlet MIDlet;

Public firstscreen (MyMIDlet MIDLET)

{

this.midlet = MIDLET;

...

}

Public void CommandAction (Command C)

{

IF (c == cmdquit)

{

Parent.firstscreendone ();

}

...

}

...

}

3, MIDP user interface application programming interface

Ensure that the portability and applicability of user interface objects based on advanced application programming interface classes are the responsibility of the MIDP device.

On the other hand, low-level classes such as Canvas and Graphics provide a larger free space to control their user interface visual performance, and listen to the low-level keyboard events. The programmer is also responsible for ensuring portability on mobile devices in different features such as display size, color or black and white, and different keyboard types. For example, it is possible to use the getWidth () and getHeight () methods to adjust the user interface to adapt to one or more devices available canvas size. The following nine-rich MIDlet routine will be introduced:

Simple application advanced application programming interface;

Use the low-level application programming interface to draw graphics such as lines, arcs, strings, and images;

MIDlet transplantation between mobile devices of different display sizes

Map between keyboard code and game action

This chapter outlines the design of the MIDP graphical user interface. If you want to get further information, see

http://java.sun.com/products/midp/.

2. Example: TictactoemIdlet

1, design

Overview

This sample application is a simple MIDLET that allows the player to play a man-machine game called Nine-pace between the MIDLET program. This routine description:

Use advanced and low-level user interface components

Switch between multi-display screens

Handling simple command

Dynamic adaptation display size

Processing keyboard events

The player first chooses which piece of chess (represented by circle and fork) and starting the game. Who is the player and MIDlet who is random decision. After a while, the program must check the status of the game and determine if the game has ended. Several possible results of the game are: players win, MIDLET program wins, or a layout. During the operation of the application, the scores of both parties can be displayed. Gamers can start new games or exit games at any time.

Figure 2: The screen snapshot shown is the MIDlet user interface in the game.

Figure 2: Succession of the game screen

2, Nine Mao Hai MIDlet

Below is the class pattern of the nine-rich MIDlet:

Figure 3: Nine-pace MIDlet class diagram

When the MIDlet starts method startApp (), the flash screen and the first game screen are created. After the flash screen displays 4 seconds, the first game screen starts to display. ChoosepieceScreen let the player choose which piece of chess (circle or fork). When the player makes the choice, he can use the OK key to confirm. This will make ChoosePieceScreen call back to the choicepiecescreendone () method for the main MIDlet.

ChoosepieceScreen is implemented using the Advanced Application Programming Interface List class.

Figure 4: ChoosepieceScreen is a senior user interface List subclass

ChoosepieceScreenDone () callback creates and displays the next screen, this screen as the Game's main screen (Gamescreen) in this application.

Whenever the player goes chess, the player uses Gamescreen's arrow keys and SELECT buttons to select the space you want to walk. After each round, the application checks the status of the game and checks whether it meets the game end conditions and displays the game results. The player ends the game by clicking on Gamescreen's Quit Command, or starting a new round of games using the new command. Quit (end) The command calls the Quit () method of the TictActoemIdlet, and then the MIDlet will call the DestroyApp () method to terminate the entire MIDlet program.

Game program logic is packaged in a separate GAME class. This article only focuses on the graphic design of the MIDlet, and discusses the logic of the game program. If you want to compare with an existing Applet Java program, see http://java.sun.com/applets/jdk/1.0/demo/tictactoe/tictactoe.java and http://java.sun.com/products/ JFC / TSC / Articles / TICTACTOE / INDEX.html game program logic. Gamescreen is implemented by using low-level Canvas and Graphics classes. It draws graphics using Canvas, Image, and Graphics objects.

Gamescreen first initializes the display panel based on the canvas size. This allows MIDlet to run on mobile devices in different display screens. In this example, an Image object is used to represent the game panel. Then Gamescreen assigns chess pieces to the player and MIDlet based on the player choosing in ChoosepieceScreen. The game is then initialized (including random decision who is first hand), then the game begins.

In order to enable GameScreen to be ported, the MIDlet's keyboard code must be mapped to the game action, such as: Up, Down, Left, Right, and Fire, for mobile devices with different keyboards. Whenever a key is pressed, the keypressed () method determines that this is a direction button or a Fire / SELECT key. If the button is pressed, the cursor moves accordingly to help the player visually select a space into the chess pieces. The SELECT button is used to select a space to put it on the chess. If you detect a condition that meets the end of the game, you will display a message to announce the winner of the game and the score of this round. (See below)

Figure 5: Gamescreen is a lower CANVAS (canvas) subclass

3, TictActoemidlet.java

TictctoemIdlet is very simple: it handles the MIDlet lifecycle event. It creates a screen object as needed and processes callbacks from the screen. The ChoosepiecescReendone callback is used to create Gamescreen. The Quit method is used by Gamescreen to end the game.

Package example.tictactoe;

Import java.io.ioException;

Import javax.microedition.midlet. *;

Import javax.microedition.lcdui. *;

Import javax.microedition.io. *;

Public class tictactoemidlet extends midlet {

PRIVATECIEPIECESCREEN Choosepiecescreen

Private Gamescreen Gamescreen

Public TictActoemIdlet ()

{

}

Public void startapp () {

Displayable current = display.getdisplay (this) .getcurrent ();

IF (current == null) {

// First Time We've Been Called

// Get the logo image

Image logo = NULL;

Try

{

LOGO = Image.createImage ("/ tictactoe.png");

}

Catch (IOException E) {

// Just Use Null Image

}

Alert Splashscreen = New Alert (Null, "Tic-Tac-TiE Forum Nokia", LOGO, ALERTTYPE.INFO; SplashScreen.SetTimeout (4000);

// 4 seconds

Choosepiecescreen = new choisepiecescreen (this);

Display.getdisplay (this) .SetCurrent (SplashScreen, choosepiecescreen);

}

Else

{

Display.getdisplay (this) .SetCurrent (current);

}

}

Public void pauseApp () {

}

Public void destroyApp (boolean unconditional) {

}

Public void quit ()

{

DESTROYAPP (FALSE);

NotifyDestroyed ();

}

Public Void ChoosepieceScreendone (Boolean Isplayercircle)

{

Gamescreen = New Gamescreen (this, isplayercircle);

Display.getdisplay (this) .Setcurrent (Gamescreen);

}

}

4, choosepiecescreen.java

ChoosepieceScreen is a screen based on the advanced application programming interface form, allowing the player to select a circle or fork as a chess. When the player presses the OK button, it uses the MIDlet's callback method choosepiecescReendone to handle the player's choice.

Package example.tictactoe;

Import javax.microedition.midlet. *;

Import javax.microedition.lcdui. *;

Import javax.microedition.io. *;

Public Class Choosepiecescreen Extends List ImmancellListener

{

Private static final string circle_text = "circle";

Private static final string cross_text = "cross";

PRIVATE FINAL TICTACTOEMIDLET MIDLET;

PRIVATE FINAL QuitCommand;

Public choiecescreen (TictActoemidlet MIDlet) {

Super ("Choose Your Piece", List.Implicit;

this.midlet = MIDLET;

Append (Circle_Text, LoadImage ("/ circle.png"));

Append (cross_text, loadimage ("/ cross.png");

Quitcommand = New Command ("Quit", Command.exit, 2);

Addcommand (QuitCommand);

SetCommandListener (this);

}

Public void CommandAction (Command C, Displayable D) {

Boolean isplayercircle = getString (getSelectedIndex ()). Equals (Circle_Text);

IF (c == List.select_command) {midlet.choosepiecescreen (isplayercircle);

}

Else

// quit command

{

MIDlet.quit ();

}

}

Private image loading (String ImageFile)

{

Image image = NULL;

Try

{

Image = image.createImage (imagefile);

}

Catch (Exception E)

{

// Use a'Null' Image in The Choice List (I.E. Text Only Choices).

}

Return image;

}

}

5, Gamescreen.java

Gamescreen uses a low-level application programming interface CANVAS screen, and image, Graphics class to draw game panels, chess pieces, and final result of the game. To get more detailed information, see Various Painting Methods and DrawCircle, Drawcross, DrawPiece, DrawPlayerCursor, Drawboard. This screen uses MIDlet's Quit callback method to indicate the end of the game.

This screen adapts to a variety of available display performance (high, wide, color, etc.). Also note that you can use a four-way navigation key, or a two-way navigation key can be used to move the cursor.

It uses the GAME class that encapsulates the logic of the main player.

Package example.tictactoe;

Import java.util.random;

Import javax.microedition.midlet. *;

Import javax.microedition.lcdui. *;

Class Gamescreen Extends Canvas Implements CommandListener {

Private static final int black = 0x00000000;

Private static final int white = 0x00fffffff;

Private static final int = 0x00ff0000;

Private static final int blue = 0x000000FF;

PRIVATE STATIC FINAL INT NO_MOVE = -1;

PRIVATE FINAL TICTACTOEMIDLET MIDLET;

PRIVATE FINAL GAME GAME;

PRIVATE FINAL Command EXITCOMMAND;

PRIVATE FINAL Command NewGameCommand;

PRIVATE FINAL RANDOM = New Random ();

Private int Screenwidth, ScreenHeight;

Private Int Boardcellsize, Boardsize, Boardtop, BoardLeft

Private Boolean Playeriscircle;

Private Boolean Computerism;

Private int precursorposition, cursorposition;

Private int computermove = no_move;

Private Int Playermove = NO_MOVE;

Private Int computeGameswontally = 0;

Private Int Playergameswontally = 0;

Private boolean isrestart;

Public Gamescreen (TictActoemIdlet MIDlet, Boolean Playeriscircle) {this.midlet = MIDLET;

This.Playeriscircle = Playeriscircle;

Computeriscircle =! Playeriscircle;

Game = new game (random);

INITIALIZEBOARD ();

// Configure Screen Commands

EXITCOMMAND = New Command ("EXIT", Command.exit, 1);

NewgameCommand = New Command ("New", Command.Screen, 2);

Addcommand (EXITCOMMAND);

Addcommand (NewGameCommand);

SetCommandListener (this);

// begin the game play initialize ();

}

// Initialize the game and game screen. Also use for game restarts.

Private vidinitialize () {

Game.initialize ();

PrecursorPosition = CursorPosition = 0;

Playermove = no_move;

Boolean computerfirst = ((random.nextint () & 1) == 0);

IF (Computerfirst) {

Computermove = Game.makeComputermove ();

}

Else

{

Computermove = NO_MOVE;

}

Isrestart = true;

Repaint ();

}

Public void paint (graphics g) {

IF (Game.ISGameOver ()) {

PaintGameOver (g);

}

Else {

Paintgame (g);

}

}

Private void PaintGame (Graphics g) {

IF (isrestart) {

// Clean the Canvas

G.SetColor (White);

g.fillRect (0, 0, ScreenWidth, ScreenHeight);

Drawboard (g);

Isrestart = false;

}

Drawcursor (G);

IF (Playermove! = NO_MOVE) {

Drawpiece (G, Playeriscircle, Playermove) and PLAYERMOVE

}

IF (Computermove! = NO_MOVE) {

Drawpiece (G, ComputerInscircle, ComputerMove);

}

}

Private void PaintGameOver (Graphics G)

{

String statusmsg = null;

IF (Game.isComputerwinner ()) {

Statusmsg = "i win!";

ComputerGameSwontAlly ;

}

Else IF (Game.IsPlayerwinner ()) {

STATUSMSG = "you win";

PlayERGAMESWONTALLY ;

}

Else {

Statusmsg = "stalemate";

}

String Tallymsg = "You:" Playergameswontally "ME:" ComputerGameSwontally; font font = font.getfont (font.face_system, font.style_plain, font.size_medium);

Int strheight = font.getHeight ();

Int statusmsgwidth = font.stringwidth (statusmsg);

INT Tallymsgwidth = font.stringwidth; Tallymsg);

Int strWidth = Tallymsgwidth;

IF (statusmsgwidth> TallyMsgwidth)

{

Strwidth = statusmsgwidth;

}

// Get the

{

X, Y

}

Position for painting the strings. INT x = (ScreenWidth - Strwidth) / 2;

X = x <0? 0: x;

INT Y = (ScreenHeight - 2 * strheight) / 2;

Y = y <0? 0: y;

// Clean the Canvas

G.SetColor (White);

g.fillRect (0, 0, ScreenWidth, ScreenHeight);

// Paint the strings' Text

G.SetColor (Black);

g.drawstring (statusmsg, x, y, (graphics.top | graphics.Left);

g.drawstring (Tallymsg, X, (Y 1 strheight), (graphics.top | graphics.Left);

}

Public void CommandAction (Command C, Displayable D) {

IF (c == EXITCOMMAND) {

MIDlet.quit ();

}

Else if (c == newgameCommand) {

Initialize ();

}

}

Private vid initializeboard () {

ScreenWidth = getWidth ();

ScreenHeight = GetHeight ();

IF (ScreenWidth> ScreenHeight) {

Boardcellsize = (ScreenHeight - 2) / 3;

BoardLeft = (ScreenWidth - (BoardCellsize * 3) / 2;

Boardtop = 1;

}

Else {

Boardcellsize = (ScreenWidth - 2) / 3;

BoardLeft = 1;

Boardtop = (ScreenHeight - Boardcellsize * 3) / 2;

}

}

protected void keypressed (int keycode) {

// can't Continue Playing Until The Player Restarts

IF (Game.ISGameOver ()) {

Return;

}

INT GameAction = getGameAction (keycode);

Switch (gameAction) {

Case Fire: DOPLAYERMOVE ();

Break; Case Right: Domovecursor (1, 0);

Break;

Case Down: Domovecursor (0, 1);

Break;

Case Left: Domovecursor (-1, 0);

Break;

Case Up: DomoveCursor (0, -1);

Break;

DEFAULT: BREAK;

}

}

Private void doplayermove () {

IF (Game.isFree (CursorPosition)) {

// Player Move Game.

MakePlayermove (CURSORPSITION);

Playermove = CURSORPSITION;

// COMPUTER MOVE

IF (! game.isgameOver ()) {

Computermove = Game.makeComputermove ();

}

Repaint ();

}

}

Private void Domovecursor (int dx, int dy) {

INT newcursorposition = CURSORPSITION DX 3 * DY;

IF (NEWCURSorPosition> = 0) && (NewCursorPosition <9))

{

PrecursorPosition = CursorPosition;

Cursorposition = NewcursorPosition;

Repaint ();

}

}

// Draw a circle or cross piece on the board

Private Void Drawpiece (Graphics G, Boolean ISCIRCLE, INT POS) {

INT x = ((POS% 3) * Boardcellsize 3;

INT Y = ((POS / 3) * BoardcellSize 3;

IF (iScircle) {

Drawcircle (G, X, Y);

}

Else {

Drawcross (g, x, y);

}

}

// Draw Blue Circle ONTO The Board Image

Private Void Drawcircle (Graphics G, INT X, INT Y) {

g.setcolor (blue);

G. Fillarc (x BoardLeft, Y Boardtop, Boardcellsize - 4, Boardcellsize - 4, 0, 360);

G.SetColor (White);

G.fillarc (x 4 BoardLeft, Y 4 Boardtop, Boardcellsize - 4 - 8, Boardcellsize - 4 - 8, 0, 360);

}

// Draw Red Cross Onto the Board Image

Private void Drawcross (Graphics G, INT X, INT Y) {

g.setcolor (red);

For (int i = 0;

i <4;

i ) {

G. Drawline (x 1 i BoardLeft, Y Boardtop, X Boardcellsize - 4 - 4 i BoardLeft, Y BoardCellsize - 5 Boardtop);

G. Drawline (x 1 i BoardLeft, Y Boardcellsize - 5 Boardtop, X Boardcellsize - 4 - 4 i BoardLeft, Y Boardtop);

}

// Visually Indicates a Player SELECTED SQUARE ON THE BOARD Image

Private Void Drawcursor (Graphics G) {

// Draw Cursor at successd Player Square.

G.SetColor (White);

G.drawRect ((PrecursorPosition% 3) * Boardcellsize 2 BoardLeft, (PrecursorPosition / 3) * Boardcellsize 2 Boardtop, Boardcellsize - 3, Boardcellsize - 3);

// Draw Cursor at successd Player Square.

G.SetColor (Black);

g.drawRect ((CursorPosition% 3) * Boardcellsize 2 BoardLeft, ((CursorPosition / 3) * Boardcellsize) 2 Boardtop, Boardcellsize - 3, Boardcellsize - 3);

}

Private void Drawboard (Graphics g) {

// Clean the Board

G.SetColor (White);

g.fillRect (0, 0, ScreenWidth, ScreenHeight);

// Draw the Board

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);

}

}

}

6, Game.java

This class encapsulates the main game program logic of the Jiugue game. As we have said, the game program logic itself is not within the scope of this routine, this paper is mainly introducing the basics of MIDP graphics programming. The game program logic's WINS array part is from http://java.sun.com/applets/jdk/1.0/demo/tictactoe/tictactoe.java this classic routine.

Note that the game program logic is independent of the game user interface (see class GameScreen), and other implementation methods can be used instead.

Package example.tictactoe;

Import java.util.random;

Import javax.microedition.midlet. *;

Import javax.microedition.lcdui. *;

// the game logic for tictactoe

Class game {

Private static final int [] WINS = {

// Horizontals

Bit (0) | Bit (1) | Bit (2),

Bit (3) | Bit (4) | Bit (5),

Bit (6) | Bit (7) | Bit (8),

// Verticals

Bit (0) | Bit (3) | Bit (6), Bit (1) | Bit (4) | Bit (7),

Bit (2) | Bit (5) | Bit (8),

// diagonals

Bit (0) | Bit (4) | Bit (8),

Bit (2) | Bit (4) | Bit (6)}

;

Private static final INT DRAWN_GAME = Bit (0) | Bit (1) | Bit (2) | Bit (3) | Bit (4) | Bit (5) | Bit (6) | Bit (7) | Bit (8) ;

Private int playerstate;

Private int computerstate;

Private random

Game (Random Random) {

this.random = random;

Initialize ();

}

Voidinitialize () {

Playerstate = 0;

Computerstate = 0;

}

Boolean isfree (int position) {

INT bit = bit (position);

Return ((Playerstate & Bit) == 0) && (Computerstate & Bit) == 0));

}

// The'Contract' Is That Caller Will Always Make Valid Moves.

// We don't check what it's the player's Turn.

Void makeplayermove (int position) {

Playerstate | = bit (position);

}

// the'contract' Is That We Will Be Called ONLY WHEN THERE IS STILL

// at Least One Free Square.

Int makecomputermove () {

Int move = getwinningcomputermove ();

IF (Move == -1) {

// can't win

Move = getRequiredBlockingComputerMove ();

IF (Move == -1) {

// Don't Need to Block

Move = getrandomputermove ();

}

}

Computerstate | = bit (move);

Return Move;

}

Boolean isgameOver () {

Return isplayerwinner () | iScomputerwinner () | IsgameDRawn ();

}

Boolean isplayerwinner () {

Return iswin (Playerstate);

}

Boolean ISComputerwinner () {

Return iswin (computerstate);

}

Boolean isgamedrawn () {

Return (Playerstate | Computerstate == DRAWN_GAME;

}

// Return A Winning Move if The Is At Least One, OtherWise Return -1

Private int getwinningcomputermove () {

INT move = -1;

For (int i = 0;

i <9;

i) {

IF (IsFree (i) && iswin (Computerstate | Bit (i)))) {move = i;

Break;

}

}

Return Move;

}

// Return a Required Blocking Move IF The Is At Least One (More

// one and we've inevitably lost, OtherWise Return -1

Private Int getRequiredBlockingComputermove () {

INT move = -1;

For (int i = 0;

i <9;

i) {

IF (ISFree (i) && iswin (Playerstate | Bit (i))) {

Move = i;

Break;

}

}

Return Move;

}

// Return A Random Move In a Free Square, // Or Return -1 IF None Are Available Private INT getrandomComputerMove () {

INT move = -1;

// DETERMINE How Many Possible Moves There Are Int NumFreesquares = 0;

For (int i = 0;

i <9;

i) {

IF (IsFree (i)) {

Numfreesquares ;

}

}

// if there at Least One Possible Move, Pick Randomly

IF (NumFreesquares> 0) {

// shift twice to get rid of sign bit, THEN MODULO NUMFREESQUARES

INT PICK = ((random.nextint () << 1) >>> 1)% NumFreesquares;

// now Find the chosen free square by counting pick down to zero

For (int i = 0;

i <9;

i) {

IF (IsFree (i)) {

IF (pick == 0) {

Move = i;

Break;

}

Pick -;

}

}

}

Return Move;

}

Private static boolean iswin (int state) {

Boolean iswinner = false;

For (int i = 0;

I

i) {

IF (State & Wins [I]) == WINS [I]) {

Iswinner = true;

Break;

}

}

Return iswinner;

}

Private static int bit (INT I) {

Return 1 << i;

}

}

7, Tictactoe.jad

Below is the application description file of the Nine-rich MIDlet.

MIDlet-name: TictActoe

MIDlet-vendor: Forum Nokia Midlet-Version: 1.1.1

MIDlet-jar-size: 11409

MIDlet-jar-url: Tictactoe.jar

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

New Post(0)