📄 community.java
字号:
} return false; } /* * ======================================================================= * Helper methods for managing SNAP data, state, and command execution. * ======================================================================= */ /** * Validates friend name and if valid submits request to * add a friend to the friends list. * * @param name */ public void addFriend( String name) {// System.out.println( "addFriend(): " + name); if (name == null || name.equals("") || name.length()<4) { showError("You must enter a friend name of at least 4 letters."); } else { ItemList il = new ItemList(); il.setItem("cmd", "requestBuddy"); il.setItem("name", name); il.setItem("message", "Be my buddy?"); il.setItem("listener", this); il.setItem("asyncListener", this); executeCmd(il); switchToView(Community.BACK); } } /** * Get the last SNAP error intercepted via the SnapEventListener * interface's processServerError() method (implemented in this * class). * * @return Error */ public String getLastError() { synchronized (this) { String error = lastError; lastError = null; return error; } } /** * Get the last SNAP error severity level intercepted via the * SnapEventListener interface's processServerError() method * (implemented in this class). * * @return Severity level */ public int getLastErrorSeverity() { synchronized (this) { int error = lastErrorSeverity; lastErrorSeverity = -1; return error; } } /** * Invent a random gameroom name. * * @return Name */ public String getRandomGameRoomName() { StringBuffer buf = new StringBuffer(); for (int i=0; i<8; i++) { buf.append((char)('a' + Math.abs(rnd.nextInt() % 26))); } return buf.toString(); } /** * Sets buddy list. * * @param buddies */ public void setBuddyList( Vector buddies) { buddyList.set( buddies); } /** * Sets MOTD messages * @param il ItemList returned from either getMOTD() or * extendedLogin() call. */ public void setMOTD( ItemList il) { if (il==null) { return; } Vector messages = il.getList( "messageList"); if (messages == null || messages.size()==0) { System.out.println("Zero messages in message list!"); return; } System.out.println( messages.size() + " messages in MOTD"); String motdText = ""; for (int i=0; i<messages.size(); i++) { ItemList il2 = (ItemList)messages.elementAt(i); String message = il2.getString( "message"); System.out.println( "Message " + i + ": " + message); motdText += message; if ( !(motdText.endsWith(".") || motdText.endsWith("!") || motdText.endsWith("?") || motdText.endsWith(","))) { motdText += "."; } motdText += "\n"; } Motd_txt = motdText; } /** * Submits request for a random quickmatch pairing * to the SNAP servers. */ public void handleQuickMatch() { ItemList il = new ItemList(); il.setItem("cmd", "randomStart"); il.setItem("lobbyID", "Random"); il.setItem("lobbyMaxUsers", new Integer(0)); // Note: 0 = infinite il.setItem("gameRoomMaxUser", new Integer(2)); il.setItem("listener", this); executeCmd(il); } /** * Handle incoming game challenges from other users. * <p> * If "leader" is 1, then this player is initiating the challenge, * so a specially formatted Chat message will be sent to the * opponent, inviting them to a game. * <p> * If leader is "0", then we were challenged, and this method is * called in order to accept the challenge. * <p> * Both challenger and challenged call "gameStart" to intiate the * game. * * @param name Name of opponent in game challenge * @param gameRoom Name of gameroom to join to start game * @param leader "1" if we are the challenger, "0" if we are the * challenged. */ public void handleChallenge(String name, String gameRoom, int leader) { ItemList il; View view = getView(PENDING_GAMESTART); view.setWaiting(true); switchToView(view, true); // If we are the challenger, send a challenge message if (leader == 1) { il = new ItemList(); il.setItem("cmd", "sendBuddyMessage"); il.setItem("name", name); il.setItem("msg", CHALLENGE_PREFIX + gameRoom); executeCmd(il); } // In either case, send a gameStart command. // If challenger, and the opponent declines, our gameStart // request will terminate. // If challenged, then the challenger will have already // issued a gameStart command, so shortly after we issue // ours in response, the game should begin. il = new ItemList(); il.setItem("cmd", "gameStart"); il.setItem("lobbyID", "Challenge"); il.setItem("lobbyMaxUsers", new Integer(0)); // Note: 0 = infinite il.setItem("gameRoomID", gameRoom); il.setItem("gameRoomMaxUsers", new Integer(2)); il.setItem("mode", new Integer(1)); il.setItem("leader", new Integer(leader)); il.setItem("listener", this); executeCmd(il); } /** * Handles incoming friend Presence update callbacks from SNAP Servers. * Analyzes user state such as GCID, in-game flag, availability, * and matchmaking mode to decide whether the user is online and * available, online and unavailable, or offline. * * @param il ItemList containing buddy presence information */ public void handlePresenceUpdate( ItemList il) { String avail = il.getString("availability"); Integer gcid = null; try { gcid = (Integer)(il.getItem("gameClassID")); } catch (Exception ignore) {} int matchMode = 0; try { matchMode = il.getInteger("matchMode"); } catch (Exception ignore) {} boolean inGame = false; try { inGame = il.getBoolean("inGame"); } catch (Exception ignore) {} String name = clipName(il.getString("fromName"));/* System.out.println("Got presence update------------"); System.out.println("name = " + name); System.out.println("gcid = " + gcid); System.out.println("availability = " + avail); System.out.println("matchMode = " + matchMode); System.out.println("inGame = " + inGame);*/ // Offline if ( avail.equals("unavailable")) { buddyList.updatePresence( name, Buddy.OFFLINE, gcid); // Online, unavailable } else if( matchMode != 0 || inGame || avail.equals("away")) { buddyList.updatePresence( name, Buddy.ONLINE_UNAVAILABLE, gcid); // Online, available } else { buddyList.updatePresence( name, Buddy.ONLINE_AVAILABLE, gcid); } } /** * Convenience method to clip off auth domain information * from fully-qualified SNAP Mobile user names. * * @param name */ private String clipName(String name) { int index = name.indexOf('@'); if (index < 0) return name; return name.substring(0, index); } /** * Extracts opponent's name from return value ItemList of a * successful gameStart or randomStart request. * * @param il ItemList returned from successful gameStart or * randomStart command * @return Opponent's name, or "Opponent" if no name found. */ protected String getOpponentName( ItemList il) { String name = "Opponent"; if (il == null) { System.out.println("Community.getOpponentName(): Null Item List!"); return name; } Vector rivals = il.getList("rivalList"); if (rivals != null) { for (int i=0; i<rivals.size(); i++) { ItemList user = (ItemList)rivals.elementAt(i); String userName = user.getString("userName"); if (userName != null && !userName.equals(username)) { return userName; } } } return name; } /** * Starts a MazeRacer game, and MazeRacerView takes over the GUI. * * @param singleUser */ private void startGame(boolean singleUser) { mazeRacer.reset( singleUser); switchToView( mazeRacer.getView(), true); } /** * Logs the user out, then puts them back on the main menu screen. */ public void logout() {// System.out.println("LOGGING OUT, RETURNING TO MAIN MENU"); // Set username to null and empty out buddy list. username = null; password = null; password2 = null; emailAddress = null; dateOfBirth = null; buddyList.set( null); if (isLoggedIn()) { cmdList.removeAllElements(); ItemList itemList = new ItemList(); itemList.setItem("cmd", "unifiedLogout"); itemList.setItem("listener", this); executeCmd(itemList); showDialog( "Logging Out", "Logging out... one moment please.", null, Community.WELCOME, Dialog.ALERT ); } else { switchToView( WELCOME); } } /** Returns <code>true</code> if user has successfully logged in. */ public boolean isLoggedIn() { return webSessionID != null; } /** * Returns MIDlet property. * @param name */ public String getProperty(String name) { return main.getProperty(name); } /** * Returns MazeRacer's game class ID. */ public Integer getGCID() { return gcid; } /** * Sets user's username. * @param username */ void setUsername(String username) { this.username = username; } /** * Returns user's username */ String getUsername() { return username; } /* * ======================================================================= * SNAP communcation management, including the main event loop that submits * SNAP commands, as well as the processServerError() and processEvents() * callbacks used for receiving errors and data back from SNAP. * ======================================================================= */ /** * Adds a SNAP command to the command queue. * * @param cmd ItemList containing command name and parameters. */ public void executeCmd(ItemList cmd) { synchronized (this) { if (!done) { // If gameStartCancel command, execute now in its own thread. // Otherwise add command to queue for processing in SNAP // messaging thread (Community.run(), below). if (!handleGameStartCancel( cmd)) { cmdList.addElement(cmd); notifyAll(); } } else { System.out.println("Community.executeCmd():"); System.out.println("Event loop finished (most likely fatally), cannot execute command!"); } } } /** * gameStartCancel commands must be sent out in a parallel
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -