DIV CSS 佈局教程網

JavaScript 貪吃蛇完整實作:物件導向版架構解析
編輯:JavaScript綜合知識     

這是一個以物件導向方式撰寫、註解完整的 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()

init 負責四件事:

  1. 用巢狀迴圈建立 30×30 的 table 與所有 td。
  2. 隨機散布若干「食物」——在空格子上填色,顏色從 red、orange、yellow、green、blue、purple、#ccc 隨機挑選。
  3. 在空格子上產生蛇頭,設為黑色並 push 進 body。
  4. 隨機決定初始方向,並掛上 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()

移動的視覺效果,靠的是「尾巴縮一節、頭長一節」:

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()。

可以怎麼改進

  • 用 Canvas 取代 table。每帧修改數十個 td 的 style 會觸發大量樣式重算,效能遠不如 Canvas 的 fillRect。DOM 版適合教學,Canvas 版適合實際遊玩。
  • 用 requestAnimationFrame 取代 setInterval。它能與螢幕刷新同步,在背景分頁時自動降頻,也不會堆積延遲。
  • 食物應該只有一個。原版在場上散布多個食物、吃到就補一個,這比較接近「收集」玩法而非傳統貪吃蛇。改成「場上永遠只有一個食物」更貼近原作體驗。
  • 鍵盤事件要用 keyCode 判斷時,記得不同瀏覽器差異。建議改用 e.key(值為 "ArrowUp" 等),並記得 preventDefault() 以免方向鍵捲動頁面。
  • 加入手勢支援。行動裝置上沒有方向鍵,需監聽 touchstart/touchend 判斷滑動方向。
  • 用正規表達式取代 alert 的字串拼接等細節之外,更實用的是把遊戲狀態與渲染分離,讓邏輯可測試。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved