本文示範如何以純原生 JavaScript 打造經典的 2048 數字合併遊戲,建議在 Chrome 瀏覽器中執行以獲得最佳體驗。以下分為 HTML、CSS 與 JavaScript 三部分說明。
頁面只需要一個遊戲容器與一個開始按鈕:
2048.html 中的主體:
<div id="div2048">
<div id="start">tap to start :-)</div>
</div>
透過不同 tile 類別替格子著上不同顏色,是 2048 視覺效果的關鍵:
#div2048 {
width: 500px; height: 500px;
background-color: #b8af9e;
margin: 0 auto; position: relative;
}
#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.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.tile2048 { color: #fff7eb; background: #eec22e; }
遊戲以 game2048 構造函數為核心,用一個長度 16 的陣列管理 4×4 的格子:
function game2048(container) {
this.container = container;
this.tiles = new Array(16);
}
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;
}\br /> this.randomTile(); this.randomTile();
},
// 隨機在空格生成 2 或 4
randomTile: function() {
var zeroTiles = [];
for (var i = 0; i < this.tiles.length; 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);
},
// 依方向移動與合併
move: function(direction) {
var j;
switch (direction) {
case 'W':
for (var i = 4; i < this.tiles.length; i++) {
j = i;
while (j >= 4) { this.merge(this.tiles[j - 4], this.tiles[j]); j -= 4; }\br /> }
break;
case 'S': /* 向下,同理反向遍歷 */ break;
case 'A': /* 向左 */ break;
case 'D': /* 向右 */ break;
}\br /> this.randomTile();\br /> },
// 合併相鄰同值格子
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); }\br /> }\br /> },
// 是否已達 2048 / 是否結束
max: function() { ... },
over: function() { ... }
};
最後用 window.onkeydown 監聽 W、S、A、D 鍵盤事件來驅動 move,並在每次操作後檢查 over() 判斷遊戲是否結束:
window.onkeydown = function(e) {
var keynum = window.event ? e.keyCode : e.which;
var keychar = String.fromCharCode(keynum);
if (['W', 'S', 'A', 'D'].indexOf(keychar) > -1) {
if (game.over()) {\br /> game.clean(); startBtn.style.display = 'block';\br /> startBtn.innerHTML = 'game over, replay?'; return;\br /> }\br /> game.move(keychar);\br /> }\br /> };
整個遊戲的核心思想,就是用一個陣列管理格子狀態,靠鍵盤方向驅動「移動—合併—生成新格」的循環。邏輯清晰、依賴極少,是練習原生 JavaScript 與遊戲思維的好題材。