純原生 JS(無任何庫依賴)實現經典 2048 遊戲,代碼結構清晰分離:
將四個方向(上下左右)統一轉換為「向左合併」問題:
// 方向映射:0=左, 1=右, 2=上, 3=下
// md % 2 === 0 為水平,md < 2 為正向
// 通過轉置矩陣 + 反轉行,統一為「向左」邏輯處理
trans(arr)function trans(row) {
// row: [{number, moveStep, newNumber, needKill}, ...]
// 1. 計算每個格子需移動步數(壓縮空格)
// 2. 從左向右掃描,相同數字合併:標記 needKill、newNumber*2、moveStep++
// 3. 輸出合併後的新行數組(補 0 至固定長度)
// 返回 [更新後的行對象數組, 純數字數組供渲染]
}
UI.update = function(dir) {
if (UI.locked) return; // 動畫進行中鎖定輸入
UI.locked = true;
var frames = UI.times; // 總幀數,默認 20
var frame = 0;
var startPos = {}; // 記錄每格初始位置
// 計算目標狀態
var result = tran(UI.map, dir);
var targetNumbers = result[1]; // 純數字矩陣
(function animate() {
if (frame > frames) {
// 動畫結束:渲染最終狀態、生成新數字、解鎖
renderFinal(targetNumbers);
return UI.addNew() || (UI.locked = false);
}
// 插值計算當前幀位置
UI.xx(function(i, j) {
var cell = UI.map[i][j];
var el = document.getElementById('i' + i + 'j' + j);
var prop = dir < 3 ? 'left' : 'top';
var start = startPos[i][j] || (startPos[i][j] = parseInt(el.style[prop]));
var dist = cell.moveStep * UI.size; // 總位移距離
var current = start + (dist * frame / frames) * (dir % 2 ? -1 : 1);
el.style[prop] = current + 'px';
});
frame++;
setTimeout(animate, 10); // ~100fps
})();
};
UI.undo = []; // 棧,最大長度 UI.maxUndo (默認 5)
function tran(map, dir) {
var undoSnapshot = x4(UI.nw);
// 保存移動前的數字狀態
for (var i = 0; i < UI.nw; i++)
for (var j = 0; j < UI.nw; j++)
undoSnapshot[i][j] = map[i][j].number;
UI.undo.push(undoSnapshot);
if (UI.undo.length > UI.maxUndo) UI.undo.shift();
// ... 正常合併邏輯
return [map, targetNumbers];
}
// 撤銷操作(可綁定 Ctrl+Z 或按鈕)
UI.undoMove = function() {
if (!UI.undo.length) return;
var prev = UI.undo.pop();
UI.xx(function(i, j) {
UI.map[i][j] = make(prev[i][j]);
});
UI.render(); // 直接渲染無動畫
};
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>2048 原生 JS</title>
<style>
/* 容器居中、格子絕對定位、數字顏色漸變 .r2 .r4 ... .r2048 */
#box { position:absolute; left:50%; top:50%; margin:-300px 0 0 -300px; }
.x, .y { position:absolute; width:80px; height:80px; line-height:80px;
font-size:30px; text-align:center; font-weight:bold; font-family:Arial; }
.x { z-index:30; background:#ddd; }
.y { z-index:10; background:#ccc; } /* 底格 */
.r2 {background:#eee4da} .r4 {background:#ede0c8} .r8 {color:#f9f6f2;background:#f2b179}
.r16 {color:#f9f6f2;background:#f59563} .r32 {color:#f9f6f2;background:#f67c5f}
.r64 {color:#f9f6f2;background:#f65e3b} .r128 {color:#f9f6f2;background:#edcf72}
.r256 {color:#f9f6f2;background:#edcc61} .r512 {color:#f9f6f2;background:#edc850}
.r1024 {color:#f9f6f2;background:#edc53f} .r2048 {color:#f9f6f2;background:#edc22e}
</style></head><body>
<div id="box"></div>
<script>
// 1. 工具函數 x4, xx, make
// 2. 核心邏輯 tran, trans
// 3. UI 對象:init, update, addNew, render, undoMove
// 4. 鍵盤/觸控綁定 -> UI.update(dir)
// 5. UI.init(4, 5, 100, 20); // 4x4, 5步撤銷, 100px格子, 20幀動畫
</script>
</body></html>
UI.map 為單一數據源,視圖純渲染衍生狀態。UI.init(nw, maxUndo, size, times) 一行適配不同規格。localStorage 持久化最高分、當前盤面touchstart/move/end 計算滑動向量)trans、tran 核心純函數