針對 NTT DoCoMo 的 DOJA (i-mode Java) 平台開發的貪食蛇遊戲,包含主遊戲類別 GreedSnake、畫面框架 Grid、蛇物件 Snake、食物 Food、節點 Node 五個類別。展示行動裝置遊戲迴圈、按鍵處理、碰撞偵測與繪圖邏輯。
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;
private Food food;
private Snake snake = new Snake();
private boolean running;
private int score, level, count, countMove, timeInterval = 200;
public void start() {
reset();
grid = new Grid(GRID_WIDTH, GRID_HEIGHT, this);
Display.setCurrent(grid);
new Thread(this).start();
}
private void reset() {
running = false; score = 0; level = 0; count = 0; countMove = 6;
}
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; }
public int getLevel() { return level; }
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);
}
}
Canvas,負責畫面繪製、食物/蛇的管理、遊戲結束顯示。Vector 儲存節點,提供移動、增長、自我碰撞檢查。編譯需包含 com.nttdocomo.ui 套件(DOJA SDK)。適合初學者參考行動遊戲基本架構。