2048 的規則簡單到一句話就能說完:方向鍵推動所有方塊,相同數字相撞就合併,合出 2048 獲勝。但也因為規則簡單,它非常適合用來練習 DOM 操作與鍵盤事件。本文用三個檔案、零依賴完成它。
<!DOCTYPE> <html xmlns="https://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>2048</title> <link rel="stylesheet" type="text/css" href="css/2048.css" /> <script type="text/javascript" src="js/2048.js"></script> </head> <body> <div id="div2048"> <a id="start">tap to start :-)</a> </div> </body> </html>
@charset "utf-8";
#div2048 {
width: 500px; height: 500px; background-color: #b8af9e;
margin: 0 auto; position: relative;
}
#start {
width: 500px; height: 500px; line-height: 500px; display: block;
text-align: center; font-size: 30px; background: #f2b179; color: #FFFFFF;
}
#div2048 div.tile {
margin: 20px 0px 0px 20px; width: 100px; height: 40px;
padding: 30px 0; font-size: 40px; line-height: 40px;
text-align: center; float: left;
}
#div2048 div.tile0 { background: #ccc0b2; }
#div2048 div.tile2 { color: #7c736a; background: #eee4da; }
#div2048 div.tile4 { color: #7c736a; background: #ece0c8; }
#div2048 div.tile8 { color: #fff7eb; background: #f2b179; }
#div2048 div.tile16 { color: #fff7eb; background: #f59563; }
#div2048 div.tile32 { color: #fff7eb; background: #f57c5f; }
#div2048 div.tile64 { color: #fff7eb; background: #f65d3b; }
#div2048 div.tile128 { color: #fff7eb; background: #edce71; }
#div2048 div.tile256 { color: #fff7eb; background: #edcc61; }
#div2048 div.tile512 { color: #fff7eb; background: #ecc850; }
#div2048 div.tile1024{ color: #fff7eb; background: #edc53f; }
#div2048 div.tile2048{ color: #fff7eb; background: #eec22e; } function game2048(container) {
this.container = container;
this.tiles = new Array(16); // 4x4 共 16 格,每格一個 div
}
game2048.prototype = {
init: function() {
for (var i = 0, len = this.tiles.length; i < len; i++) {
var tile = this.newTile(0);
tile.setAttribute('index', i);
this.container.appendChild(tile);
this.tiles[i] = tile;
}
this.randomTile();
this.randomTile();
},
newTile: function(val) {
var tile = document.createElement('div');
this.setTileVal(tile, val);
return tile;
},
setTileVal: function(tile, val) {
tile.className = 'tile tile' + val; // 換 class 即換底色
tile.setAttribute('val', val);
tile.innerHTML = val > 0 ? val : '';
},
randomTile: function() {
var zeroTiles = [];
for (var i = 0, len = this.tiles.length; i < len; i++) {
if (this.tiles[i].getAttribute('val') == 0) zeroTiles.push(this.tiles[i]);
}
var rTile = zeroTiles[Math.floor(Math.random() * zeroTiles.length)];
this.setTileVal(rTile, Math.random() < 0.8 ? 2 : 4); // 2 的機率較高
},
move: function(direction) {
var j;
switch (direction) {
case 'W': // 上
for (var i = 4, len = this.tiles.length; i < len; i++) {
j = i;
while (j >= 4) { this.merge(this.tiles[j - 4], this.tiles[j]); j -= 4; }
}
break;
case 'S': // 下
for (var i = 11; i >= 0; i--) {
j = i;
while (j <= 11) { this.merge(this.tiles[j + 4], this.tiles[j]); j += 4; }
}
break;
case 'A': // 左
for (var i = 1, len = this.tiles.length; i < len; i++) {
j = i;
while (j % 4 != 0) { this.merge(this.tiles[j - 1], this.tiles[j]); j -= 1; }
}
break;
case 'D': // 右
for (var i = 14; i >= 0; i--) {
j = i;
while (j % 4 != 3) { this.merge(this.tiles[j + 1], this.tiles[j]); j += 1; }
}
break;
}
this.randomTile();
},
merge: function(prevTile, currTile) {
var prevVal = prevTile.getAttribute('val');
var currVal = currTile.getAttribute('val');
if (currVal != 0) {
if (prevVal == 0) { // 前方空格,直接滑入
this.setTileVal(prevTile, currVal);
this.setTileVal(currTile, 0);
} else if (prevVal == currVal) { // 數字相同,合併
this.setTileVal(prevTile, prevVal * 2);
this.setTileVal(currTile, 0);
}
}
},
equal: function(tile1, tile2) {
return tile1.getAttribute('val') == tile2.getAttribute('val');
},
max: function() {
for (var i = 0, len = this.tiles.length; i < len; i++) {
if (this.tiles[i].getAttribute('val') == 2048) return true;
}
},
over: function() {
for (var i = 0, len = this.tiles.length; i < len; i++) {
if (this.tiles[i].getAttribute('val') == 0) return false; // 還有空格
if (i % 4 != 3 && this.equal(this.tiles[i], this.tiles[i + 1])) return false;
if (i < 12 && this.equal(this.tiles[i], this.tiles[i + 4])) return false;
}
return true;
},
clean: function() {
for (var i = 0, len = this.tiles.length; i < len; i++) {
this.container.removeChild(this.tiles[i]);
}
this.tiles = new Array(16);
}
};
var game, startBtn;
window.onload = function() {
var container = document.getElementById('div2048');
startBtn = document.getElementById('start');
startBtn.onclick = function() {
this.style.display = 'none';
game = game || new game2048(container);
game.init();
};
};
window.onkeydown = function(e) {
var keynum, keychar;
if (window.event) { keynum = e.keyCode; } // IE
else if (e.which) { keynum = e.which; } // 其他瀏覽器
keychar = String.fromCharCode(keynum);
if (['W', 'S', 'A', 'D'].indexOf(keychar) > -1) {
if (game.over()) {
game.clean();
startBtn.style.display = 'block';
startBtn.innerHTML = 'game over, replay?';
return;
}
game.move(keychar);
}
};用 class 換算術。整個視覺狀態都存在 tile0~tile2048 這些 class 裡,JS 只負責切換 className,樣式完全交給 CSS。這是很乾淨的分工。
val 屬性當資料來源。把數值存在自訂屬性上,避免另外維護一份二維陣列,程式碼大幅精簡。缺點是每次讀寫都要經過 DOM,效能不如純資料模型。
merge 的單向性。merge 永遠把「前格」當成目標、「後格」當成來源,而 move 的四個 case 依方向決定遍歷順序,確保永遠是朝移動方向去合併。這是整個演算法最精妙的地方。
· 支援方向鍵(↑↓←→)而不只是 WASD,並在 onkeydown 中呼叫 e.preventDefault() 避免頁面捲動。
· 加入分數與最高分紀錄,合併成功時累加。
· 加上合併與出現的過渡動畫,需要改用 transform 定位而非 float。
· max() 目前缺少 return false,勝負判斷不完整。
· 用 CSS Grid 取代 float + margin 排版,格子間距會好控制得多。
做完這個小遊戲,你對 DOM 操作、事件處理與狀態管理的理解都會往前一步。