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

📄 ge.java

📁 一个j2me游戏代码
💻 JAVA
📖 第 1 页 / 共 5 页
字号:
package pop2;

import java.io.*;
import java.util.*;
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;
import javax.microedition.rms.*;

/**
 * <p>Title: POP2</p>
 * <p>Description: Prince of Persia 2</p>
 * <p>Copyright: Copyright (c) 2003</p>
 * <p>Company: UBI soft (Beijing)</p>
 * @author Cao Heng
 * @version 1.0
 */

class SoundPlayer implements Runnable
{
    static boolean m_running = false;
    static int m_pendingSnd = -1;
    static int m_currentSnd;
    static int m_melodyNum;
    static javax.microedition.media.Player[] m_SoundTracks;

    public void init()
    {
        int         num, offset0, offset1, len, size;
        byte[]      indexbytes;
        String      fileName = "/sound.bin";

        try {
            java.io.InputStream  is = fileName.getClass().getResourceAsStream(fileName);

            indexbytes = new byte[4];
            is.read( indexbytes );
            m_melodyNum = GE.ReadInt( indexbytes, 0, 4 ) - 1;
            m_SoundTracks = new javax.microedition.media.Player[m_melodyNum];

            indexbytes = new byte[4*m_melodyNum+4];
            is.read( indexbytes, 0, 4*m_melodyNum+4 );
            offset0 = 0;
            for ( int i = 0; i < m_melodyNum; i++ )
            {
                offset1 = GE.ReadInt( indexbytes, 4*i+4, 4 );
                len = offset1 - offset0;
                byte[] melody = new byte[len];
                size = is.read( melody, 0, len );
                ByteArrayInputStream bis = new ByteArrayInputStream(melody);
                m_SoundTracks[i] = Manager.createPlayer(bis, "audio/midi");
                m_SoundTracks[i].realize();
                offset0 = offset1;
                melody = null;
                bis = null;
            }

            is.close();
        } catch (Exception e)
        {
            //sound init exception
        }
    }
    public void play(int id)
    {
        m_pendingSnd = id;
    }
    public void stop()
    {
        try
        {
            if(javax.microedition.media.Player.STARTED == m_SoundTracks[m_currentSnd].getState())
                m_SoundTracks[m_currentSnd].stop();
            if(javax.microedition.media.Player.PREFETCHED == m_SoundTracks[m_currentSnd].getState())
                m_SoundTracks[m_currentSnd].deallocate();
        } catch (Exception e) {}
    }
    public void quit()
    {
        m_running = false;
    }
    public void run()
    {
        m_running = true;
        while (m_running)
        {
            try {
                if (m_pendingSnd != -1)
                {
                    m_currentSnd = m_pendingSnd;
                    m_pendingSnd = -1;
                    javax.microedition.media.Player player = m_SoundTracks[m_currentSnd];
                    VolumeControl vc = (VolumeControl)player.getControl("VolumeControl");
                    vc.setLevel(GE.m_playSound*50);
                    player.start();
                }
                else
                {
                    Thread.yield();
                }
            } catch (Exception e) {}
        }
    }
}

//public class GE extends GameCanvas implements Runnable//, CommandListener
public class GE extends Canvas implements Runnable//, CommandListener
{
	// Thread
	Pop2MIDlet m_midlet;
	static Player m_player;
	static byte m_running = 1; // If game is running, control the thread
    static SoundPlayer m_sound = null;
    /* Sound
    //static byte[][] m_melodys;
    static int      m_currentSnd;
    static int      m_melodyNum;
    static javax.microedition.media.Player[] m_SoundTracks;
    //*/
	// Input
	static byte m_input[] = new byte[Def.KEY_SIZE];
	static byte m_inputBuf[] = new byte[Def.KEY_SIZE];
	static byte m_lastInput = Def.KEY_NONE;
	static byte m_inputTime;
	static boolean m_blockKey = false;
	// Graphic
    static final int TOPLEFT = Graphics.TOP | Graphics.LEFT;
    static final int TOPRIGHT = Graphics.TOP | Graphics.RIGHT;
    static final int TOPCENTER = Graphics.TOP | Graphics.HCENTER;
    static final int CENTER = Graphics.VCENTER | Graphics.HCENTER;
    static final int BOTTOMCENTER = Graphics.BOTTOM | Graphics.HCENTER;
	static Graphics m_g;
	static Image [] m_images = new Image[Def.IMAGE_NUM];
    static Image m_imageFire;
    static Image m_imageWater;
	static Image m_imageMisc;
	static Image m_imagePrince;
	static Image m_imageSandman;

