您的位置:首页 > 服装鞋帽 > 休闲装 > [东华艺宗]手机游戏开发之J2ME弹球

[东华艺宗]手机游戏开发之J2ME弹球

luyued 发布于 2011-01-30 09:35   浏览 N 次  

东华艺宗游戏人才培训中心

今天为大家介绍手机游戏开发之J2ME弹球。下面就是代码

====================================主程序=========================================

import javax.microedition.lcdui.Display;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;


public class Main extends MIDlet {

protected void destroyApp(boolean arg0) throws MIDletStateChangeException {
// TODO Auto-generated method stub

}

protected void pauseApp() {
// TODO Auto-generated method stub

}

protected void startApp() throws MIDletStateChangeException {
// TODO Auto-generated method stub
Display.getDisplay(this).setCurrent(new GameCanvas());
}

}

====================================画布=========================================

import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Graphics;

import java.util.Random;
import java.util.Vector;

public class GameCanvas extends Canvas implements Runnable
{
Random rand = new Random();
Ball ball = new Ball();
Vector v = new Vector();
Ball newball = null;

int x;
int y;
GameCanvas()
{
this.setFullScreenMode(true);
new Thread(this).start();
}

protected void paint(Graphics g)
{
g.setColor(0);
g.fillRect(0, 0, 240, 320);
for(int i = 0; i < v.size(); i++)
{
newball = (Ball)v.elementAt(i);
newball.paintBall(g);
newball.goAndCollision();
}
g.drawString("当前球的个数:" + v.size(), 0, 0, 20);
}

protected void keyPressed(int keyCode)
{
int key = getGameAction(keyCode);
if(key == Canvas.FIRE || keyCode == Canvas.KEY_NUM5)
{
v.addElement(new Ball());
}
if(keyCode == Canvas.KEY_NUM0)
{
v.removeElementAt(v.size() - 1);
}
}

public void run()
{
while(true)
{
try {
Thread.sleep(30);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
repaint();
}
}
}

====================================弹球类=========================================

import java.util.Random;
import javax.microedition.lcdui.Graphics;

public class Ball
{
Random rand = new Random();
int x = Math.abs(rand.nextInt()!0);
int y = Math.abs(rand.nextInt())0);

final int r = 30;
int speedx = 4;
int speedy = 4;

public void paintBall(Graphics g)
{
g.setColor(255, 0, 0);
g.fillArc(x, y, r, r, 0, 360);
}

public void goAndCollision()
{
x += speedx;
y += speedy;

if(x <= 0 || x >= 210)
{
speedx = -speedx;
}
if(y <= 0 || y >= 280)
{
speedy = -speedy;
}
}
}


MSN空间完美搬家到新浪博客!

图文资讯
广告赞助商