這是一個以物件導向方式撰寫、註解完整的 JavaScript 貪吃蛇(Snake v2.4)。與其逐行貼出數百行程式碼,不如把它的架構拆解清楚——理解了資料結構與各方法的職責,實作細節自然水到渠成。
遊戲以一個 <table> 當畫布,每個 <td> 就是一個 10×10 的格子,用背景顏色表示「有沒有東西」。
table { border-collapse: collapse; border: solid #333 1px; }
td { height: 10px; width: 10px; font-size: 0px; }
.filled { background-color: blue; }
蛇本身則用一個陣列表示,每個元素記錄一节的座標與顏色:
var Snake = {
tbl: null,
body: [], // 蛇身:[{x, y, color}, ...],索引 0 是蛇頭
direction: 0, // 0=上 1=右 2=下 3=左
timer: null,
speed: 250, // 毫秒,越小越快
paused: true,
rowCount: 30,
colCount: 30
};
「body[0] 是蛇頭」這個約定是整份程式最重要的設計決定,移動、碰撞檢測、繪製都依賴它。
init 負責四件事:
push 進 body。document.onkeydown 鍵盤事件。init: function () {
var colors = ['red','orange','yellow','green','blue','purple','#ccc'];
this.tbl = $("main");
// 建立表格
for (var row = 0; row < this.rowCount; row++) {
var tr = this.tbl.insertRow(-1);
for (var col = 0; col < this.colCount; col++) tr.insertCell(-1);
}
// 散布食物
for (var i = 0; i < 10; i++) {
var x = Math.floor(Math.random() * this.colCount);
var y = Math.floor(Math.random() * this.rowCount);
if (!this.isCellFilled(x, y)) {
this.tbl.rows[y].cells[x].style.backgroundColor =
colors[Math.floor(Math.random() * 7)];
}
}
// 產生蛇頭
while (true) {
var x = Math.floor(Math.random() * this.colCount);
var y = Math.floor(Math.random() * this.rowCount);
if (!this.isCellFilled(x, y)) {
this.tbl.rows[y].cells[x].style.backgroundColor = "black";
this.body.push({ x: x, y: y, color: 'black' });
break;
}
}
this.direction = Math.floor(Math.random() * 4);
this.paused = true;
};
document.onkeydown = function (e) {
if (!e) e = window.event;
switch (e.keyCode | e.which | e.charCode) {
case 13: // Enter:開始 / 暫停
if (Snake.paused) { Snake.move(); Snake.paused = false; }
else { Snake.pause(); Snake.paused = true; }
break;
case 37: // 左
if (Snake.direction == 1) break; // 正在向右,禁止
Snake.direction = 3;
break;
case 38: // 上(Ctrl+↑ 加速)
if (event.ctrlKey) { Snake.speedUp(-20); break; }
if (Snake.direction == 2) break; // 正在向下,禁止
Snake.direction = 0;
break;
case 39: // 右
if (Snake.direction == 3) break;
Snake.direction = 1;
break;
case 40: // 下(Ctrl+↓ 減速)
if (event.ctrlKey) { Snake.speedUp(20); break; }
if (Snake.direction == 0) break;
Snake.direction = 2;
break;
}
};
每個方向分支開頭的那個 if,是在阻止蛇直接 180 度回頭撞上自己——這是貪吃蛇最基本的規則之一。上下方向額外檢查 ctrlKey,做成加速/減速的快捷鍵。
移動的視覺效果,靠的是「尾巴縮一節、頭長一節」:
moveOneStep: function () {
if (this.checkNextStep() == -1) {
clearInterval(this.timer);
alert("Game over!");
return;
}
// 吃到食物:長高,並補上新食物
if (this.checkNextStep() == 1) {
var p = this.getNextPos();
var color = this.getColor(p.x, p.y);
this.body.unshift({ x: p.x, y: p.y, color: color });
this.generateDood();
return;
}
// 一般移動
var point = this.getNextPos();
var color = this.body[0].color; // 保留蛇頭顏色
for (var i = 0; i < this.body.length - 1; i++) {
this.body[i].color = this.body[i+1].color; // 顏色往前遞移
}
this.body.pop(); // 尾巴退一節
this.body.unshift({ x: point.x, y: point.y, color: color }); // 頭長一節
}
這個「顏色往前遞移」的細節,就是 v2.4 修正的重點:讓蛇身的顏色隨著前進而流動,視覺上比整條固定同色生動得多。
getNextPos: function () {
var x = this.body[0].x, y = this.body[0].y;
if (this.direction == 0) y--; // 上
else if (this.direction == 1) x++; // 右
else if (this.direction == 2) y++; // 下
else x--; // 左
return { x: x, y: y };
}
checkNextStep: function () {
var p = this.getNextPos();
// 撞牆
if (p.x < 0 || p.x >= this.colCount || p.y < 0 || p.y >= this.rowCount) return -1;
// 撞到自己
for (var i = 0; i < this.body.length; i++) {
if (this.body[i].x == p.x && this.body[i].y == p.y) return -1;
}
// 有食物
if (this.isCellFilled(p.x, p.y)) return 1;
return 0; // 空地
}
用 -1 / 0 / 1 三種回傳值區分「結束」「空地」「吃到」,讓呼叫端能用簡潔的 if 分流,是相當乾淨的設計。
erase: function () {
for (var i = 0; i < this.body.length; i++)
this.eraseDot(this.body[i].x, this.body[i].y);
},
paint: function () {
for (var i = 0; i < this.body.length; i++)
this.paintDot(this.body[i].x, this.body[i].y, this.body[i].color);
},
eraseDot: function (x, y) { this.tbl.rows[y].cells[x].style.backgroundColor = ""; },
paintDot: function (x, y, color) { this.tbl.rows[y].cells[x].style.backgroundColor = color; },
isCellFilled: function (x, y) {
return this.tbl.rows[y].cells[x].style.backgroundColor != "";
}
每一帧的順序是 erase → moveOneStep → paint:先擦掉舊位置,更新資料,再畫上新位置。由於食物與蛇身共用「格子有顏色」這個判斷,isCellFilled 無法區分兩者,因此吃到時才需要額外抓一次顏色存進 body。
move: function () {
this.timer = setInterval(function () {
Snake.erase(); Snake.moveOneStep(); Snake.paint();
}, this.speed);
},
pause: function () { clearInterval(Snake.timer); this.paint(); },
speedUp: function (time) {
if (!this.paused) {
if (this.speed + time < 10 || this.speed + time > 2000) return; // 上下限保護
this.speed += time;
this.pause();
this.move(); // 用新速度重啟計時器
}
},
restart: function () {
if (this.timer) clearInterval(this.timer);
for (var i = 0; i < this.rowCount; i++) this.tbl.deleteRow(0);
this.body = [];
this.init();
this.speed = 250;
}
加速的實作方式是「先停、改 speed、再啟」,因為 setInterval 的間隔一旦設定就無法中途變更。這也是為什麼 speedUp 必須先 pause()。
fillRect。DOM 版適合教學,Canvas 版適合實際遊玩。e.key(值為 "ArrowUp" 等),並記得 preventDefault() 以免方向鍵捲動頁面。