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

📄 gamecanvasdemo.java

📁 jBuilderX无线应用开发源代码
💻 JAVA
字号:
import javax.microedition.midlet.*;
import javax.microedition.lcdui.game.*;
import javax.microedition.lcdui.*;

public class GameCanvasDemo extends MIDlet implements CommandListener{

	private Display display;
	private final static Command exit = new Command("Exit", Command.EXIT, 1);
	//运行游戏的GameCanvas对象
	private BallCanvas gameCanvas;

	public GameCanvasDemo(){
		display=Display.getDisplay(this);	
		gameCanvas=new BallCanvas();	
		gameCanvas.addCommand(exit);
		gameCanvas.setCommandListener(this);
	}

	public void startApp(){	
		display.setCurrent(gameCanvas);
		gameCanvas.startGame();
	}

	public void pauseApp(){
		gameCanvas.stopGame();
	}

	public void destroyApp(boolean b){
		gameCanvas.stopGame();
	}

	 public void commandAction(Command c, Displayable s){
       if (c == exit) {
			destroyApp(false);
			notifyDestroyed();
		}
    }
}

//该类继承了GameCanvas类,并封装了游戏的运行逻辑
class BallCanvas extends GameCanvas implements Runnable{
	//指示游戏是否结束
	private boolean gameOver;
	//绘制图像缓冲区的Graphics对象
	private Graphics g;
	//屏幕显示区域的宽度和高度
	private  int width,height;	
	//小球的位置
	private int x,y;	
	//小球的半径
	private int radius;		

	public BallCanvas(){
		//阻止键盘事件产生
		super(true);
		//获得绘制图像缓冲区的Graphics对象
		g=getGraphics();
		//设置小球的初始位置和半径
		x=10;
		y=10;
		radius=5;
		//获得屏幕显示区域的宽度和高度
		width=this.getWidth();
		height=this.getHeight();	
	}

	//开始运行游戏
	public void startGame(){
		gameOver = false;
		Thread myThread = new Thread(this);
		myThread.start();
	}

	//停止运行游戏
	public void stopGame(){
		gameOver=true;
	}

	//游戏主循环
	public void run(){
	    while(!gameOver){
			//查询键盘状态
			int keyState=this.getKeyStates();
			
			//处理用户输入,根据用户按键方向移动小球,并保证小球不移出屏幕显示区域
			//LEFT键按下
			if((keyState&LEFT_PRESSED)!=0){
				x--;
				if(x<radius)
					x=radius;
			}
			//RIGHT键按下
			if((keyState&RIGHT_PRESSED)!=0){
				x++;
				if(x>width-radius)
					x=width-radius;
			}
			//UP键按下
			if((keyState&UP_PRESSED)!=0){
				y--;
				if(y<radius)
					y=radius;
			}
			//DOWN键按下
			if((keyState&DOWN_PRESSED)!=0){
				y++;
				if(y>height-radius)
					y=height-radius;
			}

			//绘制图像缓冲区
			//用白色填充背景区域
			g.setColor(255,255,255);
			g.fillRect(0,0,width,height);
			//用红色绘制小球
			g.setColor(255,0,0);
			g.fillArc(x-radius,y-radius,radius+radius,radius+radius,0,360);	

			//将缓冲区复制到实际屏幕
			flushGraphics();

			//延时10毫秒
			try {
				Thread.sleep(10); 
			}
			catch (InterruptedException ie) {
			}
  	    }
	}
}

⌨️ 快捷键说明

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