三個核心類:
SnakeMIDlet:MIDlet 入口,啟動畫布。SnakeCanvas:繼承 Canvas 並實現 Runnable,負責繪製與主循環。Snake:蛇身邏輯,用 Vector 存儲節段(x, y, 方向, 長度)。本質:蛇頭長度++,蛇尾長度--;蛇尾長度 ≤ 0 時移除尾節段。
public synchronized void move() {
if (sections.isEmpty()) return;
int[] tail = (int[]) sections.lastElement();
int[] head = (int[]) sections.firstElement();
// 移動尾部
switch (tail[2]) { case 1: tail[1]--; break; ... }
tail[3]--; // 尾部縮短
head[3]++; // 頭部增長
if (tail[3] <= 0) sections.removeElement(tail);
}
按鍵事件觸發 breakInto(dir),在蛇頭前插入新節段,方向為新方向,長度歸零(下一幀增長)。
public synchronized void breakInto(int dir) {
int[] head = (int[]) sections.firstElement();
if (dir == head[2]) return; // 同方向無操作
int[] newHead = new int[4];
// 根據舊頭方向計算新頭起始坐標
switch (head[2]) { ... }
newHead[2] = dir; newHead[3] = 0;
sections.insertElementAt(newHead, 0);
}
paint(Graphics g) 遍歷節段,根據方向畫線段。使用 synchronized 保證繪製與移動線程安全。