下面是一个将 HTML、CSS 和 JavaScript 完全整合在同一个文件里的俄罗斯方块示例,界面简洁美观,并且包含:
- 主画布(Canvas)用于渲染方块
- 下一个方块预览
- 当前分数显示
- 开始/暂停按钮
- 简单的渐变背景和现代化配色
将下面代码保存为 tetris.html,用浏览器打开即可体验。
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>漂亮的俄罗斯方块</title>
<style>
* { margin:0; padding:0; box-sizing:border-box; }
body {
display:flex; align-items:center; justify-content:center;
height:100vh; background: linear-gradient(135deg, #2c3e50, #4ca1af);
font-family: "微软雅黑","Arial",sans-serif;
}
#game-container {
display: flex; gap:20px;
background: rgba(255,255,255,0.1);
padding:20px; border-radius:10px;
box-shadow: 0 8px 24px rgba(0,0,0,0.2);
}
canvas { background: #111; border: 4px solid #333; }
#sidebar {
color: #fff; display:flex; flex-direction:column;
align-items:center; gap:20px;
}
#score, #next {
background: rgba(255,255,255,0.1); padding:10px;
border-radius:6px; width:100%;
text-align:center;
}
#next canvas { background:#111; }
button {
padding:10px 20px; font-size:16px;
border:none; border-radius:6px;
background: #e67e22; color:#fff; cursor:pointer;
transition: background 0.3s;
}
button:hover { background:#d35400; }
</style>
</head>
<body>
<div id="game-container">
<!-- 主游戏区 -->
<canvas id="board" width="240" height="480"></canvas>
<!-- 侧边栏:分数、下一个方块、控制按钮 -->
<div id="sidebar">
<div id="score">
<h2>分数</h2>
<div id="score-value">0</div>
</div>
<div id="next">
<h2>下一个</h2>
<canvas id="preview" width="100" height="100"></canvas>
</div>
<button id="start">开始 / 暂停</button>
<p style="font-size:12px; color:#ddd; text-align:center;">←→ 下落 ↑ 旋转 ↓ 加速</p>
</div>
</div>
<script>
const COLS = 10, ROWS = 20, BLOCK = 24;
const COLORS = ['#000', '#e74c3c', '#f1c40f', '#2ecc71', '#9b59b6', '#3498db', '#e67e22', '#1abc9c'];
const SHAPES = [
[], // 占位
[[0,1,0],[1,1,1]], // T
[[1,1],[1,1]], // O
[[0,1,1],[1,1,0]], // S
[[1,1,0],[0,1,1]], // Z
[[1,0,0],[1,1,1]], // L
[[0,0,1],[1,1,1]], // J
[[1,1,1,1]] // I
];
const boardCanvas = document.getElementById('board');
const boardCtx = boardCanvas.getContext('2d');
const previewCanvas = document.getElementById('preview');
const previewCtx = previewCanvas.getContext('2d');
const scoreElem = document.getElementById('score-value');
const startBtn = document.getElementById('start');
let board = [];
let current, next;
let score = 0;
let gameOver = false, paused = true;
let dropInterval = 800, lastDrop = 0;
// 初始化空白棋盘
function initBoard() {
board = Array.from({length: ROWS}, () => Array(COLS).fill(0));
}
// 生成新方块
function createPiece() {
const type = Math.floor(Math.random() * (SHAPES.length-1)) + 1;
const shape = SHAPES[type];
return {
type,
shape: shape.map(row => row.slice()),
x: Math.floor((COLS - shape[0].length)/2),
y: 0
};
}
// 绘制方块
function drawMatrix(matrix, ctx, offsetX, offsetY) {
matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value) {
ctx.fillStyle = COLORS[value];
ctx.fillRect((x+offsetX)*BLOCK, (y+offsetY)*BLOCK, BLOCK-1, BLOCK-1);
}
});
});
}
// 更新主画布
function draw() {
boardCtx.clearRect(0,0, boardCanvas.width, boardCanvas.height);
drawMatrix(board, boardCtx, 0, 0);
drawMatrix(current.shape, boardCtx, current.x, current.y);
}
// 绘制下一个预览
function drawPreview() {
previewCtx.clearRect(0,0, previewCanvas.width, previewCanvas.height);
const matrix = next.shape;
const offX = Math.floor((4 - matrix[0].length)/2);
const offY = Math.floor((4 - matrix.length)/2);
drawMatrix(matrix, previewCtx, offX, offY);
}
// 碰撞检测
function collide(board, piece) {
const m = piece.shape, o = {x: piece.x, y: piece.y};
for (let y=0; y<m.length; ++y) {
for (let x=0; x<m[y].length; ++x) {
if (m[y][x] &&
(board[y+o.y] && board[y+o.y][x+o.x]) !== 0) {
return true;
}
}
}
return false;
}
// 将方块固定到棋盘
function merge(board, piece) {
piece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value) board[y+piece.y][x+piece.x] = value;
});
});
}
// 清行并更新分数
function sweep() {
let rowCount = 0;
outer:
for (let y=ROWS-1; y>=0; --y) {
for (let x=0; x<COLS; ++x) {
if (board[y][x] === 0) {
continue outer;
}
}
// 此行已满,移除并在顶部添加空行
const row = board.splice(y,1)[0].fill(0);
board.unshift(row);
rowCount++;
y++;
}
if (rowCount > 0) {
score += rowCount * rowCount * 100;
scoreElem.textContent = score;
}
}
// 旋转
function rotate(matrix) {
return matrix[0].map((_, i) => matrix.map(row => row[i])).reverse();
}
// 尝试旋转
function rotatePiece(dir) {
const m = current.shape;
const rotated = dir > 0 ? rotate(m) : rotate(rotate(rotate(m)));
const origX = current.x;
let offset = 1;
while (collide(board, {shape:rotated, x: current.x, y: current.y})) {
current.x += offset;
offset = -(offset + (offset>0?1:-1));
if (offset > rotated[0].length) {
current.x = origX;
return;
}
}
current.shape = rotated;
}
// 游戏主循环
function update(time = 0) {
if (!paused) {
const delta = time - lastDrop;
if (delta > dropInterval) {
current.y++;
if (collide(board, current)) {
current.y--;
merge(board, current);
sweep();
current = next;
next = createPiece();
drawPreview();
if (collide(board, current)) {
gameOver = true; paused = true;
alert("游戏结束!您的分数:" + score);
}
}
lastDrop = time;
}
draw();
}
if (!gameOver) requestAnimationFrame(update);
}
// 控制事件
document.addEventListener('keydown', event => {
if (paused) return;
switch(event.key) {
case 'ArrowLeft':
current.x--;
if (collide(board, current)) current.x++;
break;
case 'ArrowRight':
current.x++;
if (collide(board, current)) current.x--;
break;
case 'ArrowDown':
current.y++;
if (collide(board, current)) { current.y--; }
break;
case 'ArrowUp':
rotatePiece(1);
break;
}
draw();
});
// 开始 / 暂停
startBtn.addEventListener('click', () => {
if (gameOver) {
init();
gameOver = false;
}
paused = !paused;
startBtn.textContent = paused ? "继续" : "暂停";
if (!paused) {
lastDrop = performance.now();
requestAnimationFrame(update);
}
});
// 初始化游戏
function init() {
initBoard();
score = 0;
scoreElem.textContent = score;
current = createPiece();
next = createPiece();
drawPreview();
draw();
}
// 首次加载
init();
</script>
</body>
</html>
说明:
- 使用 Canvas 渲染主游戏区和“下一个”预览。
- 通过
requestAnimationFrame 实现平滑的下落动画。
- 支持方向键控制:← → 移动,↑ 旋转,↓ 加速下落。
- 每次消除 N 行,得分
N²×100,并即时刷新分数。
- 点击“开始/暂停”按钮可控制游戏状态。
直接保存并打开即可体验。祝你游戏愉快!🎮