DIV CSS 佈局教程網

用純 JavaScript 寫一個貪吃蛇遊戲
編輯:關於JavaScript     

這是一份以純 JavaScript 實作的貪吃蛇,作為練習專案的備份留下來。整個遊戲沒有任何外部依賴,用表格(table)當畫布,鍵盤方向鍵控制移動。

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS 貪吃蛇 - 練習</title>
<style type="text/css">
#pannel table { border-collapse: collapse; }
#pannel table td {
    border: 1px solid #808080;
    width: 10px; height: 10px;
    font-size: 0; line-height: 0;
    overflow: hidden;
}
#pannel table .snake { background-color: green; }
#pannel table .food  { background-color: blue; }
</style>

<script type="text/javascript">
// 方向常數直接用鍵盤 keyCode,省一層對映
var Direction = new function () {
    this.UP    = 38;
    this.RIGHT = 39;
    this.DOWN  = 40;
    this.LEFT  = 37;
};

// 全域設定
var Common = new function () {
    this.width  = 20;    // 水平方格數
    this.height = 20;    // 垂直方格數
    this.speed  = 250;   // 間隔毫秒,值越小越快
    this.workThread = null;
};

var Main = new function () {
    var control = new Control();

    window.onload = function () {
        control.Init("pannel");

        // 開始按鈕
        document.getElementById("btnStart").onclick = function () {
            control.Start();
            this.disabled = true;
            document.getElementById("selSpeed").disabled = true;
            document.getElementById("selSize").disabled = true;
        };

        // 調速度
        document.getElementById("selSpeed").onchange = function () {
            Common.speed = this.value;
        };

        // 調棋盤大小
        document.getElementById("selSize").onchange = function () {
            Common.width  = this.value;
            Common.height = this.value;
            control.Init("pannel");
        };
    };
};

/* 控制器 */
function Control() {
    this.snake = new Snake();
    this.food  = new Food();

    /* 初始化:建立表格 */
    this.Init = function (pid) {
        var html = [];
        html.push("<table>");
        for (var y = 0; y < Common.height; y++) {
            html.push("<tr>");
            for (var x = 0; x < Common.width; x++) {
                html.push('<td id="box_' + x + "_" + y + '"> </td>');
            }
            html.push("</tr>");
        }
        html.push("</table>");

        this.pannel = document.getElementById(pid);
        this.pannel.innerHTML = html.join("");
    };

    /* 開始遊戲:監聽鍵盤、生成食物、啟動刷新計時器 */
    this.Start = function () {
        var me = this;

        this.MoveSnake = function (ev) {
            var evt = window.event || ev;
            me.snake.SetDir(evt.keyCode);
        };

        try {
            document.attachEvent("onkeydown", this.MoveSnake);      // 舊 IE
        } catch (e) {
            document.addEventListener("keydown", this.MoveSnake, false);
        }

        this.food.Create();

        Common.workThread = setInterval(function () {
            me.snake.Eat(me.food);
            me.snake.Move();
        }, Common.speed);
    };
}

/* 蛇 */
function Snake() {
    this.isDone = false;
    this.dir = Direction.RIGHT;
    this.pos = new Array(new Position());

    /* 移動:擦除尾端、整體前移、重新定位頭部、繪製並判定結束 */
    this.Move = function () {
        // 先清掉目前尾巴的格子
        document.getElementById("box_" + this.pos[0].X + "_" + this.pos[0].Y).className = "";

        // 每一節往前追上一節的位置
        for (var i = 0; i < this.pos.length - 1; i++) {
            this.pos[i].X = this.pos[i + 1].X;
            this.pos[i].Y = this.pos[i + 1].Y;
        }

        // 依方向推進頭部
        var head = this.pos[this.pos.length - 1];
        switch (this.dir) {
            case Direction.UP:    head.Y--; break;
            case Direction.RIGHT: head.X++; break;
            case Direction.DOWN:  head.Y++; break;
            case Direction.LEFT:  head.X--; break;
        }
        this.pos[this.pos.length - 1] = head;

        // 逐格繪製,同時檢查是否咬到自己或超出邊界
        for (var i = 0; i < this.pos.length; i++) {
            var isExits = false;
            for (var j = i + 1; j < this.pos.length; j++) {
                if (this.pos[j].X == this.pos[i].X && this.pos[j].Y == this.pos[i].Y) {
                    isExits = true;
                    break;
                }
            }
            if (isExits) { this.Over(); break; }   // 咬到自己

            var obj = document.getElementById("box_" + this.pos[i].X + "_" + this.pos[i].Y);
            if (obj) {
                obj.className = "snake";
            } else {
                this.Over(); break;                // 移出邊界
            }
        }

        this.isDone = true;
    };

    /* 遊戲結束 */
    this.Over = function () {
        clearInterval(Common.workThread);
        alert("遊戲結束!");
    };

    /* 吃到食物則屁股跟著變長,並重新生成食物 */
    this.Eat = function (food) {
        var head = this.pos[this.pos.length - 1];
        var isEat = false;

        switch (this.dir) {
            case Direction.UP:    if (head.X == food.pos.X && head.Y == food.pos.Y + 1) isEat = true; break;
            case Direction.RIGHT: if (head.Y == food.pos.Y && head.X == food.pos.X - 1) isEat = true; break;
            case Direction.DOWN:  if (head.X == food.pos.X && head.Y == food.pos.Y - 1) isEat = true; break;
            case Direction.LEFT:  if (head.Y == food.pos.Y && head.X == food.pos.X + 1) isEat = true; break;
        }

        if (isEat) {
            // 在尾端補上一節,蛇就變長了
            this.pos[this.pos.length] = new Position(food.pos.X, food.pos.Y);
            food.Create(this.pos);
        }
    };

    /* 控制方向:禁止 180 度回頭 */
    this.SetDir = function (dir) {
        switch (dir) {
            case Direction.UP:
                if (this.isDone && this.dir != Direction.DOWN) { this.dir = dir; this.isDone = false; }
                break;
            case Direction.RIGHT:
                if (this.isDone && this.dir != Direction.LEFT) { this.dir = dir; this.isDone = false; }
                break;
            case Direction.DOWN:
                if (this.isDone && this.dir != Direction.UP)   { this.dir = dir; this.isDone = false; }
                break;
            case Direction.LEFT:
                if (this.isDone && this.dir != Direction.RIGHT){ this.dir = dir; this.isDone = false; }
                break;
        }
    };
}

