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

📄 mazeracer.java

📁 j2me编写的一个在线游戏
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
            return;        }        if (id == HEARTBEAT) {            System.out.println("heartbeat received.");            return;        }        if (state == WAITING_FOR_NUMBER && id == NUMBER) {            if (num == data[1]) {                reset(singleUser);                return;            } else {	            isLead = num > data[1];	            if (!isLead) {	            	sendGamePacket(new byte[] {FOLLOW_ACK});	            	setState(WAIT_FOR_LEAD_PING);	            } else {	            	setState(WAIT_FOR_FOLLOW_ACK);	            		            }//	            setState(isLead ? WAIT_FOR_FOLLOW_ACK : WAIT_FOR_LEAD_PING);	            return;            }        }        if (state == WAIT_FOR_FOLLOW_ACK && id == FOLLOW_ACK) {            sendGamePacket(new byte[] {LEAD_PING});            setState(WAIT_FOR_FOLLOW_PING);            then = System.currentTimeMillis();            return;        }        if (state == WAIT_FOR_LEAD_PING && id == LEAD_PING) {            sendGamePacket(new byte[] {FOLLOW_PING});            setState(WAIT_FOR_LEVEL_SEED);            return;        }        if (state == WAIT_FOR_FOLLOW_PING && id == FOLLOW_PING) {            byte[] buf;            delay = (int)(System.currentTimeMillis() - then) / 2;            seed = rnd.nextInt();            Util.setSeed(seed);            maze.reset();            view.repaint();            buf = new byte[5];            buf[0] = LEVEL_SEED;            packInteger(buf, 1, seed);            sendGamePacket(buf);            try {Thread.sleep(delay);}            catch (InterruptedException e) {}            view.setTicker("Go!");            setState(LEVEL_STARTED);            levelStart = System.currentTimeMillis();//            lastContact = -1;            return;        }        if (state == WAIT_FOR_LEVEL_SEED && id == LEVEL_SEED) {            delay = 0;            seed = unpackInteger(data, 1);            Util.setSeed(seed);            maze.reset();            view.repaint();            view.setTicker("Go!");            setState(LEVEL_STARTED);            levelStart = System.currentTimeMillis();//            lastContact = -1;            return;        }        if ((state == LEVEL_STARTED || state == LEVEL_COMPLETED) && id == PLAYER_UPDATE) {            pos = unpackInteger(data, 1);            playerList[1].setPosition(pos);            return;        }        if (state == LEVEL_STARTED && id == COMPLETION) {            setState(LEVEL_COMPLETED);            sendGamePacket(new byte[] {CONCEDE});            winString[2]++;            view.setTicker( opponent + " finished first.");            reset(singleUser);            return;        }        if (state == LEVEL_COMPLETED && id == CONCEDE) {            winCount++;            winString[0] = (char)('0' + winCount);            if (winCount > 2) {                view.setTicker("You won!");                sendGamePacket(new byte[] {VICTORY});                ItemList itemList;                itemList = new ItemList();                itemList.setItem("cmd", "gameStop");                itemList.setItem("gcid", community.getGCID());                itemList.setItem("category1", "TOTAL_TIME");                itemList.setItem("value1", "" + new Integer((int)(totalTime / 1000)));                itemList.setItem("category2", "WINS");                itemList.setItem("value2", "1");                community.executeCmd(itemList);                playing = false;                gameOver(true);                community.showDialog(                        "Game Over", "Game over, you won!",                        null, Community.MAZEEXIT, Dialog.ALERT                        );            } else {                view.setTicker("You finished first!");                reset(singleUser);            }            return;        }        if (state == LEVEL_COMPLETED && id == COMPLETION) {            rdelta = unpackInteger(data, 1);            if (rdelta < lastDelta) {                sendGamePacket(new byte[] {CONCEDE});                winString[2]++;                view.setTicker( opponent + " finished first.");            } else {                winCount++;                winString[0] = (char)('0' + winCount);                view.setTicker("You finished first!");            }            reset(singleUser);            return;        }        if (id == VICTORY) {            winCount = -1;            view.setTicker( opponent + " won :(");            ItemList itemList = new ItemList();            itemList.setItem("cmd", "gameStop");            itemList.setItem("gcid", community.getGCID());            itemList.setItem("category1", "LOSSES");            itemList.setItem("value1", "1");            community.executeCmd(itemList);            playing = false;            gameOver( true);            community.showDialog(                    "Game Over", "Game over, " + opponent + " won!",                    null, Community.MAZEEXIT, Dialog.ALERT                    );	            return;        }        System.out.println("received stray packet, id = " + id);   	}   	    /**     * Get level indicator as char array.     * @return level indicator as char array.     */    public char[] getLevel() {        return levelString;    }    /**     * Get time indicator as char array.     * @return time indicator as char array.     */    public char[] getTime() {        return timeString;    }    /**     * Called when the app is put into a paused state, such as     * during an incoming phone call.     */    public void pause() {     	synchronized (this) {     		paused = true;     	}    	pauseTime = System.currentTimeMillis();    }        /**     * Called when app is woken up from a paused state, e.g. after     * an incoming call.  If the app has been asleep too long, the     * game will exit.     */    public void resume() {     	synchronized (this) {     		paused = false;     	}    	if (playing &&     		System.currentTimeMillis()-pauseTime >= CONTACT_TIMEOUT)     	{            gameOver( false);            community.showDialog(                    "Game Over", "Sorry, your game was paused too long. " +                    "Game Over.  Please try again!",                    null, Community.MAZEEXIT, Dialog.ALERT                    );	    	}     }        /**     * Updates the current time and its display in the GUI.     */    private void updateTime() {        int min, sec, tenth, millis;        millis = (int)(System.currentTimeMillis() - levelStart);        min = millis / (1000 * 60);        millis = millis % (1000 * 60);        sec = millis / 1000;        millis = millis % 1000;        tenth = millis / 100;        timeString[timeString.length - 1] = (char)('0' + tenth);        timeString[timeString.length - 3] = (char)('0' + sec % 10);        timeString[timeString.length - 4] = (char)('0' + sec / 10);        timeString[timeString.length - 6] = (char)('0' + min % 10);        timeString[timeString.length - 7] = (char)('0' + min / 10);    }	/**	 * Check to see if we should send an updated position to      * the other player -- only send if we've moved at least     * 2 pixels in Y or Y to reduce the number of messages      * passed back and forth during gameplay.     * 	 * @param pos	 */    private void handlePosChanged( int pos)    {        int w = maze.getWidth();        int oldX = lastSentPos % w;        int oldY = lastSentPos / w;        int x = pos % w;        int y = pos / w;        int absX = Math.abs( x-oldX);        int absY = Math.abs( y-oldY);        if (absX>1 || absY>1) {            packInteger(updateBuf, 1, pos);            sendGamePacket(updateBuf);            lastSentPos = pos;        }    }        /**     * Terminate the thread driving this instance.     */    public void stop() {        done = true;    }    /**      * Main game loop. Executed each time a new game is played.       * Sends out position updates and/or heartbeats in case the      * player hasn't moved within the heartbeat interval. Also     * sends out notification when the user reaches the end of     * the maze.     */    public void run() {        int stop, pos;        done = false;        playing = true;        stop = maze.getWidth() * maze.getHeight() - maze.getWidth() - 1;        level = 1;        winCount = 0;        lastContact = -1;        lastPacketSent = -1;        timeString  = new char[] {'0', '0', ':', '0', '0', '.', '0'};        levelString[levelString.length - 1] = (char)('0' + level % 10);        levelString[levelString.length - 2] = (char)('0' + level / 10);        winString[0] = '0';        winString[2] = '0';        if (!singleUser) view.setTicker("Preparing, please wait...");        view.repaint();        while (!done) {        	        	while (paused) {        		try { Thread.sleep( 500); } catch (Exception ignore) {}        		if (done || !playing) return;        	}            if (lastContact > 0 && !singleUser && playing ) {            	if((System.currentTimeMillis()-lastContact) >= CONTACT_TIMEOUT) {	                community.showDialog(	                        "Error", "Lost contact with your opponent. Game over, " +	                        "please try again!",	                        null, Community.MAZEEXIT, Dialog.ALERT	                        );	                gameOver(false);	                break;            	} else if((System.currentTimeMillis()-lastContact) >= 5000) {            		synchronized(this) {            			if(state == WAIT_FOR_LEAD_PING) {            				sendGamePacket(new byte[] {NUMBER, (byte)num});            				sendGamePacket(new byte[] {FOLLOW_ACK});            			} else if (state == WAIT_FOR_FOLLOW_ACK) {            				sendGamePacket(new byte[] {NUMBER, (byte)num});            			}            		}            	}            }            if (state == LEVEL_STARTED && playing) {                updateTime();                playerList[0].move(dir);                pos = playerList[0].getPosition();                if (lastPos != pos) handlePosChanged( pos);                lastPos = pos;                               if (pos == stop) {                    setState(LEVEL_COMPLETED);                    lastDelta = (int)(System.currentTimeMillis() - levelStart);                    totalTime += lastDelta;                    byte[] buf = new byte[5];                    buf[0] = COMPLETION;                    packInteger(buf, 1, lastDelta);                    sendGamePacket(buf);                    if (singleUser) reset(singleUser);                    else view.setTicker("Maze solved, syncing with opponent...");                }            }                        // Send a heartbeat ping if we haven't sent any other            // game messages in a while            if (lastPacketSent > 0 && !paused && playing &&                (System.currentTimeMillis()-lastPacketSent)>PING_INTERVAL)            {            	sendGamePacket(new byte[] {HEARTBEAT});            }            view.repaint();            try {Thread.sleep(100);}            catch (InterruptedException e) {}        }    }}

⌨️ 快捷键说明

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