萬盛學電腦網

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

JavaScript 貪吃蛇遊戲完整實作:面向物件、註解完整、可直接執行

遊戲特色

  • 純原生 JS,無外部依賴
  • 面向物件設計,程式碼結構清晰
  • 完整註解,適合學習參考
  • 支援鍵盤控制、暫停/繼續、加速、分數計算
  • 蛇身顏色漸變效果

完整原始碼

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>貪吃蛇 Snake v2.4</title>
  <style>
    body { font-family: sans-serif; font-size: 14px; text-align: center; }
    #gameContainer { display: inline-block; margin-top: 20px; }
    table { border-collapse: collapse; border: 2px solid #333; background: #f0f0f0; }
    td { width: 12px; height: 12px; font-size: 0; }
    .snake-head { background: #2c3e50; border-radius: 2px; }
    .snake-body { background: #3498db; border-radius: 1px; }
    .food { background: #e74c3c; border-radius: 50%; }
    .obstacle { background: #95a5a6; }
    #info { margin: 10px 0; font-size: 16px; }
    #controls { margin-top: 10px; }
    button { padding: 8px 16px; margin: 0 5px; cursor: pointer; }
  </style>
</head>
<body>
  <h1>🐍 JavaScript 貪吃蛇</h1>
  <div id="info">分數: <span id="score">0</span> | 速度: <span id="speed">250</span>ms | 狀態: <span id="status">按 Enter 開始</span></div>
  <div id="gameContainer"><table id="board"></table></div>
  <div id="controls">
    <button id="btnStart">開始/暫停 (Enter)</button>
    <button id="btnRestart">重新遊戲</button>
  </div>

  <script>
    // 工具函式
    const $ = id => document.getElementById(id);

    /***************************************************************
     * 貪吃蛇核心類別
     ***************************************************************/
    const SnakeGame = {
      // 設定
      rowCount: 30,
      colCount: 30,
      initialSpeed: 250,
      speedStep: 20,
      minSpeed: 50,

      // 狀態
      board: null,
      body: [],           // [{x, y, color}]
      direction: 0,       // 0上 1右 2下 3左
      timer: null,
      speed: 250,
      paused: true,
      score: 0,
      food: null,
      obstacles: [],

      // 顏色漸變色盤
      colors: ['#e74c3c', '#e67e22', '#f1c40f', '#2ecc71', '#3498db', '#9b59b6', '#1abc9c'],

      // 初始化
      init() {
        this.board = $('board');
        this.buildBoard();
        this.bindEvents();
        this.reset();
      },

      // 建立棋盤格
      buildBoard() {
        this.board.innerHTML = '';
        for (let r = 0; r < this.rowCount; r++) {
          const tr = this.board.insertRow();
          for (let c = 0; c < this.colCount; c++) {
            tr.insertCell();
          }
        }
      },

      // 重置遊戲
      reset() {
        this.clearTimer();
        this.body = [];
        this.direction = Math.floor(Math.random() * 4);
        this.speed = this.initialSpeed;
        this.score = 0;
        this.paused = true;
        this.obstacles = [];
        this.updateInfo();
        this.clearBoard();
        this.generateObstacles(10);
        this.spawnSnake();
        this.spawnFood();
        $('status').textContent = '按 Enter 開始';
        $('btnStart').textContent = '開始 (Enter)';
      },

      // 清空棋盤顏色
      clearBoard() {
        for (const row of this.board.rows) {
          for (const cell of row.cells) {
            cell.style.background = '';
            cell.className = '';
          }
        }
      },

      // 產生障礙物
      generateObstacles(count) {
        for (let i = 0; i < count; i++) {
          let x, y;
          do {
            x = Math.floor(Math.random() * this.colCount);
            y = Math.floor(Math.random() * this.rowCount);
          } while (this.isCellFilled(x, y));
          this.board.rows[y].cells[x].className = 'obstacle';
          this.obstacles.push({x, y});
        }
      },

      // 產生蛇頭
      spawnSnake() {
        let x, y;
        do {
          x = Math.floor(Math.random() * this.colCount);
          y = Math.floor(Math.random() * this.rowCount);
        } while (this.isCellFilled(x, y));
        
        const headCell = this.board.rows[y].cells[x];
        headCell.className = 'snake-head';
        this.body.push({x, y, color: 'head'});
      },

      // 產生食物
      spawnFood() {
        let x, y;
        do {
          x = Math.floor(Math.random() * this.colCount);
          y = Math.floor(Math.random() * this.rowCount);
        } while (this.isCellFilled(x, y));
        
        this.food = {x, y};
        this.board.rows[y].cells[x].className = 'food';
      },

      // 檢查格子是否被佔用
      isCellFilled(x, y) {
        const cell = this.board.rows[y].cells[x];
        return cell.className !== '' || this.body.some(seg => seg.x === x && seg.y === y);
      },

      // 綁定鍵盤與按鈕事件
      bindEvents() {
        document.onkeydown = e => this.handleKey(e);
        $('btnStart').onclick = () => this.togglePause();
        $('btnRestart').onclick = () => this.reset();
      },

      handleKey(e) {
        const key = e.keyCode || e.which || e.charCode;
        switch (key) {
          case 13: // Enter
            this.togglePause();
            break;
          case 37: // Left
            if (this.direction !== 1) this.direction = 3;
            break;
          case 38: // Up
            if (e.ctrlKey) this.speedUp(-this.speedStep);
            else if (this.direction !== 2) this.direction = 0;
            break;
          case 39: // Right
            if (this.direction !== 3) this.direction = 1;
            break;
          case 40: // Down
            if (e.ctrlKey) this.speedUp(this.speedStep);
            else if (this.direction !== 0) this.direction = 2;
            break;
        }
      },

      togglePause() {
        if (this.paused) {
          this.move();
          this.paused = false;
          $('status').textContent = '遊戲中...';
          $('btnStart').textContent = '暫停 (Enter)';
        } else {
          this.pause();
        }
      },

      pause() {
        this.clearTimer();
        this.paused = true;
        $('status').textContent = '已暫停,按 Enter 繼續';
        $('btnStart').textContent = '繼續 (Enter)';
      },

      speedUp(delta) {
        this.speed = Math.max(this.minSpeed, this.speed + delta);
        $('speed').textContent = this.speed;
        if (!this.paused) {
          this.clearTimer();
          this.move(); // 重新排程
        }
      },

      clearTimer() {
        if (this.timer) clearTimeout(this.timer);
        this.timer = null;
      },

      // 核心移動邏輯
      move() {
        if (this.paused) return;

        // 計算新頭部位置
        const head = this.body[0];
        let nx = head.x, ny = head.y;
        switch (this.direction) {
          case 0: ny--; break; // 上
          case 1: nx++; break; // 右
          case 2: ny++; break; // 下
          case 3: nx--; break; // 左
        }

        // 邊界檢查
        if (nx < 0 || nx >= this.colCount || ny < 0 || ny >= this.rowCount) {
          this.gameOver('撞牆了!');
          return;
        }

        // 自撞/障礙物檢查
        if (this.body.some(seg => seg.x === nx && seg.y === ny) ||
            this.obstacles.some(o => o.x === nx && o.y === ny)) {
          this.gameOver('撞到自己或障礙物!');
          return;
        }

        // 移動:新增頭部
        const newHead = {x: nx, y: ny, color: 'head'};
        this.body.unshift(newHead);
        this.board.rows[ny].cells[nx].className = 'snake-head';

        // 原頭部變身體
        if (this.body.length > 1) {
          const oldHead = this.body[1];
          this.board.rows[oldHead.y].cells[oldHead.x].className = 'snake-body';
          // 身體顏色漸變
          const colorIdx = Math.min(this.body.length - 2, this.colors.length - 1);
          this.board.rows[oldHead.y].cells[oldHead.x].style.background = this.colors[colorIdx];
        }

        // 檢查吃食物
        if (nx === this.food.x && ny === this.food.y) {
          this.score += 10;
          this.updateInfo();
          this.spawnFood();
          // 每 50 分加速
          if (this.score % 50 === 0) this.speedUp(-this.speedStep);
        } else {
          // 未吃食物:移除尾部
          const tail = this.body.pop();
          this.board.rows[tail.y].cells[tail.x].className = '';
          this.board.rows[tail.y].cells[tail.x].style.background = '';
        }

        // 遞迴排程下一幀
        this.timer = setTimeout(() => this.move(), this.speed);
      },

      gameOver(reason) {
        this.clearTimer();
        this.paused = true;
        $('status').textContent = `遊戲結束:${reason} 最終分數 ${this.score}`;
        $('btnStart').textContent = '重新開始 (Enter)';
        alert(`遊戲結束!\n${reason}\n分數:${this.score}`);
      },

      updateInfo() {
        $('score').textContent = this.score;
        $('speed').textContent = this.speed;
      }
    };

    // 啟動遊戲
    SnakeGame.init();
  </script>
</body>
</html>

核心架構解析

模組職責
設定區棋盤大小、速度參數、顏色色盤
狀態區蛇身陣列、方向、計時器、分數、食物、障礙物
init/reset初始化與重置,分離關注點
buildBoard/clearBoardDOM 操作封裝
spawnSnake/spawnFood實體生成邏輯
move核心遊戲迴圈:位置計算 → 碰撞檢測 → DOM 更新 → 遞迴排程
handleKey輸入處理,防止 180 度轉向

關鍵技術點

  1. 遞迴 setTimeout 而非 setInterval:確保每幀執行完成後再排程下一幀,避免卡頓導致堆疊
  2. 蛇身陣列 unshift/pop:O(1) 頭部插入、尾部移除,模擬隊列
  3. CSS class 而非 inline style:樣式分離,易維護
  4. 色盤漸變:根據蛇身長度索引色盤,視覺回饋豐富
  5. Ctrl+方向鍵加速:展示組合鍵處理

擴充建議

  • 加入本地儲存最高分
  • 實作等級系統(障礙物增加、速度基準提升)
  • 支援觸控滑動控制(行動裝置)
  • 加入特殊食物(加分、減速、穿牆)
  • 改用 Canvas 渲染提升大棋盤效能
copyright © 萬盛學電腦網 all rights reserved