DOJA开发贪吃蛇的代码
时间:2011-01-11
公司准备做手机游戏方面的项目,第一次做DOJA相关的项目,练习了“贪吃蛇”这个游戏,现把自己做的源代码发布出来,希望给才接触DOJA的新手一点提示和帮助。也欢迎大家提出改正。
//主运行类
package greedSnake;
import com.nttdocomo.ui.Display;
import com.nttdocomo.ui.IApplication;
public class GreedSnake extends IApplication implements Runnable{
public static final int GRID_WIDTH = 20;
public static final int GRID_HEIGHT = 24;
public static final int NODE_SIZE = 10;
private Grid grid = null;
private Food food = null;
private Snake snake = new Snake();;
private boolean running;
private int score;
private int level;
private int count;
private int countMove;
private int timeInterval;
//----------------------------------------
/** Set up game. */
public void start() {
reset();
grid = new Grid(GRID_WIDTH, GRID_HEIGHT, this);
Display.setCurrent(grid);
Thread runner = new Thread(this);
runner.start();
}
private void reset() {
running = false;
score = 0;
level = 0;
count = 0;
countMove = 6;
timeInterval = 200;
}
/** Runnable interface. */
public void run() {
food=grid.addFood();
grid.addSnake(snake);
grid.repaint();
for(;;) {
if (food == null) {
food=grid.addFood();
continue;
}
try {
Thread.sleep(timeInterval);
} catch (Exception e) {
break;
}
if (!running) {
snake.move();
Node head = snake.getHead();
if (grid.overlapsWith(head)||(snake.ptInSnake(head))){
running = true;
continue;
}
if((head.x==food.getX())&&(head.y==food.getY())){
int scoreGet=(10000-200*countMove)/timeInterval;
score+=scoreGet>0 ? scoreGet : 0;
countMove=0;
snake.eatFood(food);
grid.reduceFood(food);
food=null;
if( ++count%5 == 0){
level++;
}
}else{
countMove++;
}
grid.repaint();
}else{
grid.setGameOver();
break;
}
}
grid.repaint();
}
public int getScore() {
return score;
}
/** Get the current level of the game. */
public int getLevel() {
return level;
}
/** Key event handler. */
public void keyPressed(int key) {
if (key == Display.KEY_SELECT) {
grid.setGameOver();
}
if (key == Display.KEY_LEFT) {
snake.setDirection(Snake.LEFT);
}
if (key == Display.KEY_RIGHT) {
snake.setDirection(Snake.RIGHT);
}
if (key == Display.KEY_DOWN) {
snake.setDirection(Snake.DOWN);
}
if (key == Display.KEY_UP) {
snake.setDirection(Snake.UP);
}
}
}
//画面框架类
package greedSnake;
import com.nttdocomo.ui.Canvas;
import com.nttdocomo.ui.Display;
import com.nttdocomo.ui.Font;
import com.nttdocomo.ui.Frame;
import com.nttdocomo.ui.Graphics;
//---------------------
/**
* This class represents the grid box that catches
* the pieces dropping from above. If a dropped piece
* fills up one or more horizontal lines in the grid,
* these lines will be removed from it.
*/
public class Grid extends Canvas {
private int width;
|