一個極度精簡的俄羅斯方塊實現,全部邏輯濃縮在單個 HTML 文件中,無外部依賴,利用位運算表示方塊形狀、位運算碰撞檢測、CSS 字符渲染畫面。適合學習遊戲核心循環、位運算技巧、極簡編程風格。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JS Tetris</title>
<style>
body { background:#000; font:25px/25px "SimSun", monospace; color:#9f9; text-shadow:2px 3px 1px #0f0; }
#box { float:left; width:252px; border:#999 20px ridge; }
#info { float:left; color:#cfc; padding:24px; }
#next { padding:8px; width:105px; }
<div id="box"></div>
<div id="info">NEXT:<div id="next"></div><div id="text"></div></div>
<script>
// ===== 配置常量 =====
// 地圖:22 行 + 1 底部哨兵行,每行 12 格用 14 位表示(兩側各 1 位作邊界)
// 0x801 = 100000000001 (二進制),即左右邊界為 1,中間 12 格為 0
var map = eval("[" + Array(23).join("0x801,") + "0xfff]"); // 最後一行 0xfff = 111111111111 全滿,作為底部邊界
// 7 種方塊的 4 種旋轉狀態(位掩碼,每 4 位代表一行,共 4 行 = 16 位)
// 0x6600 = 0110 0110 0000 0000 (田字塊 O)
// 0x2222,0xf00 = I 塊豎/橫
// 0xc600,0x2640 = Z/S 塊
// 0x6c00,0x4620 = 反 Z/S
// 0x4460,0x2e0,0x6220,0x740 = J/L/T 等
var tetris = [
[0x6600], // O
[0x2222, 0xf00], // I
[0xc600, 0x2640], // Z
[0x6c00, 0x4620], // S
[0x4460, 0x2e0, 0x6220, 0x740], // J
[0x2260, 0xe20, 0x6440, 0x4700], // L
[0x2620, 0x720, 0x2320, 0x2700] // T
];
// 字符映射:空格、方塊、預覽方塊
var char = { empty: "\u3000", block: "\u25a0", preview: "\u25a1" };
// 鍵位映射:38 上(旋轉)、40 下(加速)、37 左、39 右、32 空格(暫停)
var keyMap = {
"38": "rotate(1)",
"40": "down()",
"37": "move(2, 1)", // x2 左移
"39": "move(0.5, -1)", // x0.5 右移
"32": "0; pause=!pause"
};
// ===== 遊戲狀態變量 =====
var current, position, backup, timer, nextPiece, pause = false;
var info = { speed: 1, lines: 0, score: 0 };
// ===== 核心函數 =====
function start() {
current = nextPiece.shape;
backup = position = {
shapeRows: [], y: 0, x: 4, rotation: nextPiece.rotation
};
spawnNext();
renderNextPreview();
renderInfo();
rotate(0); // 初始化當前方塊的 shapeRows
timer = setInterval("pause || down()", ~~(Math.pow(1.3, 12 - info.speed) * 30 + 20));
}
function gameOver() {
document.onkeydown = null;
alert("GAME OVER");
}
function spawnNext() {
var shapes = tetris[~~(Math.random() * 7)];
nextPiece = { shape: shapes, rotation: ~~(Math.random() * shapes.length) };
}
function renderNextPreview() {
var shape = nextPiece.shape[nextPiece.rotation % nextPiece.shape.length];
// 將 16 位轉為 4x4 二進制字符串,替換為字符
var html = (shape | 0x10000).toString(2).slice(-16) // 取低 16 位
.replace(/..../g, "$<br/>") // 每 4 位換行
.replace(/1/g, char.preview)
.replace(/0/g, char.empty);
document.getElementById("next").innerHTML = html;
}
function renderInfo() {
document.getElementById("text").innerHTML =
"SCORE: " + info.score + "<br/><br/>" +
"LINES: " + info.lines + "<br/><br/>" +
"SPEED: " + info.speed;
}
// 將當前方塊的 4 行位掩碼解析到 position.shapeRows,並按 x 位移
function rotate(dir) {
var shape = current[position.rotation = (position.rotation + dir) % current.length];
for (var i = 0; i < 4; i++) {
// 取每 4 位 (一行),左移 position.x 位對齊地圖
position.shapeRows[i] = ((shape >> (12 - i * 4)) & 15) << position.x;
}
update(checkCollision());
}
// 嘗試下移一行
function down() {
position.y++;
if (checkCollision()) { // 碰撞則回滾並鎖定
lockPiece();
return;
}
update();
}
// 左右移動:x 乘以 2 (左移) 或 0.5 (右移) 實現位移 1 格
function move(multiplier, dir) {
position.x += dir;
for (var i = 0; i < 4; i++) position.shapeRows[i] *= multiplier;
update(checkCollision());
}
// 碰撞檢測:當前方塊 4 行與地圖對應行按位與,非 0 即碰撞
function checkCollision() {
for (var i = 0; i < 4; i++) {
if ((position.shapeRows[i] & map[position.y + i]) !== 0) {
return true;
}
}
return false;
}
// 更新畫面:將地圖 + 當前方塊合成 HTML
function update(collided) {
if (collided) position = backup; // 碰撞則恢復上一幀狀態
else backup = { shapeRows: position.shapeRows.slice(0), y: position.y, x: position.x, rotation: position.rotation };
var html = "";
for (var i = 0; i < 22; i++) {
html += map[i].toString(2).slice(1, -1) + "<br/>"; // 去除兩側邊界位
}
// 疊加當前方塊
for (var i = 0; i < 4; i++) {
var rowBits = position.shapeRows[i].toString(2).replace(/1/g, char.block);
var match = rowBits.match(/([^0]+)/);
if (match) {
var pos = (position.y + i + 1) * 15 - match[0].length - 4; // 計算插入位置
html = html.substr(0, pos) + match[0] + html.substr(pos + match[0].length);
}
}
document.getElementById("box").innerHTML = html.replace(/1/g, char.block).replace(/0/g, char.empty);
}
// 鎖定方塊到地圖,消行計分
function lockPiece() {
var cleared = 0;
for (var i = 0; i < 4 && position.y + i < 22; i++) {
map[position.y + i] |= position.shapeRows[i];
if (map[position.y + i] === 0xfff) { // 滿行
map.splice(position.y + i, 1);
map.unshift(0x801);
cleared++;
}
}
clearInterval(timer);
if (map[1] !== 0x801) return gameOver(); // 新方塊生成位置被佔用
// 計分:消行數^1.5 * 10 + 2
info.score += ~~(Math.pow(cleared, 1.5) * 10) + 2;
if (cleared) {
info.lines += cleared;
if (info.lines % 20 === 0) info.speed++;
}
renderInfo();
start(); // 新一輪
}
// 鍵盤控制
document.onkeydown = function(e) {
var code = (e || event).keyCode;
if (keyMap[code]) eval("pause || " + keyMap[code]);
};
spawnNext();
start();
</script>
</body>
</html>