萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

原生 JavaScript 實現經典貪吃蛇遊戲完整源碼解析

貪吃蛇是鍛鍊邏輯思維、DOM 操作、定時器、鍵盤事件、碰撞檢測的絕佳練習項目。本文提供一個結構清晰、註釋完整的 ES5 版貪吃蛇實現,涵蓋初始化、移動、進食、生長、碰撞判斷、速度/大小調節全流程。

遊戲架構設計

  • Direction:方向常量枚舉 (UP=38, RIGHT=39, DOWN=40, LEFT=37)。
  • Common:全局配置 (寬/高格數、速度、定時器引用)。
  • Control:控制器,負責初始化面板、啟動遊戲循環、鍵盤監聽、食物創建。
  • Snake:蛇實體,管理身體座標數組、移動邏輯、方向控制、碰撞自檢、進食判定。
  • Food:食物實體,隨機生成不與蛇身重疊的位置。
  • Position:座標結構 {x, y}。

完整源碼 (可直接保存為 .html 運行)

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<title>JS 貪吃蛇練習版</title>
<style>
#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>
var Direction = { UP: 38, RIGHT: 39, DOWN: 40, LEFT: 37 };
var Common = { width: 20, height: 20, speed: 250, workThread: null };

window.onload = function() {
    var control = new Control();
    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 = Common.height = +this.value; 
        control.Init("pannel"); 
    };
};

function Control() {
    this.snake = new Snake();
    this.food = new Food();
    this.pannel = null;

    this.Init = function(pid) {
        var html = ['<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 + '">&nbsp;</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) { me.snake.SetDir((ev || window.event).keyCode); };
        if (document.attachEvent) document.attachEvent("onkeydown", this.MoveSnake);
        else 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 Position()]; // 初始長度 1

    this.Move = function() {
        // 擦除尾部
        var tail = this.pos[0];
        var tailEl = document.getElementById('box_' + tail.X + '_' + tail.Y);
        if (tailEl) tailEl.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;
        }

        // 繪製新蛇身 & 碰撞檢測
        for (var i = 0; i < this.pos.length; i++) {
            var p = this.pos[i];
            // 自咬檢測
            for (var j = i+1; j < this.pos.length; j++) {
                if (this.pos[j].X === p.X && this.pos[j].Y === p.Y) { this.Over(); return; }
            }
            var el = document.getElementById('box_' + p.X + '_' + p.Y);
            if (el) el.className = 'snake';
            else { this.Over(); return; } // 撞牆
        }
        this.isDone = true; // 幀結束,允許下一次轉向
    };

    this.Over = function() {
        clearInterval(Common.workThread);
        alert("遊戲結束!得分:" + (this.pos.length - 1));
    };

    this.Eat = function(food) {
        var head = this.pos[this.pos.length - 1];
        var nextX = head.X, nextY = head.Y;
        switch (this.dir) {
            case Direction.UP:    nextY--; break;
            case Direction.RIGHT: nextX++; break;
            case Direction.DOWN:  nextY++; break;
            case Direction.LEFT:  nextX--; break;
        }
        if (nextX === food.pos.X && nextY === food.pos.Y) {
            this.pos.push(new Position(food.pos.X, food.pos.Y)); // 增長
            food.Create(this.pos);
        }
    };

    this.SetDir = function(dir) {
        if (!this.isDone) return; // 同一幀內只允許轉向一次
        var opposite = { 38:40, 40:38, 37:39, 39:37 };
        if (dir !== opposite[this.dir]) { this.dir = dir; this.isDone = false; }
    };
}

function Food() {
    this.pos = new Position();
    this.Create = function(snakeBody) {
        // 清除舊食物
        var old = document.getElementById('box_' + this.pos.X + '_' + this.pos.Y);
        if (old) old.className = '';
        
        var x, y, overlap;
        do {
            overlap = false;
            x = Math.floor(Math.random() * Common.width);
            y = Math.floor(Math.random() * Common.height);
            if (snakeBody) {
                for (var i = 0; i < snakeBody.length; i++) {
                    if (snakeBody[i].X === x && snakeBody[i].Y === y) { overlap = true; break; }
                }
            }
        } while (overlap);
        
        this.pos = new Position(x, y);
        var el = document.getElementById('box_' + x + '_' + y);
        if (el) el.className = 'food';
    };
}

function Position(x, y) {
    this.X = (arguments.length > 0) ? x : 0;
    this.Y = (arguments.length > 1) ? y : 0;
}
</script>
</head>
<body>
<div id="pannel"></div>
<br/>
<button id="btnStart">開始遊戲</button>
<select id="selSpeed">
    <option value="100">極快</option>
    <option value="250" selected>正常</option>
    <option value="500">慢速</option>
</select>
<select id="selSize">
    <option value="10">10x10</option>
    <option value="20" selected>20x20</option>
    <option value="30">30x30</option>
</select>
</body>
</html>

核心邏輯解析

  1. 雙緩衝繪製:先擦除尾部 DOM class,再更新座標數組,最後批量設置頭部及身體 class,減少重排。
  2. 幀鎖 isDone:防止同一幀內多次鍵盤事件導致 180° 掉頭或多步移動。
  3. 碰撞檢測 O(n²):雙層循環檢測自咬,長度較短時可接受;長蛇可優化為 Set/Map 存儲座標鍵 "x,y" O(1) 查找。
  4. 食物生成去重:do-while 循環確保不生成在蛇身上。

現代化重構方向

  • 渲染層分離:使用 <canvas> 或 requestAnimationFrame 繪製,性能提升百倍,支援粒子特效。
  • 狀態管理:引入 Redux/Vuex/Pinia 或簡單 Store 模式,邏輯與視圖解耦。
  • 輸入處理:使用 keydown 事件 e.code (如 'ArrowUp') 替代 keyCode,支援國際鍵盤佈局。
  • TypeScript 重寫:接口化 Direction、Position、GameState,編譯期發現邏輯錯誤。

這個百行級小遊戲包含了遊戲循環、狀態機、輸入處理、碰撞檢測、DOM 操作等核心前端技能,是進階開發者的優秀練手項目。

copyright © 萬盛學電腦網 all rights reserved