    static Font sFont;
    static short sFont_H;

	// playfield
	Image m_imageBg;
    static Image m_imageTilekit;
	static byte  m_mapBuf[];
	static int   m_bgWidth; // tile number in one horizonal line
	static int   m_bgHeight; // tile number in one vertical line
	static int   m_tileWidth = Def.TILE_WIDTH;
	static int   m_tileHeight = Def.TILE_HEIGHT;
	static boolean m_updateBg;
	static int   m_tileImageID;
	int   m_tileCountPerLine;
	int   m_prevX0; // X left position of last screen in background
	int   m_prevX1; // X right position of last screen in background
	int   m_prevY0; // X top position of last screen in background
	int   m_prevY1; // X bottom position of last screen in background
	int   m_bufWidth;
	int   m_bufHeight;
	// draw message
	static String m_text[]; // string resource
	static boolean m_brushTop;
	static boolean m_brushBottom;
	static int m_msgIndex;
	static int m_msgLine;
	static long m_msgTime;
    static int m_progress;
	static int m_textCounter;
	static boolean m_textOver;

	// text in credits
	final static int MENU_ITEM_NUM = 6;
	final String STR_MENU[] = {"New Game", "Continue", "Free Tour", "Options", "About", "Exit"};
	final static int PAUSE_ITEM_NUM = 5;
	final String STR_PAUSE[] = {"Resume", "Hints:", "Sound:", "Main Menu", "Exit"};
    final static int OPTION_ITEM_NUM = 4;
	final String STR_OPTION[] = {"Main Menu", "Hints:", "Sound:", "Controls"};
	// text in legal texts
	//final String STR_LEGAL_TEXTS =
	//    "\u00A9 2003 Gameloft.^Based on Prince^of Persia created^by Jordan Mechner.^All Rights^Reserved.^"+
	//	"Gameloft and^the Gameloft logo^are trademarks^of Gameloft^in the US and/or^other countries.^"+
	//	"Prince of Persia^The Sands of Time^is a trademark of^Jordan Mechner^used under license^by Gameloft.";
		//"Available on^PlayStation 2,^XBOX,^Gamecube,^PC CD-ROM and^GameBoyAdvance^www.^princesandsoftime.^com";
	// text in credits
	final String STRING_VERSION = "Version ";
    static String STR_CREDITS;
	final String STR_CREDITS_1 =
		"Info and support:^www.gameloft.com^support@gameloft.^com^^Prince of Persia^Sands of Time^";
    final String STR_CREDITS_2 =
		"^^^Copyright 2003^Gameloft SA^^^Credits^^Project Manager^Philippe Laurens^^Producer^Ding Xue Song^^Game Designer^Ding Xue Song^"+
		"Programmers^Su Ning^Cao Heng^Qiu Wei Min^^Sound Designer^Philippe Arsenault^^Artists^Zhi Yong^Tian Yan^Huang Mei^^Quality Assurance^Benjamin Goulet^Jean-Claude Labelle^Nicolas Gauvreau^Richard Cloutier^Jean-Virgile Laprise^Mathieu Ducharme^Yannick Belzil^F.M. St-Hilaire^Nguyen Hung Tam^Ricardo Filippi^Gao Bo^Wang Xun^Ma Ning";
	// text in controls
	final String STR_CONTROLS =
		"Controls^^2: Jump, Climb Up^8: Climb Down^4: Move Left^6: Move Right^^^Right Soft Key:^Select In Menu^Pause In Game^^5: Select In Menu^Attack In Game";
	final String STR_STORY_BEGIN =
        "Many moons ago,^in the ancient^kingdom of^Persia, King^Shahraman and his^young son, the^Prince, were at^the war with^Maharajah of^India. They were^helped by a Vizier^who betrayed the^Maharajah and^allowed the^Persian army to^sack the palace.^When the palace^was plundered,^the Vizier asked^the Prince to^steal a magic^Dagger which was^locked up in the^Maharajah's^vaults, under^heavy guard.^Little did the^Prince know,^however, that the^Vizier had his^greedy eye on^quite another^prize: the Sands^of Time!";
	final String STR_STORY_END =
	    "And so it was the^Prince's Dagger^that struck home^and the Vizier^breathed his last.^The Sands of Time^came back to bless^the people of In-^dia. And long may^those good souls^continue to live^in peace and feli-^city, for our hero^- the Prince -^dwells on, forever^in their hearts!";
	final String STR_SCORE[] = { "Qualified", "Skilled", "Expert", "Master", "GrandMaster" };
	final int CLR_SCORE[] = { 0x0000FE, 0x00FEFE, 0xFEFE00, 0xFE7E7E, 0xFE0000 };
	final static int LEVEL_SCORE[] = { 50, 60, 60, 70, 100, 160, 160, 220 };
	// Game Control
	byte m_painted; // If this frame has painted.
	static byte m_levelPassed[] = new byte[Def.LEVEL_NUMBER]; // if level is passed
	static byte m_playSound = 2; // if game play sound
	static byte m_playHint = 1; // if game view hint
	final static int RECORD_LENGTH = 50;
	static byte[] record = new byte[RECORD_LENGTH];
	static short m_levelScore[] = new short[Def.LEVEL_NUMBER]; // if level is passed
	static int m_gameState; // indicate the state of game : menu, run or others
	static int m_levelSelected; // which level player will play (0,1,...N)
	static int m_levelLoad; // which level is loaded now
	static int m_menuIndex; // current selected menu index
	static int m_pauseIndex = -1; // current selected pause menu index
	static int m_optionIndex = -1; // current selected pause menu index
	static int m_levelPassHurt;
	// Frame
	static long m_timeRate = Def.TIME_RATE_MIN;
	//static long m_timeRateAverage;
	static long m_lastFrameTime;
	static long m_curFrameTime; // Start time of each frame
	static long m_levelPassTime;
	//static long m_lasttime;

	/* Lyman DEBUG
    static int m_keycode;
	static int Lyman; // secret recipe

	static int m_Debug1; // show debug info, 0 : show none
	static int m_Debug2; // show debug info, 0 : show none
	static int m_Debug3; // show debug info, 0 : show none
    static int m_updatedAI;
	static int m_lastFps, m_curFps; // fps in last second
	                      // 0  1  2  3  4  5  6  7  8  9
    static long m_piece[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // the time piece for each frame
    //*/

	static boolean m_inited;

    public GE(Pop2MIDlet midlet)
    {
        //super(false);
        m_midlet = midlet;
        sFont = Font.getFont( Font.FACE_PROPORTIONAL, Font.STYLE_BOLD, Font.SIZE_LARGE );
        sFont_H  = (short)sFont.getHeight();
        m_inited = false;
	}

	// Initialize all variables ------------------------------------------------
	void gameInit()
	{
        // Create other class
        m_player = new Player();

        // Init resource
        resetKey();
        loadImages(true);

        soundInit();
        System.gc();
        loadRecord();
        System.gc();

        loadString();
		loadAnimation();
        System.gc();

        // Init Datas
        m_levelLoad = -1;
        m_progress = 0;
        STR_CREDITS = STR_CREDITS_1 + STRING_VERSION + m_midlet.getAppProperty("MIDlet-Version") + STR_CREDITS_2;
        playSound(Def.SOUND_TITLE_MID, 1);

        // show legal texts first
        if (Legal.isEU)
            loadImage( Def.PNG_UBILOGO, "/ubilogo.png");
        m_textCounter = 0;
        m_gameState = Def.STATE_LEGAL_TEXTS;

        if (m_levelPassed[0] == 0)
            m_menuIndex = 0;
        else if (m_levelPassed[Def.LEVEL_NUMBER-1] > 0)
            m_menuIndex = 2;
        else
            m_menuIndex = 1;
	}

	// Thread circle -----------------------------------------------------------
	public void run()
	{
        if (!m_inited)
        {
            setFullScreenMode(true);

            m_inited = true;
            m_gameState = Def.STATE_FIRST_SCREEN;
            //m_g = getGraphics();
            //render();
            //flushGraphics();
            repaint();
            serviceRepaints();

            try{ Thread.sleep(1000); }catch(Exception e){}
            gameInit();
        }
        //if (m_running!=0)
        //{
	        //m_lasttime = System.currentTimeMillis();
		while ( m_running != 0)
		{
			// Lyman DEBUG, show fps
			//m_curFps++;
			//m_lastFrameTime = m_curFrameTime;
			m_curFrameTime = System.currentTimeMillis();
			//m_lasttime = m_curFrameTime;
			//Lyman DEBUG, show fps
			//if (m_curFrameTime % 1000 < m_lastFrameTime % 1000)
			//{
			//	m_lastFps = m_curFps;
			//	m_curFps = 0;
			//}
			// Process game state
			updateState();
            // Lyman DEBUG
            //m_piece[0] = System.currentTimeMillis() - m_curFrameTime;
			m_painted = 0;
			repaint();
            while (m_painted == 0)
            {
                Thread.yield();
            }
            //if (isShown())
            //{
            //    updateState();
            //    render();
            //    flushGraphics();
            //}
			//m_lastFrameTime = System.currentTimeMillis() - m_curFrameTime;
            // Lyman DEBUG
            //m_piece[1] = m_lastFrameTime - m_piece[0];
			/* auto gc
			if (m_lastFrameTime > Def.TIME_RATE_MAX)
			{
				System.gc();
			}
			else
			{
				if (m_timeRateAverage > m_timeRate + 20 || m_timeRateAverage < m_timeRate - 20)
					m_timeRateAverage = m_timeRate;
				if (m_lastFrameTime <= m_timeRateAverage) // if this frame time is short, DO gc
					System.gc();
				m_timeRateAverage = m_timeRateAverage*4/5 + m_lastFrameTime/5;
			}//*/
            ///* time to sleep
            m_lastFrameTime = System.currentTimeMillis() - m_curFrameTime;
            while (m_lastFrameTime < m_timeRate)
            {
                Thread.yield();
                m_lastFrameTime = System.currentTimeMillis() - m_curFrameTime;
            }//*/
            // Lyman DEBUG
            //m_piece[2] = System.currentTimeMillis() - m_curFrameTime - m_piece[0] - m_piece[1];
		}
        //    Display.getDisplay(m_midlet).callSerially(this);
        //}
        //else
        //{
            m_sound.m_running = false;

            m_midlet.notifyDestroyed();
            m_midlet.destroyApp(true);
        //}
	}

	// Release all resource and Save Records -----------------------------------
	void pauseGame()
	{
        if (m_gameState == Def.STATE_RUN)
        {
            m_pauseIndex = 0;
            m_gameState = Def.STATE_PAUSE;
            m_levelPassTime = m_curFrameTime - m_levelPassTime;
            //setCommands("", "Select");
        }
	}
	// Release all resource and Save Records -----------------------------------
	//void gameDestroyed()
	//{
	//	saveRecord();
    //    try{ Thread.yield(); Thread.sleep(1000); }catch(Exception e){}

⌨️ 快捷键说明

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