俄羅斯方塊是經典的程序設計練習項目,涵蓋二維數組建模、碰撞檢測、旋轉變換、定時器遊戲循環、鍵盤事件處理、行消除算法等核心前端技能。本文梳理完整實現思路,提供關鍵代碼片段,並指出優化方向,適合進階前端開發者作為算法與邏輯訓練。
area[18][10],0=空,1=已佔用。blocks[7][4][4][2]。activeBlock[4] 存儲當前方塊 4 個小格的 {x, y} 絕對坐標。// 檢查單元格 (x,y) 是否合法:在界內且 area[x][y]===0
function isCellValid(x, y) {
return x >= 0 && x < 18 && y >= 0 && y < 10 && area[x][y] === 0;
}
// 檢查左移合法性
function checkLeft() {
for (var i = 0; i < 4; i++) {
var b = activeBlock[i];
if (b.y === 0 || !isCellValid(b.x, b.y - 1)) return false;
}
return true;
}
// 同理實現 checkRight()、checkDown()
以方塊中心(或某基準塊)為原點,每個小格繞中心旋轉 90°:
// (x, y) 相對中心 (cx, cy) 旋轉 90° 順時針 -> (cy - y + cx, x - cx + cy)
// 簡化:預計算 4 種旋轉態的相對偏移,運行時直接查表替換 activeBlock 坐標
function rotate() {
var nextRot = (currentRot + 1) % 4;
var candidate = getBlockCoords(blockType, nextRot, centerX, centerY);
if (candidate.every(isCellValid)) {
activeBlock = candidate;
currentRot = nextRot;
}
// 可加入「牆踢」邏輯:旋轉失敗時嘗試左右/下平移 1-2 格再試
}
var timer, status = 0; // 0=停止, 1=運行, 2=結束
function begin() {
status = 1;
if (!generateBlock()) { alert("Game Over!"); status = 2; return; }
paint();
timer = setInterval(moveDown, 1000); // 1s 下落一格
}
document.onkeydown = keyControl;
function keyControl(e) {
if (status !== 1) return;
switch (e.keyCode) {
case 37: if (checkLeft()) moveLeft(); break; // 左
case 39: if (checkRight()) moveRight(); break; // 右
case 40: moveDown(); break; // 加速下落
case 38: rotate(); break; // 旋轉
case 32: hardDrop(); break; // 空格直接落底
}
paint();
}
function generateBlock() {
activeBlock = [];
var type = Math.floor(Math.random() * 7);
var coords = initialCoords[type]; // 預定義初始 4 格坐標
for (var i = 0; i < 4; i++) {
if (!isCellValid(coords[i].x, coords[i].y)) return false; // 頂部被佔用 -> Game Over
activeBlock[i] = { x: coords[i].x, y: coords[i].y };
}
currentRot = 0; blockType = type;
return true;
}
function moveDown() {
if (checkDown()) {
activeBlock.forEach(b => b.x++);
} else {
// 固化到 area
activeBlock.forEach(b => area[b.x][b.y] = 1);
var lines = deleteLines();
updateScore(lines);
if (!generateBlock()) { clearInterval(timer); status = 2; alert("Game Over!"); }
}
paint();
}
function deleteLines() {
var lines = 0;
for (var i = 17; i >= 0; i--) {
var full = true;
for (var j = 0; j < 10; j++) if (area[i][j] === 0) { full = false; break; }
if (full) {
lines++;
// 以上所有行下移一行
for (var k = i; k > 0; k--) area[k] = area[k-1].slice();
area[0] = new Array(10).fill(0);
i++; // 重新檢查當前行(因為上方行已下移)
}
}
return lines;
}
將 area + activeBlock 合併映射到 DOM 表格(<table id="area">)的單元格背景色,或用 Canvas fillRect 繪製,後者性能更優。
area[x][y] = {filled:1, color:'red'})。generateBlock 為 peekNext() + spawnNext(),側邊顯示預覽。setInterval 間隔,或用 requestAnimationFrame 幀級控制。從零手寫 Tetris 是鍛鍊「數據結構建模 + 狀態機設計 + 事件驅動 + 渲染分離」綜合能力的最佳項目之一。建議先跑通最小可行版本(MVT),再逐步疊加上述特性,過程中必將深化對 JavaScript 異步、閉包、性能優化的理解。