/* 食物 */
function Food() {
    this.pos = new Position();

    /* 隨機生成,並排除蛇佔用的格子 */
    this.Create = function (pos) {
        // 清掉舊食物的格子
        document.getElementById("box_" + this.pos.X + "_" + this.pos.Y).className = "";

        var x = 0, y = 0, isCover = false;

        do {
            x = parseInt(Math.random() * (Common.width  - 1));
            y = parseInt(Math.random() * (Common.height - 1));
            isCover = false;

            if (pos instanceof Array) {
                for (var i = 0; i < pos.length; i++) {
                    if (x == pos[i].X && y == pos[i].Y) {
                        isCover = true;
                        break;
                    }
                }
            }
        } while (isCover);

        this.pos = new Position(x, y);
        document.getElementById("box_" + x + "_" + y).className = "food";
    };
}

function Position(x, y) {
    this.X = 0;
    this.Y = 0;
    if (arguments.length >= 1) this.X = x;
    if (arguments.length >= 2) this.Y = y;
}
</script>
</head>
<body>
<div id="pannel" style="margin-bottom: 10px;"></div>

<select id="selSize">
  <option value="20">20*20</option>
  <option value="30">30*30</option>
  <option value="40">40*40</option>
</select>

<select id="selSpeed">
  <option value="500">速度-慢</option>
  <option value="250" selected="selected">速度-中</option>
  <option value="100">速度-快</option>
</select>

<input type="button" id="btnStart" value="開始" />
</body>
</html>

幾個設計意圖

用 table 當畫布。每個 <td> 有 id="box_x_y",靠改 className 來切換「空 / 蛇 / 食物」三種狀態。好處是實作直觀,壞處是每次移動都要好幾次 DOM 查詢與樣式重算,棋盤一大就會卡。

先清尾、再全體前移、最後畫頭。這個順序讓「移動」變成「每節往前追上一節」,實作起來比逐格算座標簡單得多。

SetDir 用 isDone 做節流。它確保一個計時週期內只接受一次轉向,同時禁止 180 度回頭——少了這層保護,玩家連按兩下就能讓蛇撞進自己脖子。

值得改進的地方

用 Canvas 取代 table。這是最有感的優化。<canvas> 透過 fillRect 畫方塊,不必為每個格子配置 DOM 節點,效能差距在棋盤變大時非常明顯。

用 requestAnimationFrame 取代 setInterval。後者會與瀏覽器的實際刷新週期錯開,容易出現畫面撕裂與不必要的重繪;前者由瀏覽器統一調度,在分頁被切到背景時也會自動暫停。

用 keydown 一種寫法就好。attachEvent 是 IE8 以下的私有 API,今天的專案不必再照顧。

鍵值硬編碼可以換掉。直接用 38/39/40/37 雖然省事,但寫成 ArrowUp 這類字串(event.key)可讀性更好,也方便擴充 WASD 支援。

碰撞檢測有邏輯漏洞。現在是每格都跟其他格比對,O(n²)。更關鍵的是:蛇頭移動到尾節原本所在位置應該是合法的(因為尾巴同時會移開),但目前的實作會誤判為咬到自己。修正方式是在檢查時排除「即將移開的尾節」。

食物生成可能無限迴圈。當蛇佔满棋盤時,do...while 會永遠找不到空格。這其實就是「通關」條件,應該在進入迴圈前先檢查剩餘空格數。

作為一個理解遊戲主迴圈、狀態管理與鍵盤事件的練習專案,這份程式碼的結構是清楚的;把它改寫成 Canvas 版本,會是很好的下一步練習。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved