⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 community.java

📁 j2me编写的一个在线游戏
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
/* ------------------------------------------------------------------------- *          Copyright 2004-2005 Nokia Corporation  All rights reserved.          Nokia Mobile Phones          Restricted Rights: Use, duplication, or disclosure by the          U.S. Government is subject to restrictions as set forth in          subparagraph (c)(1)(ii) of DFARS 252.227-7013, or in FAR          52.227-19, or in FAR 52.227-14 Alt. III, as applicable.          This software is proprietary to and embodies the          confidential technology of Nokia Possession, use, or copying          of this software and media is authorized only pursuant to a          valid written license from Nokia or an authorized          sublicensor.          Nokia  - Wireless Software Solutions * ------------------------------------------------------------------------- */package samples.commui;import com.nokia.sm.net.ItemList;import com.nokia.sm.net.ServerComm;import com.nokia.sm.net.SnapEventListener;import samples.ui.*;import javax.microedition.lcdui.Canvas;import javax.microedition.lcdui.Display;import javax.microedition.lcdui.Image;import java.util.Random;import java.util.Vector;/** * Main manager class for MazeRacer sample game functionality. * <p> * Primary responsiblities include: management of SNAP session * and all communication with SNAP servers, including sending  * events and intercepting results and errors; management of  * the various screens in the app GUI; and storage and management * of all screen-independent user and game data. */public class Community implements AsyncCommandListener, SnapEventListener, ButtonListListener, EventListener, Runnable {    public static Community instance;    public static final String CHALLENGE_PREFIX = "+++ ChAlLeNgE +++: ";    public static final String NON_CRITICAL = "non-critical";    static final int    MAX_NEW_ACCOUNTS_PER_DAY= 5;        private static final Random rnd = new Random();    static public final Image FADING_BACKGROUND  = ResourceManager.getImage("/fading_background.png");    static final Image OVERLAY_BACKGROUND = ResourceManager.getImage("/overlay_background.png");    static final Image SELECTED_SECTION   = ResourceManager.getImage("/selected_section.png");    static final Image SPLASH_IMG         = ResourceManager.getImage("/device_splash.png");        static final String About_txt 		  = "/about.txt";    static String Motd_txt 		  			= "/motd.txt";    static final String Game_Help_txt 	  = "/game_help.txt";    static final String SM_Help_txt 	  = "/sm_help.txt";    static final String Operator_Help_txt = "/operator_help.txt";    static final String SPLASH              = "Splash";    static final String GAME                = "Game";    static final String MOTD                = "Message of the day";    static final String WELCOME				= "Welcome";    static final String GO_ONLINE           = "go online";    static final String SINGLE_USER         = "single user game";    static final String ABOUT				= "about";    static final String CREATE_ACCOUNT      = "create account";    static final String DIALOG              = "Dialog";    static final String CHAT                = "chat messages";    static final String FRIENDS             = "Friends";    static final String HOME                = "Home";    static final String PLAY                = "Play";    static final String PENDING_GAMESTART   = "Waiting for player";    static final String RANKING             = "rankings";    static final String TOP_10              = "Top 10";    static final String MY_RANKINGS         = "My Rankings";    static final String STATS               = "Stats";    static  String HELP                		= "help";    static final String SM_HELP             = "SNAP Mobile Help";    static final String GAME_HELP           = "Game Help";    static final String OPERATOR_HELP       = "Operator Help";    static final String EMAIL_DOB           = "E-mail & Birthdate";    static final String USER_PASS           = "Username & Password";    static final String TERMS               = "Terms";    static final String SUBMIT_SCORES       = "SubmitScores";    static final String SELECT              = "select";    static final String SEND                = "send";    static final String CANCEL              = "cancel";    static final String BACK                = "back";    static final String MAZEEXIT          	= "mazeexit";    static final String EXIT                = "exit";    static final String REALLY_EXIT         = "exit!";    static final String LOGIN               = "login";    static final String LOGOUT              = "log out";    static final String REALLY_LOGOUT       = "log out!";    static final String NEXT                = "next";    static final String OK                  = "ok";    static final String YES                 = "yes";    static final String NO                  = "no";    static final String RMS_USERNAME        = "userName";    static final String RMS_PASSWORD        = "passWord";//    static final String RMS_SAVE_PASSWORD   = "savePass";    //  GUI data    private ViewCanvas canvas;    private MazeRacer mazeRacer;    private Vector cmdList;    private BuddyList buddyList;    private String[] statList;    private boolean inGame;    //Snap specific data    private String webSessionID;    private String impsSessionID;    private String snapSessionID;    private String snapUserID;    private ServerComm comm;    private Vector viewList;    private View motd;    private MainApp main;    private String lastError;    private int lastErrorSeverity;    private Integer gcid;    private String operatorId;    private boolean done;    private boolean waitingForGame;    private AsyncCommandListener asyncListener=null;    private String asyncCommand=null;    private boolean		inGameReg			= false;    private boolean		saveLogin			= false;    // User login/registration info -- save here for later retrieval    // if login/registration screens are revisited after errors take the    // user back to the main menu.  (Upon return to the main menu, the    // registration screens are destroyed, and recreated from scratch    // if revisited -- so previously entered data must be saved here    // if it is to be retained.)    public String       username            = "";    public String       password            = "";    public String       password2           = "";    public String       dateOfBirth         = "";    public String       emailAddress        = "";    public int          minAge              = 13;    /** Returns <code>com.nokia.sm.net.ServerComm</code> instance. */    public ServerComm getServerComm()       { return comm; }    protected int       getMinAge()             { return minAge; }    protected MainApp   getMainApp()            { return main; }    /**     * Sets user's SNAP session IDs.     *     * @param returnValues an ItemList returned from a SNAP login command.     */    public void setLoginInfo(ItemList returnValues)    {        if (returnValues == null) return;        setLoginInfo(        		returnValues.getString("webSessionID"),        		returnValues.getString("impsSessionID"),        		returnValues.getString("snapSessionID"),        		returnValues.getString("snapUserID")        	);    }    /**     * Sets user's SNAP session IDs.     *     * @param webSessionID     * @param impsSessionID     * @param snapSessionID     * @param snapUserID     */    public void setLoginInfo(String webSessionID, String impsSessionID, String snapSessionID, String snapUserID) {        this.webSessionID = webSessionID;        this.impsSessionID = impsSessionID;        this.snapSessionID = snapSessionID;        this.snapUserID = snapUserID;    }    /*     * =======================================================================     *  Instance lifecycle methods: static initializer, constructor, pause     *  resume and exit methods.     * =======================================================================     */    /**     * Calls static initializers on View and SnapLoginView.     */    static void initialize() {        CommunityView.initialize();        View.initialize();        BuddyView.initialize();        ButtonListView.initialize();        Chat.initialize();        Dialog.initialize();        LoginView.initialize();        RankingView.initialize();        TextView.initialize();    }    /** Loads SNAP properties from .jad file */    protected void loadSnapProperties()    {        try { minAge 	= Integer.parseInt( main.getProperty("SNAP-Mobile-MinAge")); } catch (Exception e) {}        String reg 		= main.getProperty("SNAP-Mobile-InGameReg");        String save 	= main.getProperty("SNAP-Mobile-SaveLogin");        if (reg  != null) inGameReg = reg.equals ("true");        if (save != null) saveLogin = save.equals("true");	    }    /**     * Constructor.  Loads settings from .jad file.  Performs network     * connectivity check if connectivity has not been established in the     * past.  Then, instantiates and displays LoginView screen.     *     * @param main Reference to caller's code, via the <code>MainApp</code>     *  interface.  This reference is used to return control back to the     *  calling code once login and/or registration are complete, by means     *  of the handleEvent() method.     */    public Community(MainApp main) {        this.main = main;        cmdList = new Vector();        viewList = new Vector();        buddyList = new BuddyList();        gcid = new Integer( 49721);        username = "";        View splash = getView(SPLASH);        splash.setActive(true);        canvas = new ViewCanvas(splash);        Display.getDisplay(main.getMIDlet()).setCurrent(canvas);        canvas.waitForResize();        mazeRacer = new MazeRacer(this);        inGame = false;        waitingForGame = false;        lastError = null;        lastErrorSeverity = -1;        initialize();        // Note: set to true in order to force initialization of the        // network connection early, in the ServerComm constructor.        boolean initializeNetwork = false;        System.out.println("server url:" + main.getProperty("SNAP-Mobile-Host"));        System.out.println("server port:" + Integer.parseInt(main.getProperty("SNAP-Mobile-Port")));        System.out.println("protocol:" + main.getProperty("SNAP-Mobile-Protocol"));        System.out.println("*** Note:  Set 'Small-Maze' parameter in .jad file to 'true' to play with a smaller (faster) maze.");        try {	        comm = new ServerComm(	                main.getProperty("SNAP-Mobile-Host"),	                Integer.parseInt(main.getProperty("SNAP-Mobile-Port")),	                main.getProperty("SNAP-Mobile-Protocol"),	                Integer.parseInt(main.getProperty("SNAP-Mobile-SKU")),	                initializeNetwork	        	);            comm.addSnapEventListener(this);//            switchToView(WELCOME);    	} catch (RuntimeException r) {            // Check for SecurityExceptions (see if user            // pressed "no" to the GPRS permissions dialog popup.)            // If so, tell them to exit app and restart.  Note:            // ServerComm takes the summary of CheckedExceptions,            // then rewraps them as RuntimeExceptions before            // rethrowing, so we need to check for the name of the            // original exception inside the body of the Runtime            // Exception.    		if (r.toString().toLowerCase().indexOf("security")!=-1) {        		showError(        				"Unable to connect to network.  You must " +        				"press 'YES' in the GPRS/Airtime Permissions " +        				"dialog.  Please exit app and restart.",        				Community.REALLY_EXIT, Dialog.ALERT        				);    		}    	}        operatorId = getProperty("SNAP-Mobile-OperatorID");        int count = Integer.parseInt(getProperty("Stat-Count"));        statList = new String[count];        for (int i=0; i<statList.length; i++) {            statList[i] = getProperty("Stat-" + (i + 1));        }        Thread thread = new Thread(this);        thread.start();        instance = this;    }    public void pause()    {    	mazeRacer.pause();    }    public void resume()    {    	mazeRacer.resume();    }    /**     * Saves username/password if login saving is enabled, and is checked     * "on" by the user. Then, returns control back to calling code via the     * <code>handleEvent()</code> method of the     * <code>com.nokia.sm.miniui.EventHandler</code> interface, which     * the calling code must implement.     */    public void exit() {        System.out.println("EXITING MIDLET");        synchronized (this) {            cmdList.removeAllElements();            if (isLoggedIn()) {                ItemList itemList = new ItemList();                itemList.setItem("cmd", "unifiedLogout");                itemList.setItem("listener", this);                executeCmd(itemList);            }            comm.removeSnapEventListener(this);            comm.stop();            done = true;        }        main.exit();    }    /*     * =======================================================================     *  View management and GUI wrangling responsibilities.     * =======================================================================     */    /**     * Returns active View.     *     * @return View     */    public View getView()    {    	return canvas.getView();    }    /**     * Returns a particular View by name.  View is created if it does not     * already exist, or if View caching is turned off.  Requesting View     * "back" will pop the current View off the View stack, destroy it,     * and return the previous View.  Requesting View "exit" will cause     * SnapLogin to exit.     *     * @param name Name of the view to return     */    View getView(String name) {        String url;        View view;        int i;        view = null;        synchronized (viewList) {            if (viewList.size() > 1 && name.equals(BACK)) {                viewList.removeElementAt(viewList.size() - 1);                view = (View)viewList.elementAt(viewList.size() - 1);                return view;            }        }        view = findView(name);        if (view != null) return view;

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -