//package BallGame;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.game.GameCanvas;
import javax.microedition.lcdui.game.LayerManager;
import javax.microedition.lcdui.game.TiledLayer;
/**
* <strong>FileName</strong>: BallCanvas.java
* <HR>
* <strong>Description</strong>: Basic game canvans with background description and input functions.
* <P><HR>
* @author
* <em>
* This Game is developed by <B>Fansy</B>.<BR>
* F.S.Studio 1999~2005
* </em>
* @version 0.3.2
*/
public class BallCanvas extends GameCanvas implements Runnable
{
private LayerManager manager; //图层管理
private Image backimage; //背景图像
private int Level=4; //初始关卡
private static int keyState; //键盘状态
private Ball ball;
private Bar bar;
private Block block;
private Graphics g; //绘图缓冲
private int Score=0; //游戏得分
private byte[][] backmap={ //背景描述
{1,3,3,3,3,3,3,2},
{7,0,0,0,0,0,0,4},
{7,0,0,0,0,0,0,4},
{7,0,0,0,0,0,0,4},
{7,0,0,0,0,0,0,4},
{7,0,0,0,0,0,0,4},
{7,0,0,0,0,0,0,4},
{7,0,0,0,0,0,0,4},
{7,0,0,0,0,0,0,4}};
public TiledLayer background; //背景图层
public static final int MAX_LEVEL=5;
public BallCanvas()
{
super(false);
g=getGraphics();
bar=new Bar(this); //建立挡板对象
block=new Block(); //建立砖块对象
ball=new Ball(this,bar,block); //建立小球对象
try {backimage=Image.createImage("/backimage.png");} //装载背景图像
catch(Exception e){}
background=new TiledLayer(8,9,backimage,30,30); //建立背景图层,共有8行,9列
for(int i=0;i<9;i++) //初始化背景图层
for(int j=0;j<8;j++)
background.setCell(j,i,backmap[i][j]);
block.InitLevel(Level); //初始化关卡
manager=new LayerManager(); //
manager.append(ball.createBallSprite()); //
manager.append(bar.createBarSprite()); //建立图层管理对象并添加图层进行管理
manager.append(block.blocktd); //
manager.append(background); //
}
public void run()
{
ball.BallReady();
ball.start();
while (true)
{
keyState=getKeyStates(); //获取键盘状态
if((keyState&LEFT_PRESSED)!=0&&bar.getBarRefPixelX()>30) //左键按下
{
bar.BarMoveLeft();
if(!ball.isBallRun())
ball.setBallPosition(bar.getBarRefPixelX(),257);
}
else if((keyState&RIGHT_PRESSED)!=0&&bar.getBarRefPixelX()<210) //右键按下
{
bar.BarMoveRight();
if(!ball.isBallRun())
ball.setBallPosition(bar.getBarRefPixelX(),257);
}
try{Thread.sleep(20);}
catch(Exception e){}
}
}
public void isLevelClear()
{
if(block.isAllClear()) //过关
{
if(Level<MAX_LEVEL)
{
Level++;
block.InitLevel(Level);
ball.reset();
ball.BallReady();
bar.reset();
}
else
{
new GameOver().showGameOver();
}
}
}
public void drawScore() //绘制分数到缓冲区
{
g.setColor(0x00ffffffff);
g.drawString("Level:"+(Level+1)+" Score:"+Score,10,270,20);
}
public void drawScreen() //刷新屏幕
{
g.setColor(0x00000000);
g.fillRect(0,0,240,290); //清除图像缓冲区
drawScore();
manager.paint(g,0,0); //重绘缓冲图像
flushGraphics(); //刷新用户屏幕并显示
}
public void start()
{
Thread t=new Thread(this);
t.setPriority(Thread.MAX_PRIORITY);
t.start();
}
public void addScore(int extraScore)
{
Score+=extraScore;
}
}