65.9K
CodeProject 正在变化。 阅读更多。
Home

J2ME 随机数游戏

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (2投票s)

2011 年 7 月 18 日

CPOL

3分钟阅读

viewsIcon

31378

downloadIcon

2338

使用 J2ME 技术开发一个随机数游戏。

Sample Image - maximum width is 600 pixels

Sample Image - maximum width is 600 pixels

Sample Image - maximum width is 600 pixels

Sample Image - maximum width is 600 pixels

引言

本文演示了如何使用Java 2 Micro Edition平台 (J2ME) 开发一个随机数游戏。本文将简要介绍使用J2ME开发实用应用程序的简易性。这不是对J2ME的深入讨论。假设读者具备Java语言编程的工作知识。

背景

J2ME是一个基于Java的平台,用于开发能够在小型设备(最常见的是移动电话)上运行的应用程序。使用J2ME,任何人都可以轻松地开发可在移动设备上运行的有用Java应用程序。这些应用程序称为MIDlet,由移动设备中内置的应用程序管理软件 (AMS) 管理。J2ME应用程序在一个模拟器上执行。构建J2ME应用程序时,会创建两个文件,一个扩展名为JAR,另一个扩展名为JAD。JAR文件是一个包含MIDlet类的存档文件,JAD文件是一个描述JAR文件的描述符文件。可以通过将这两个文件复制到设备上来在支持Java的移动设备上执行该应用程序。

MIDlet在其生命周期中经历以下状态:

  • 暂停
  • 启动
  • 销毁

初始状态为暂停状态。AMS激活midlet并调用其startApp()方法,使其进入启动状态。destroyApp()方法用于销毁midlet。一个布尔参数传递给destroyApp()方法,以指示销毁是无条件的还是可选的。可选销毁可以通过抛出MIDletStateChangeException来取消。

Using the Code

每个MIDlet都需要两个主要包:javax.microedition.midletjavax.microedition.lcdui。在J2ME中,abstract Display类表示主显示屏,表单类表示可以显示在屏幕上的许多表单之一。可以通过实现CommandListener接口来实现处理命令。CommandListener接口声明了commandAction()方法,该方法必须由MIDlet类实现。

package azim;			// Main package

import javax.microedition.midlet.*;	// Contains definition for the MIDlet class
import javax.microedition.lcdui.*;	// Contains definition for common 
				// user interface elements
import java.util.*;		// For the Random class

public class RandomMidlet extends MIDlet implements CommandListener
{

    Form form;				// Represents the main form
    Display display;			// Represents the main display screen
    TextField txtNumber			// Text field to accept input from user.
    Command cmdCheck,cmdExit,cmdAbout;	// Commands to perform processing
    int x,ctr;				// Number and counter

startApp()方法用于创建MIDlet的用户界面并注册commandListenerRandom类的nextInt()方法返回介于0和传递给它的参数之间的值。

public void startApp()
{
    x=new Random().nextInt(101);			// Generating a random number
    ctr=0;					// Initializing the counter
    form=new Form("Number Guess Game");		// Initializing the form with title
    display=Display.getDisplay(this);		// Initializing the display
    txtNumber=new TextField("Enter a number 
		(Between 0 and 100)", "", 10, TextField.NUMERIC);
						// Accepting number
    cmdCheck=new Command("Check",Command.OK,1);	// Initializing command
    cmdExit=new Command("Exit",Command.EXIT,3);	// Initializing command
    cmdAbout=new Command("About",Command.HELP,4);	// Initializing command
    form.append(txtNumber);			// Adding TextField on form
    form.addCommand(cmdCheck);		// Adding Command
    form.addCommand(cmdExit);		// Adding Command
    form.addCommand(cmdAbout);		// Adding Command
    form.setCommandListener(this);		// Adding Command
    display.setCurrent(form);		// Displaying Form
}

实现其他生命周期方法。

public void pauseApp()
{
}

public void destroyApp(boolean unconditional)
{
    notifyDestroyed();
}

实现commandAction()方法。commandAction()方法接收两个参数。Command参数表示启动该进程的源命令,Displayable参数表示发生事件的对象。

Alert对象用于在对话框中显示消息。Alert构造函数的第一个参数是标题。第二个参数是要显示的消息。第三个参数表示要显示的图像。第四个参数是警报类型。

public void commandAction(Command c,Displayable d)
    {
        if(c==cmdCheck)				// Check command was selected
        {
            if(txtNumber.getString().trim().length()==0)// Return if no input given
            {
                return;
            }
            Alert alert=null;
            int n=Integer.parseInt(txtNumber.getString());// Get number entered by user
            ctr++;					// Increment counter
            if(n<x)
            {
                alert=new Alert("Not quite","Try a larger value ",null,AlertType.WARNING);
		// Show error if entered number is less than the guessed number
            }
            else if(n>x)
            {
                alert=new Alert("Not quite","Try a smaller value ",null,AlertType.WARNING);
		// Show error if entered number is greater than the guessed number
            }
            else
            {
                alert=new Alert("You got it","Congrats!!! 
		You have made it in "+ctr+" attempts.",null,AlertType.INFO);
			// Show success message if entered number is equal to 
			// the guessed number
                x=new Random().nextInt(101);	// Generate new random number
                ctr=0;			// Reset counter
            }
            alert.setTimeout(Alert.FOREVER);  // Specify alert to be displayed until closed.
            display.setCurrent(alert);	// Display alert
        }
        if(c==cmdExit)
        {
            destroyApp(true);		// Destroy MIDlet if Exit command selected
        }
        if(c==cmdAbout)
        {
            Alert alert=new Alert("About Random Game",
			"Programmed by Azim",null,AlertType.INFO);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);	// Display About information
        }
    }
}

关注点

我使用Java(TM) ME Platform SDK 3.0开发了此应用程序。其他环境,如Netbeans和Sun Java (TM) Wireless Toolkit 2.5.2_01 for CLDC,也可以用于开发J2ME应用程序。运行应用程序时,输出显示在模拟器上。可以通过将生成的JAD和JAR文件复制到设备上来在支持Java的移动设备上执行该应用程序。

历史

  • 2011年7月15日:初始版本
© . All rights reserved.