萬盛學電腦網

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

JavaScript 從零實作 2048 遊戲:邏輯與渲染完整教學

專案簡介

2048 是經典滑塊合成遊戲。本文提供基於原生 JavaScript 的完整實作,包含 HTML 結構、CSS 樣式(含數字顏色漸層)與核心遊戲邏輯(移動、合成、生成新數字、勝負判定)。

檔案結構

  • 2048.html - 入口頁面
  • css/2048.css - 樣式(數字顏色對應)
  • js/2048.js - 遊戲核心邏輯

HTML 架構

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
  <meta charset="utf-8">
  <title>2048</title>
  <link rel="stylesheet" href="css/2048.css" />
  <script src="js/2048.js"></script>
</head>
<body>
  <div id="div2048">
    <a id="start">tap to start :-)</a>
  </div>
</body>
</html>

CSS 樣式精華:數字顏色映射

#div2048 {
  width: 500px; height: 500px;
  background: #b8af9e; margin: 0 auto; position: relative;
}
#start {
  width: 100%; height: 100%; display: block;
  line-height: 500px; text-align: center;
  font-size: 30px; background: #f2b179; color: #fff;
}
#div2048 div.tile {
  position: absolute; /* 由 JS 計算 left/top */
  width: 100px; height: 100px;
  margin: 20px 0 0 20px; /* 間距 20px */
  font-size: 40px; line-height: 100px; text-align: center;
  border-radius: 6px;
  transition: all 0.15s ease; /* 移動動畫 */
}

/* 數字對應顏色 */
.tile0  { background: #ccc0b2; color: #776e65; }
.tile2  { background: #eee4da; color: #776e65; }
.tile4  { background: #ece0c8; color: #776e65; }
.tile8  { background: #f2b179; color: #f9f6f2; }
.tile16 { background: #f59563; color: #f9f6f2; }
.tile32 { background: #f67c5f; color: #f9f6f2; }
.tile64 { background: #f65e3b; color: #f9f6f2; }
.tile128, .tile256, .tile512 { background: #edcf72; color: #f9f6f2; font-size: 35px; }
.tile1024, .tile2048 { background: #edcc61; color: #f9f6f2; font-size: 30px; }

核心 JS 邏輯架構 (2048.js)

// 遊戲狀態
var board = [];        // 4x4 矩陣
var score = 0;
var hasConflicted = []; // 合併標記,防止同回合重複合併

// 初始化
function newGame() {
  initBoard();
  generateOneNumber();
  generateOneNumber();
  updateBoardView();
}

// 初始化棋盤矩陣
function initBoard() {
  for (var i = 0; i < 4; i++) {
    board[i] = [];
    hasConflicted[i] = [];
    for (var j = 0; j < 4; j++) {
      board[i][j] = 0;
      hasConflicted[i][j] = false;
    }
  }
}

// 隨機生成 2 或 4
function generateOneNumber() {
  if (noSpace(board)) return false;
  var randx = parseInt(Math.floor(Math.random() * 4));
  var randy = parseInt(Math.floor(Math.random() * 4));
  var times = 0;
  while (times < 50) {
    if (board[randx][randy] == 0) break;
    randx = parseInt(Math.floor(Math.random() * 4));
    randy = parseInt(Math.floor(Math.random() * 4));
    times++;
  }
  if (times == 50) {
    for (var i = 0; i < 4; i++)
      for (var j = 0; j < 4; j++)
        if (board[i][j] == 0) { randx = i; randy = j; }
  }
  board[randx][randy] = Math.random() < 0.5 ? 2 : 4;
  showNumberWithAnimation(randx, randy, board[randx][randy]);
  return true;
}

// 核心:向左移動邏輯(其他方向類似)
function moveLeft() {
  if (!canMoveLeft(board)) return false;
  for (var i = 0; i < 4; i++)
    for (var j = 1; j < 4; j++)
      if (board[i][j] != 0)
        for (var k = 0; k < j; k++)
          if (board[i][k] == 0 && noBlockHorizontal(i, k, j, board)) {
            showMoveAnimation(i, j, i, k);
            board[i][k] = board[i][j];
            board[i][j] = 0;
            continue;
          }
          else if (board[i][k] == board[i][j] && noBlockHorizontal(i, k, j, board) && !hasConflicted[i][k]) {
            showMoveAnimation(i, j, i, k);
            board[i][k] *= 2;
            board[i][j] = 0;
            score += board[i][k];
            updateScore(score);
            hasConflicted[i][k] = true;
            continue;
          }
  setTimeout(updateBoardView, 200);
  return true;
}

// 輔助:水平無阻擋
function noBlockHorizontal(row, col1, col2, board) {
  for (var i = col1 + 1; i < col2; i++)
    if (board[row][i] != 0) return false;
  return true;
}

// 同理實作 moveRight, moveUp, moveDown...

// 鍵盤事件綁定
document.addEventListener('keydown', function(event) {
  switch(event.keyCode) {
    case 37: event.preventDefault(); moveLeft(); break;
    case 38: event.preventDefault(); moveUp(); break;
    case 39: event.preventDefault(); moveRight(); break;
    case 40: event.preventDefault(); moveDown(); break;
  }
});

關鍵演算法細節

  1. 移動與合併分離:先移動到最遠空位,再檢查相鄰相同數字合併。
  2. hasConflicted 陣列:防止單回合中同一格被合併兩次(如 2+2=4,該 4 不能再合併)。
  3. 動畫分離:資料模型更新後,透過 `setTimeout` 觸發視圖更新,CSS `transition` 自動處理平滑移動。
  4. 勝負判定:出現 2048 → 勝利;無空格且無法移動 → 遊戲結束。

啟動遊戲

// 2048.js 末尾
$(function() {
  $('#start').click(function() {
    $(this).hide();
    newGame();
  });
});

延伸挑戰

  • 加入「撤銷」功能(記錄歷史狀態堆疊)
  • 實作 AI 自動遊玩(期望最大化算法)
  • 支援觸控滑動(`touchstart`/`touchend` 計算向量)
  • 響應式佈局適配行動裝置

這個專案完整展示了「資料模型驅動視圖」的前端架構思想,是進階 JavaScript 開發的經典練習題。

copyright © 萬盛學電腦網 all rights reserved