public void paint(graphics g)
{
// painting code goes here.
}
protected void keypressed(int keycode)
{
// respond to key presses here.
}
}
这样的结构存在一些问题,事件处理、游戏绘制的动作放在不同的线程内处理,对游戏可能产生不可预料的影响。gamecanvas的出现很好的解决了这个问题,你可以在应用程序的线程中获得graphics对象,这时候系统会在off-screen的缓冲区内进行绘制,当你调用flushgraphics()的时候会马上绘制到手机屏幕上去。只有当屏幕被更新后者个方法才会返回,而调用repaint()的话,方法马上就返回你就不知道什么时候paint()才被调用。另外gamecanvas通过getkeystates()方法来判断用户的输入事件。这样你就不用等待系统调用keypressed()方法了,getkeystates()可以马上得到现在按键的状态。
如果我们采用gamecanvas做游戏的时候,通常游戏的结构如下:
import javax.microedition.lcdui.*;
import javax.microedition.lcdui.game.*;
public class simplegamecanvas extends gamecanvas implements runnable
{
private volatile boolean mtrucking;
private long mframedelay;
private int mx, my;
private int mstate;
public simplegamecanvas()
{
super(true);
mx = getwidth() / 2;
my = getheight() / 2;
mstate = 0;
mframedelay = 20;
}
public void start()
{
mtrucking = true;
thread t = new thread(this);
t.start();
}
public void stop()
{
mtrucking = false;
}
public void run()
{
graphics g = getgraphics();
while (mtrucking == true)
{
tick();
input();
render(g);
try
{
thread.sleep(mframedelay);//这里我们也可以通过定义每桢的时间来处理,更合理些。
} catch (interruptedexception ie)
{
stop();
}
}
}
private void tick()
{
mstate = (mstate + 1) % 20;
}
private void input()
{
int keystates = getkeystates();
if ((keystates & left_pressed) != 0)
mx = math.max(0, mx - 1);
if ((keystates & right_pressed) != 0)
mx = math.min(getwidth(), mx + 1);
if ((keystates & up_pressed) != 0)
my = math.max(0, my - 1);
if ((keystates & down_pressed) != 0)
my = math.min(getheight(), my + 1);
}
private void render(graphics g)
{
g.setcolor(0xffffff);
g.fillrect(0, 0, getwidth(), getheight());
g.setcolor(0x0000ff);
g.drawline(mx, my, mx - 10 + mstate, my - 10);
g.drawline(mx, my, mx + 10, my - 10 + mstate);
g.drawline(mx, my, mx + 10 - mstate, my + 10);
g.drawline(mx, my, mx - 10, my + 10 - mstate);
flushgraphics();
}
}
[1] [2] [3] [4] 下一页
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器