同题横评:用 HTML + 原生 JavaScript(不使用任何外部…
结论速览
本报告由「AI 大众点评 · 同题横评工作台」自动生成,同一任务并发调用多家大模型后对比输出。
本次横评产品(4)
横评任务
用 HTML + 原生 JavaScript(不使用任何外部依赖、不引用任何 CDN)生成一个完整、可直接在浏览器打开运行的单文件俄罗斯方块游戏。要求:①标准 10×20 棋盘,7 种经典方块(I、O、T、S、Z、J、L)颜色区分;②键盘操作:←→移动、↓软降、↑旋转、空格硬降、P 暂停;③计分系统(按消行数计分)、等级加速机制、下一个方块预览区;④游戏结束判定、结算面板与重新开始按钮;⑤界面美观,带开始界面;⑥附操作说明面板。只输出完整可运行的 HTML 代码。
综合排名
指标对比
| 通义千问冠军 | Kimi亚军 | DeepSeek季军 | 智谱 GLM | 豆包 | |
|---|---|---|---|---|---|
| 综合分 | 8.2 | 7.7 | 7.6 | 4.0 | 调用失败 |
| 质量分 | 8.7 | 8.4 | 8.7 | 3.1 | — |
| 性能分 | 6.9 | 5.9 | 5.1 | 9.7 | — |
| 正确性/可运行性 | 9.0 | 8.5 | 9.0 | 1.0 | — |
| 逻辑性 | 8.5 | 8.0 | 8.5 | 3.0 | — |
| 完整性 | 10.0 | 10.0 | 10.0 | 5.0 | — |
| 稳定性 | 7.5 | 7.5 | 7.5 | 1.0 | — |
| 风格 | 8.0 | 7.5 | 8.0 | 6.0 | — |
| 效率 | 7.0 | 7.0 | 7.0 | 7.0 | — |
| 响应耗时 | 139.8s | 145.0s | 187.5s | 123.1s | — |
| Token(入/出) | 176 / 6337 | 152 / 5697 | 150 / 8053 | 158 / 2612 | — |
| 调用费用(估算) | ¥0.01 | ¥0.09 | ¥0.02 | 免费 | — |
| 单位产出成本 | ¥0.0012 / 分 | ¥0.0117 / 分 | ¥0.0026 / 分 | 翻车·不计 | — |
高亮为该指标最优值。综合分 = 质量 × 70% + 性能 × 30%;性能分 = 速度 45% + Token 40% + 费用 15%;质量分六维加权(可运行性 30 / 逻辑 25 / 完整 20 / 稳定 10 / 风格 10 / 效率 5)。输出被截断或可运行性 ≤ 2 时,综合分封顶 4.0。
调用费用按各模型官方刊例价 × 真实 token 用量折算,仅为平台 API 成本估算,用户使用横评无需付费。「单位产出成本」= 调用费用 ÷ 综合分(每得 1 分的成本,越低越划算),截断或可运行性 ≤ 2 的样本标注「不计」,不参与最优比较。
输出对比
左右滑动查看各家产物,可直接在线试玩
查看完整源码
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>俄罗斯方块 - 原生 JavaScript</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #1a2a6c, #2c3e50);
color: #fff;
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.game-container {
display: flex;
flex-direction: column;
align-items: center;
max-width: 900px;
width: 100%;
}
.header {
text-align: center;
margin-bottom: 20px;
padding: 15px;
background: rgba(0, 0, 0, 0.3);
border-radius: 12px;
width: 100%;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}
.header h1 {
font-size: 2.8rem;
margin-bottom: 8px;
background: linear-gradient(to right, #ff7e5f, #feb47b);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
letter-spacing: 2px;
}
.header p {
font-size: 1.1rem;
opacity: 0.9;
max-width: 600px;
margin: 0 auto;
}
.game-ui {
display: flex;
gap: 25px;
width: 100%;
justify-content: center;
flex-wrap: wrap;
}
.board-container {
position: relative;
background: rgba(0, 0, 0, 0.4);
padding: 15px;
border-radius: 12px;
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.4);
}
#board {
display: block;
background: #0d1b2a;
border: 2px solid #415a77;
border-radius: 4px;
box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.6);
}
.side-panel {
display: flex;
flex-direction: column;
gap: 20px;
width: 220px;
}
.panel {
background: rgba(0, 0, 0, 0.4);
border-radius: 12px;
padding: 18px;
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3);
}
.panel-title {
font-size: 1.3rem;
margin-bottom: 15px;
color: #ffd166;
text-align: center;
font-weight: bold;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}
.stats {
display: flex;
flex-direction: column;
gap: 12px;
}
.stat-item {
display: flex;
justify-content: space-between;
padding: 8px 12px;
background: rgba(255, 255, 255, 0.08);
border-radius: 8px;
font-size: 1.1rem;
}
.stat-label {
font-weight: 600;
opacity: 0.85;
}
.stat-value {
font-weight: bold;
color: #4cc9f0;
}
.next-piece {
display: flex;
justify-content: center;
}
#next-board {
background: #0d1b2a;
border: 2px solid #415a77;
border-radius: 4px;
box-shadow: inset 0 0 10px rgba(0, 0, 0, 0.6);
}
.controls {
margin-top: 10px;
}
.control-item {
display: flex;
justify-content: space-between;
margin: 8px 0;
font-size: 0.95rem;
}
.key {
background: rgba(255, 255, 255, 0.15);
padding: 4px 10px;
border-radius: 6px;
font-weight: bold;
min-width: 40px;
text-align: center;
}
.game-over, .start-screen {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.85);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
border-radius: 12px;
z-index: 10;
backdrop-filter: blur(5px);
transition: all 0.3s ease;
}
.game-over h2, .start-screen h2 {
font-size: 2.5rem;
margin-bottom: 20px;
color: #ff6b6b;
text-shadow: 0 0 10px rgba(255, 107, 107, 0.5);
}
.game-over p, .start-screen p {
font-size: 1.3rem;
margin-bottom: 30px;
text-align: center;
max-width: 80%;
line-height: 1.6;
}
.final-score {
font-size: 1.8rem;
margin: 15px 0;
color: #4cc9f0;
font-weight: bold;
}
.btn {
background: linear-gradient(to right, #ff7e5f, #feb47b);
color: white;
border: none;
padding: 14px 36px;
font-size: 1.2rem;
font-weight: bold;
border-radius: 50px;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 4px 15px rgba(255, 126, 95, 0.4);
letter-spacing: 1px;
}
.btn:hover {
transform: translateY(-3px);
box-shadow: 0 6px 20px rgba(255, 126, 95, 0.6);
}
.btn:active {
transform: translateY(1px);
}
.instructions {
background: rgba(0, 0, 0, 0.4);
border-radius: 12px;
padding: 20px;
margin-top: 20px;
width: 100%;
box-shadow: 0 6px 16px rgba(0, 0, 0, 0.3);
}
.instructions h2 {
text-align: center;
margin-bottom: 15px;
color: #ffd166;
font-size: 1.5rem;
}
.instructions ul {
padding-left: 25px;
}
.instructions li {
margin-bottom: 10px;
line-height: 1.5;
font-size: 1.05rem;
}
.instructions .key {
background: rgba(255, 255, 255, 0.2);
display: inline-block;
margin: 0 3px;
}
@media (max-width: 768px) {
.game-ui {
flex-direction: column;
align-items: center;
}
.side-panel {
width: 100%;
max-width: 400px;
}
.header h1 {
font-size: 2.2rem;
}
}
</style>
</head>
<body>
<div class="game-container">
<div class="header">
<h1>TETRIS</h1>
<p>经典俄罗斯方块 - 原生 JavaScript 实现 | 无需网络依赖</p>
</div>
<div class="game-ui">
<div class="board-container">
<canvas id="board" width="300" height="600"></canvas>
<div class="game-over" id="gameOverScreen" style="display:none;">
<h2>GAME OVER</h2>
<p>方块堆叠到顶部!游戏结束。</p>
<div class="final-score">最终得分:<span id="finalScore">0</span></div>
<button class="btn" id="restartBtn">重新开始</button>
</div>
<div class="start-screen" id="startScreen">
<h2>TETRIS</h2>
<p>经典益智游戏,考验你的反应与策略!</p>
<button class="btn" id="startBtn">开始游戏</button>
</div>
</div>
<div class="side-panel">
<div class="panel">
<div class="panel-title">游戏信息</div>
<div class="stats">
<div class="stat-item">
<span class="stat-label">分数</span>
<span class="stat-value" id="score">0</span>
</div>
<div class="stat-item">
<span class="stat-label">等级</span>
<span class="stat-value" id="level">1</span>
</div>
<div class="stat-item">
<span class="stat-label">消行</span>
<span class="stat-value" id="lines">0</span>
</div>
</div>
</div>
<div class="panel">
<div class="panel-title">下一个方块</div>
<div class="next-piece">
<canvas id="next-board" width="120" height="120"></canvas>
</div>
</div>
<div class="panel">
<div class="panel-title">操作说明</div>
<div class="controls">
<div class="control-item">
<span>左/右方向键</span>
<span class="key">← →</span>
</div>
<div class="control-item">
<span>下方向键</span>
<span class="key">↓</span>
</div>
<div class="control-item">
<span>上方向键</span>
<span class="key">↑</span>
</div>
<div class="control-item">
<span>空格键</span>
<span class="key">SPACE</span>
</div>
<div class="control-item">
<span>暂停</span>
<span class="key">P</span>
</div>
</div>
</div>
</div>
</div>
<div class="instructions">
<h2>游戏规则</h2>
<ul>
<li><strong>移动:</strong>← → 方向键左右移动方块</li>
<li><strong>软降:</strong>↓ 方向键加速下落(不加分)</li>
<li><strong>旋转:</strong>↑ 方向键顺时针旋转方块</li>
<li><strong>硬降:</strong>空格键立即下落到底部(获得额外分数)</li>
<li><strong>暂停:</strong>按 P 键暂停/继续游戏</li>
<li><strong>计分:</strong>单行 100×等级,双行 300×等级,三行 500×等级,四行 800×等级</li>
<li><strong>升级:</strong>每消除 10 行升一级,下落速度加快</li>
</ul>
</div>
</div>
<script>
// 游戏配置
const COLS = 10;
const ROWS = 20;
const BLOCK_SIZE = 30;
const COLORS = [
null,
'#FF0D72', // I - 红色
'#0DC2FF', // O - 青色
'#0DFF72', // T - 绿色
'#F538FF', // S - 紫色
'#FF8E0D', // Z - 橙色
'#FFE138', // J - 黄色
'#3877FF' // L - 蓝色
];
// 方块定义:每个数组代表一种方块的四种旋转状态
const PIECES = [
null,
// I
[
[[0,0,0,0], [1,1,1,1], [0,0,0,0], [0,0,0,0]],
[[0,0,1,0], [0,0,1,0], [0,0,1,0], [0,0,1,0]],
[[0,0,0,0], [0,0,0,0], [1,1,1,1], [0,0,0,0]],
[[0,1,0,0], [0,1,0,0], [0,1,0,0], [0,1,0,0]]
],
// O
[
[[1,1], [1,1]],
[[1,1], [1,1]],
[[1,1], [1,1]],
[[1,1], [1,1]]
],
// T
[
[[0,1,0], [1,1,1], [0,0,0]],
[[0,1,0], [0,1,1], [0,1,0]],
[[0,0,0], [1,1,1], [0,1,0]],
[[0,1,0], [1,1,0], [0,1,0]]
],
// S
[
[[0,1,1], [1,1,0], [0,0,0]],
[[0,1,0], [0,1,1], [0,0,1]],
[[0,0,0], [0,1,1], [1,1,0]],
[[1,0,0], [1,1,0], [0,1,0]]
],
// Z
[
[[1,1,0], [0,1,1], [0,0,0]],
[[0,0,1], [0,1,1], [0,1,0]],
[[0,0,0], [1,1,0], [0,1,1]],
[[0,1,0], [1,1,0], [1,0,0]]
],
// J
[
[[1,0,0], [1,1,1], [0,0,0]],
[[0,1,1], [0,1,0], [0,1,0]],
[[0,0,0], [1,1,1], [0,0,1]],
[[0,1,0], [0,1,0], [1,1,0]]
],
// L
[
[[0,0,1], [1,1,1], [0,0,0]],
[[0,1,0], [0,1,0], [0,1,1]],
[[0,0,0], [1,1,1], [1,0,0]],
[[1,1,0], [0,1,0], [0,1,0]]
]
];
// 游戏状态
let canvas, ctx, nextCanvas, nextCtx;
let board, score, level, lines, gameOver, isPaused;
let currentPiece, nextPiece;
let dropCounter, dropInterval;
let lastTime = 0;
// 初始化画布
function initCanvas() {
canvas = document.getElementById('board');
ctx = canvas.getContext('2d');
ctx.scale(BLOCK_SIZE, BLOCK_SIZE);
nextCanvas = document.getElementById('next-board');
nextCtx = nextCanvas.getContext('2d');
nextCtx.scale(BLOCK_SIZE/2, BLOCK_SIZE/2);
}
// 创建空棋盘
function createBoard() {
board = Array.from(Array(ROWS), () => Array(COLS).fill(0));
}
// 创建新方块
function createPiece(type) {
return {
type,
matrix: PIECES[type][0],
x: Math.floor(COLS / 2) - Math.floor(PIECES[type][0][0].length / 2),
y: 0
};
}
// 碰撞检测
function collide(board, piece) {
const [m, o] = [piece.matrix, piece];
for (let y = 0; y < m.length; y++) {
for (let x = 0; x < m[y].length; x++) {
if (m[y][x] !== 0 &&
(board[y + o.y] === undefined ||
board[y + o.y][x + o.x] === undefined ||
board[y + o.y][x + o.x] !== 0)) {
return true;
}
}
}
return false;
}
// 合并方块到棋盘
function merge(board, piece) {
piece.matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
board[y + piece.y][x + piece.x] = value;
}
});
});
}
// 旋转方块
function rotate(matrix, dir) {
// 转置矩阵
const rotated = matrix[0].map((_, i) =>
matrix.map(row => row[i])
);
// 反转每一行实现顺时针旋转
if (dir > 0) {
return rotated.map(row => row.reverse());
} else {
return rotated.reverse();
}
}
// 旋转当前方块
function rotatePiece(piece, dir) {
const originalMatrix = piece.matrix;
let offset = 1;
piece.matrix = rotate(piece.matrix, dir);
// 碰撞处理:如果旋转后碰撞,尝试偏移修正
while (collide(board, piece)) {
piece.x += offset;
offset = -(offset + (offset > 0 ? 1 : -1));
if (offset > piece.matrix[0].length) {
piece.matrix = originalMatrix;
return;
}
}
}
// 方块下落
function dropPiece() {
currentPiece.y++;
if (collide(board, currentPiece)) {
currentPiece.y--;
merge(board, currentPiece);
clearLines();
resetPiece();
}
}
// 硬降
function hardDrop() {
while (!collide(board, currentPiece)) {
currentPiece.y++;
}
currentPiece.y--;
merge(board, currentPiece);
clearLines();
resetPiece();
}
// 重置当前方块
function resetPiece() {
currentPiece = nextPiece;
nextPiece = createPiece(Math.floor(Math.random() * 7) + 1);
// 游戏结束检测
if (collide(board, currentPiece)) {
gameOver = true;
document.getElementById('gameOverScreen').style.display = 'flex';
document.getElementById('finalScore').textContent = score;
}
}
// 清除满行
function clearLines() {
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) {
// 计分:1行=100, 2行=300, 3行=500, 4行=800
const points = [0, 100, 300, 500, 800][rowCount] * level;
score += points;
lines += rowCount;
// 升级:每10行升一级
level = Math.floor(lines / 10) + 1;
// 更新UI
document.getElementById('score').textContent = score;
document.getElementById('level').textContent = level;
document.getElementById('lines').textContent = lines;
// 加速:基础间隔为1000ms,每级减少50ms,最低200ms
dropInterval = Math.max(200, 1000 - (level - 1) * 50);
}
}
// 绘制方块
function drawMatrix(matrix, offset, context = ctx) {
matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
context.fillStyle = COLORS[value];
context.fillRect(x + offset.x, y + offset.y, 1, 1);
// 添加3D效果边框
context.strokeStyle = 'rgba(0, 0, 0, 0.3)';
context.lineWidth = 0.05;
context.strokeRect(x + offset.x, y + offset.y, 1, 1);
// 内部高光
context.fillStyle = 'rgba(255, 255, 255, 0.2)';
context.fillRect(x + offset.x + 0.1, y + offset.y + 0.1, 0.3, 0.3);
}
});
});
}
// 绘制棋盘
function drawBoard() {
board.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
ctx.fillStyle = COLORS[value];
ctx.fillRect(x, y, 1, 1);
// 边框
ctx.strokeStyle = 'rgba(0, 0, 0, 0.4)';
ctx.lineWidth = 0.05;
ctx.strokeRect(x, y, 1, 1);
// 高光
ctx.fillStyle = 'rgba(255, 255, 255, 0.15)';
ctx.fillRect(x + 0.1, y + 0.1, 0.3, 0.3);
}
});
});
}
// 绘制下一个方块预览
function drawNextPiece() {
// 清空画布
nextCtx.fillStyle = '#0d1b2a';
nextCtx.fillRect(0, 0, nextCanvas.width, nextCanvas.height);
// 居中绘制
const offsetX = (nextCanvas.width / (BLOCK_SIZE/2) - nextPiece.matrix[0].length) / 2;
const offsetY = (nextCanvas.height / (BLOCK_SIZE/2) - nextPiece.matrix.length) / 2;
nextCtx.fillStyle = COLORS[nextPiece.type];
drawMatrix(nextPiece.matrix, {x: offsetX, y: offsetY}, nextCtx);
}
// 绘制当前方块
function drawPiece() {
drawMatrix(currentPiece.matrix, currentPiece);
}
// 绘制游戏
function draw() {
// 清空画布
ctx.fillStyle = '#0d1b2a';
ctx.fillRect(0, 0, canvas.width, canvas.height);
// 绘制网格背景
ctx.strokeStyle = 'rgba(65, 90, 119, 0.2)';
ctx.lineWidth = 0.02;
for (let x = 0; x <= COLS; x++) {
ctx.beginPath();
ctx.moveTo(x, 0);
ctx.lineTo(x, ROWS);
ctx.stroke();
}
for (let y = 0; y <= ROWS; y++) {
ctx.beginPath();
ctx.moveTo(0, y);
ctx.lineTo(COLS, y);
ctx.stroke();
}
drawBoard();
drawPiece();
}
// 键盘控制
document.addEventListener('keydown', event => {
if (gameOver || isPaused) return;
switch(event.keyCode) {
case 37: // ←
currentPiece.x--;
if (collide(board, currentPiece)) {
currentPiece.x++;
}
break;
case 39: // →
currentPiece.x++;
if (collide(board, currentPiece)) {
currentPiece.x--;
}
break;
case 40: // ↓
dropPiece();
dropCounter = 0;
break;
case 38: // ↑
rotatePiece(currentPiece, 1);
break;
case 32: // 空格
hardDrop();
break;
case 80: // P
togglePause();
break;
}
});
// 切换暂停状态
function togglePause() {
isPaused = !isPaused;
if (isPaused) {
document.getElementById('gameOverScreen').style.display = 'none';
}
}
// 主游戏循环
function update(deltaTime) {
if (gameOver || isPaused) return;
dropCounter += deltaTime;
if (dropCounter > dropInterval) {
dropPiece();
dropCounter = 0;
}
}
// 游戏循环
function gameLoop(time = 0) {
const deltaTime = time - lastTime;
lastTime = time;
update(deltaTime);
draw();
requestAnimationFrame(gameLoop);
}
// 初始化游戏
function initGame() {
createBoard();
score = 0;
level = 1;
lines = 0;
gameOver = false;
isPaused = false;
dropCounter = 0;
dropInterval = 1000;
// 创建初始方块
nextPiece = createPiece(Math.floor(Math.random() * 7) + 1);
resetPiece();
// 更新UI
document.getElementById('score').textContent = score;
document.getElementById('level').textContent = level;
document.getElementById('lines').textContent = lines;
}
// 启动游戏
function startGame() {
document.getElementById('startScreen').style.display = 'none';
document.getElementById('gameOverScreen').style.display = 'none';
initGame();
}
// 事件监听器
document.getElementById('startBtn').addEventListener('click', startGame);
document.getElementById('restartBtn').addEventListener('click', startGame);
// 初始化
window.addEventListener('load', () => {
initCanvas();
initGame();
gameLoop();
// 监听P键全局暂停
document.addEventListener('keydown', event => {
if (event.keyCode === 80 && !gameOver) {
event.preventDefault();
togglePause();
}
});
});
</script>
</body>
</html>
```查看完整源码
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>经典俄罗斯方块</title>
<style>
:root {
--bg-color: #1a1a2e;
--panel-bg: #16213e;
--text-color: #e94560;
--light-text: #f1f1f1;
--accent: #0f3460;
--border-color: #533483;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
background-color: var(--bg-color);
color: var(--light-text);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
overflow: hidden;
}
.game-wrapper {
display: flex;
gap: 20px;
position: relative;
padding: 20px;
background: rgba(0, 0, 0, 0.2);
border-radius: 10px;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
}
/* 游戏主区域 */
.game-area {
position: relative;
}
canvas {
border: 2px solid var(--border-color);
background-color: #000;
display: block;
box-shadow: 0 0 10px var(--border-color);
}
/* 侧边信息栏 */
.side-panel {
display: flex;
flex-direction: column;
gap: 20px;
width: 150px;
}
.info-box {
background-color: var(--panel-bg);
padding: 15px;
border-radius: 8px;
border: 1px solid var(--accent);
text-align: center;
}
.info-box h3 {
color: var(--text-color);
margin-bottom: 10px;
font-size: 14px;
text-transform: uppercase;
letter-spacing: 1px;
}
.info-box p {
font-size: 20px;
font-weight: bold;
color: #fff;
}
/* 下一个方块预览 */
.preview-canvas {
width: 120px;
height: 120px;
margin: 0 auto;
background: #000;
border: 1px solid #333;
}
/* 按钮样式 */
button {
background-color: var(--text-color);
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
border-radius: 5px;
transition: background 0.2s;
width: 100%;
font-weight: bold;
}
button:hover {
background-color: #ff6b81;
}
/* 覆盖层 (开始/结束/暂停) */
.overlay {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.85);
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
z-index: 10;
border-radius: 4px;
text-align: center;
}
.overlay h1 {
color: var(--text-color);
font-size: 36px;
margin-bottom: 10px;
text-shadow: 0 0 10px rgba(233, 69, 96, 0.5);
}
.overlay p {
margin-bottom: 20px;
color: #ccc;
line-height: 1.6;
}
.hidden {
display: none !important;
}
/* 操作说明 */
.instructions {
margin-top: 10px;
font-size: 12px;
color: #aaa;
text-align: left;
}
.instructions li {
margin-bottom: 5px;
list-style: none;
}
.key {
display: inline-block;
background: #333;
padding: 2px 6px;
border-radius: 3px;
border-bottom: 2px solid #111;
color: #fff;
font-family: monospace;
font-size: 12px;
min-width: 24px;
text-align: center;
}
/* 游戏结束分数 */
.final-score {
font-size: 48px;
color: #ffd700;
margin: 10px 0;
text-shadow: 0 0 15px rgba(255, 215, 0, 0.6);
}
</style>
</head>
<body>
<div class="game-wrapper">
<!-- 左侧:游戏画布 -->
<div class="game-area">
<canvas id="tetris" width="240" height="400"></canvas>
<!-- 开始界面 -->
<div id="start-screen" class="overlay">
<h1>俄罗斯方块</h1>
<p>TETRIS</p>
<button id="start-btn">开始游戏</button>
<div class="instructions" style="margin-top:20px; text-align:center;">
<p>操作说明</p>
<p><span class="key">←</span> <span class="key">→</span> 移动</p>
<p><span class="key">↑</span> 旋转</p>
<p><span class="key">↓</span> 软降</p>
<p><span class="key">Space</span> 硬降</p>
<p><span class="key">P</span> 暂停</p>
</div>
</div>
<!-- 暂停界面 -->
<div id="pause-screen" class="overlay hidden">
<h1>游戏暂停</h1>
<p>按 P 继续</p>
</div>
<!-- 结束界面 -->
<div id="game-over-screen" class="overlay hidden">
<h1>游戏结束</h1>
<div class="final-score" id="final-score">0</div>
<p>最终得分</p>
<button id="restart-btn">重新开始</button>
</div>
</div>
<!-- 右侧:信息面板 -->
<div class="side-panel">
<div class="info-box">
<h3>下一个</h3>
<canvas id="next" class="preview-canvas" width="120" height="120"></canvas>
</div>
<div class="info-box">
<h3>分数</h3>
<p id="score">0</p>
</div>
<div class="info-box">
<h3>等级</h3>
<p id="level">1</p>
</div>
<div class="info-box">
<h3>消除行数</h3>
<p id="lines">0</p>
</div>
</div>
</div>
<script>
// ================= 游戏核心逻辑 =================
const canvas = document.getElementById('tetris');
const context = canvas.getContext('2d');
const nextCanvas = document.getElementById('next');
const nextContext = nextCanvas.getContext('2d');
// UI 元素
const scoreElement = document.getElementById('score');
const levelElement = document.getElementById('level');
const linesElement = document.getElementById('lines');
const finalScoreElement = document.getElementById('final-score');
const startScreen = document.getElementById('start-screen');
const pauseScreen = document.getElementById('pause-screen');
const gameOverScreen = document.getElementById('game-over-screen');
const startBtn = document.getElementById('start-btn');
const restartBtn = document.getElementById('restart-btn');
// 游戏常量
const COLS = 10;
const ROWS = 20;
const BLOCK_SIZE = 20; // 主画布块大小
const PREVIEW_BLOCK_SIZE = 25; // 预览画布块大小
// 缩放画布以适应逻辑网格
context.scale(BLOCK_SIZE, BLOCK_SIZE);
nextContext.scale(PREVIEW_BLOCK_SIZE, PREVIEW_BLOCK_SIZE);
// 颜色定义 (7种经典方块)
const colors = [
null,
'#FF0D72', // T - 紫色/品红
'#0DC2FF', // I - 青色
'#0DFF72', // S - 绿色
'#F538FF', // Z - 红色/粉色 (这里按常规配色调整)
'#FF8E0D', // L - 橙色
'#FFE138', // O - 黄色
'#3877FF', // J - 蓝色
];
// 修正标准颜色以匹配常见认知 (此处为了美观微调)
// 重新映射:1:T, 2:O, 3:L, 4:J, 5:I, 6:S, 7:Z
const pieceColors = {
'T': '#a000f0',
'O': '#f0f000',
'L': '#f0a000',
'J': '#0000f0',
'I': '#00f0f0',
'S': '#00f000',
'Z': '#f00000'
};
// 方块形状定义 (矩阵)
function createPiece(type) {
if (type === 'I') {
return [
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
[0, 1, 0, 0],
];
} else if (type === 'L') {
return [
[0, 2, 0],
[0, 2, 0],
[0, 2, 2],
];
} else if (type === 'J') {
return [
[0, 3, 0],
[0, 3, 0],
[3, 3, 0],
];
} else if (type === 'O') {
return [
[4, 4],
[4, 4],
];
} else if (type === 'Z') {
return [
[5, 5, 0],
[0, 5, 5],
[0, 0, 0],
];
} else if (type === 'S') {
return [
[0, 6, 6],
[6, 6, 0],
[0, 0, 0],
];
} else if (type === 'T') {
return [
[0, 7, 0],
[7, 7, 7],
[0, 0, 0],
];
}
}
// 游戏状态
let dropCounter = 0;
let dropInterval = 1000;
let lastTime = 0;
let isPaused = false;
let isGameOver = false;
let isPlaying = false;
let animationId = null;
let board = createMatrix(COLS, ROWS);
let player = {
pos: {x: 0, y: 0},
matrix: null,
score: 0,
lines: 0,
level: 1,
nextType: null
};
// 创建空矩阵
function createMatrix(w, h) {
const matrix = [];
while (h--) {
matrix.push(new Array(w).fill(0));
}
return matrix;
}
// 绘制矩阵
function drawMatrix(matrix, offset, ctx = context, isGhost = false) {
matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
// 边框
ctx.fillStyle = isGhost ? 'rgba(255, 255, 255, 0.1)' : getColor(value);
ctx.fillRect(x + offset.x, y + offset.y, 1, 1);
if (!isGhost) {
// 内部高光,增加立体感
ctx.lineWidth = 0.05;
ctx.strokeStyle = 'rgba(255,255,255,0.3)';
ctx.strokeRect(x + offset.x, y + offset.y, 1, 1);
ctx.fillStyle = 'rgba(255,255,255,0.1)';
ctx.fillRect(x + offset.x + 0.1, y + offset.y + 0.1, 0.8, 0.8);
}
}
});
});
}
// 获取颜色
function getColor(value) {
// 这里的 value 对应矩阵中的数字
// 0: T, 1:I, 2:L, 3:J, 4:O, 5:Z, 6:S
// 注意矩阵定义里的数字,createPiece 中 I=1, L=2, J=3, O=4, Z=5, S=6, T=7
const colorMap = [
null,
'#00f0f0', // I (1)
'#f0a000', // L (2)
'#0000f0', // J (3)
'#f0f000', // O (4)
'#f00000', // Z (5)
'#00f000', // S (6)
'#a000f0' // T (7)
];
return colorMap[value] || '#fff';
}
// 绘制背景网格
function drawGrid() {
context.strokeStyle = '#222';
context.lineWidth = 0.02;
for (let x = 0; x <= COLS; x++) {
context.beginPath();
context.moveTo(x, 0);
context.lineTo(x, ROWS);
context.stroke();
}
for (let y = 0; y <= ROWS; y++) {
context.beginPath();
context.moveTo(0, y);
context.lineTo(COLS, y);
context.stroke();
}
}
// 主绘制循环
function draw() {
// 填充背景
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
drawGrid();
drawMatrix(board, {x: 0, y: 0});
// 绘制阴影 (Ghost piece)
if (!isGameOver && !isPaused) {
drawGhost();
}
drawMatrix(player.matrix, player.pos);
// 绘制下一个方块
drawNextPiece();
}
function drawGhost() {
const ghost = {
pos: { ...player.pos },
matrix: player.matrix
};
while (!collide(board, ghost)) {
ghost.pos.y++;
}
ghost.pos.y--; // 回退一格
drawMatrix(ghost.matrix, ghost.pos, context, true);
}
function drawNextPiece() {
nextContext.fillStyle = '#000';
nextContext.fillRect(0, 0, nextCanvas.width, nextCanvas.height);
if (player.nextType) {
const matrix = createPiece(player.nextType);
// 居中计算
const offsetX = (5 - matrix[0].length) / 2;
const offsetY = (5 - matrix.length) / 2;
drawMatrix(matrix, {x: offsetX, y: offsetY}, nextContext);
}
}
// 合并方块到棋盘
function merge(arena, player) {
player.matrix.forEach((row, y) => {
row.forEach((value, x) => {
if (value !== 0) {
arena[y + player.pos.y][x + player.pos.x] = value;
}
});
});
}
// 旋转矩阵
function rotate(matrix, dir) {
for (let y = 0; y < matrix.length; ++y) {
for (let x = 0; x < y; ++x) {
[matrix[x][y], matrix[y][x]] = [matrix[y][x], matrix[x][y]];
}
}
if (dir > 0) {
matrix.forEach(row => row.reverse());
} else {
matrix.reverse();
}
}
// 碰撞检测
function collide(arena, player) {
const m = player.matrix;
const o = player.pos;
for (let y = 0; y < m.length; ++y) {
for (let x = 0; x < m[y].length; ++x) {
if (m[y][x] !== 0 &&
(arena[y + o.y] && arena[y + o.y][x + o.x]) !== 0) {
return true;
}
}
}
return false;
}
// 玩家控制
function playerDrop() {
player.pos.y++;
if (collide(board, player)) {
player.pos.y--;
merge(board, player);
arenaSweep();
playerReset();
}
dropCounter = 0;
}
function playerMove(dir) {
player.pos.x += dir;
if (collide(board, player)) {
player.pos.x -= dir;
}
}
function playerRotate(dir) {
const pos = player.pos.x;
let offset = 1;
rotate(player.matrix, dir);
while (collide(board, player)) {
player.pos.x += offset;
offset = -(offset + (offset > 0 ? 1 : -1));
if (offset > player.matrix[0].length) {
rotate(player.matrix, -dir);
player.pos.x = pos;
return;
}
}
}
function playerHardDrop() {
while (!collide(board, player)) {
player.pos.y++;
}
player.pos.y--;
merge(board, player);
arenaSweep();
playerReset();
dropCounter = 0;
}
// 生成新方块
function playerReset() {
const pieces = 'ILJOTSZ';
if (!player.nextType) {
player.nextType = pieces[pieces.length * Math.random() | 0];
}
player.matrix = createPiece(player.nextType);
player.nextType = pieces[pieces.length * Math.random() | 0];
// 初始位置居中,稍微偏上
player.pos.y = 0;
player.pos.x = (board[0].length / 2 | 0) - (player.matrix[0].length / 2 | 0);
// 游戏结束判定:如果刚生成就碰撞
if (collide(board, player)) {
isGameOver = true;
isPlaying = false;
finalScoreElement.innerText = player.score;
gameOverScreen.classList.remove('hidden');
cancelAnimationFrame(animationId);
}
}
// 消除行
function arenaSweep() {
let rowCount = 0;
outer: for (let y = board.length - 1; y > 0; --y) {
for (let x = 0; x < board[y].length; ++x) {
if (board[y][x] === 0) {
continue outer;
}
}
const row = board.splice(y, 1)[0].fill(0);
board.unshift(row);
++y;
rowCount++;
}
if (rowCount > 0) {
// 计分逻辑
// 1行: 100, 2行: 300, 3行: 500, 4行: 800
const lineScores = [0, 100, 300, 500, 800];
player.score += lineScores[rowCount] * player.level;
player.lines += rowCount;
// 等级提升 (每10行升一级)
const newLevel = Math.floor(player.lines / 10) + 1;
if (newLevel > player.level) {
player.level = newLevel;
// 加速
dropInterval = Math.max(100, 1000 - (player.level - 1) * 100);
}
updateScore();
}
}
function updateScore() {
scoreElement.innerText = player.score;
levelElement.innerText = player.level;
linesElement.innerText = player.lines;
}
// 游戏主循环
function update(time = 0) {
if (!isPlaying || isPaused) return;
const deltaTime = time - lastTime;
lastTime = time;
dropCounter += deltaTime;
if (dropCounter > dropInterval) {
playerDrop();
}
draw();
animationId = requestAnimationFrame(update);
}
// 键盘事件
document.addEventListener('keydown', event => {
if (!isPlaying) {
// 只有回车或空格可以在结束后重启 (可选)
if (event.keyCode === 13 && isGameOver) {
resetGame();
}
return;
}
if (isGameOver) return;
if (event.keyCode === 80) { // P 键暂停
togglePause();
return;
}
if (isPaused) return;
if (event.keyCode === 37) { // 左
playerMove(-1);
} else if (event.keyCode === 39) { // 右
playerMove(1);
} else if (event.keyCode === 40) { // 下
playerDrop();
} else if (event.keyCode === 38) { // 上
playerRotate(1);
} else if (event.keyCode === 32) { // 空格
event.preventDefault(); // 防止滚动
playerHardDrop();
}
draw(); // 按键立即刷新
});
function togglePause() {
isPaused = !isPaused;
if (isPaused) {
pauseScreen.classList.remove('hidden');
cancelAnimationFrame(animationId);
} else {
pauseScreen.classList.add('hidden');
lastTime = performance.now();
update();
}
}
function resetGame() {
board = createMatrix(COLS, ROWS);
player.score = 0;
player.lines = 0;
player.level = 1;
dropInterval = 1000;
updateScore();
isGameOver = false;
isPaused = false;
isPlaying = true;
startScreen.classList.add('hidden');
gameOverScreen.classList.add('hidden');
pauseScreen.classList.add('hidden');
player.nextType = null;
playerReset();
lastTime = performance.now();
update();
}
// 按钮事件绑定
startBtn.addEventListener('click', resetGame);
restartBtn.addEventListener('click', resetGame);
// 初始化绘制一次背景
context.fillStyle = '#000';
context.fillRect(0, 0, canvas.width, canvas.height);
drawGrid();
</script>
</body>
</html>
```实现要点
这是您需要的单文件俄罗斯方块游戏HTML代码。它包含了完整的游戏逻辑、界面和交互,无需任何外部依赖,打开即可运行。
核心玩法与操作说明
游戏遵循经典俄罗斯方块的规则,您可以快速上手。其核心机制围绕方块的移动、旋转与消除展开,并通过计分和等级系统提供持续挑战。
- 方块控制:使用键盘的 ←/→ 键左右移动方块,↑ 键旋转方块,↓ 键让方块加速下落,空格键 则让方块直接落到底部。
- 游戏进程:方块会随时间自动下落。您需要合理安排方块的位置,填满横向的一整行即可消除该行并得分。消除的行数越多,单次得分越高。
- 等级与速度:游戏会记录您消除的总行数。每消除10行,等级会提升一级,同时方块的下落速度会加快,让挑战逐步升级。
- 界面与状态:右侧面板清晰显示您的当前分数、等级和已消除行数。您还可以在这里看到下一个方块的预览,以便提前规划。游戏支持暂停(P键),并在结束时弹出结算面板,方便您查看最终得分并重新开始。
---
优化建议: 您可以在代码开头的“常量与配置”部分调整 `BASE_INTERVAL` 的值来改变游戏的基础下落速度,或修改 `SCORE_MAP` 对象来调整不同消行数对应的得分。
查看完整源码
这是您需要的单文件俄罗斯方块游戏HTML代码。它包含了完整的游戏逻辑、界面和交互,无需任何外部依赖,打开即可运行。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>俄罗斯方块 · 经典版</title>
<style>
* {
box-sizing: border-box;
user-select: none;
}
body {
min-height: 100vh;
margin: 0;
background: linear-gradient(145deg, #1a1e2c, #0f121b);
display: flex;
justify-content: center;
align-items: center;
font-family: 'Segoe UI', Roboto, system-ui, sans-serif;
}
.game-wrapper {
background: rgba(18, 22, 33, 0.85);
backdrop-filter: blur(4px);
border-radius: 2.5rem;
padding: 2rem 2.5rem;
box-shadow: 0 25px 40px rgba(0, 0, 0, 0.6), inset 0 0 0 1px rgba(255, 255, 255, 0.05);
border: 1px solid #2d3445;
}
.game-container {
display: flex;
gap: 2rem;
align-items: flex-start;
justify-content: center;
flex-wrap: wrap;
}
/* 画板区域 */
.play-area {
position: relative;
}
canvas#boardCanvas {
display: block;
width: 300px;
height: 600px;
border-radius: 1.2rem;
background-color: #0b0e14;
box-shadow: inset 0 0 0 2px #2a2f3f, 0 10px 20px rgba(0,0,0,0.5);
}
/* 右侧信息栏 */
.info-panel {
display: flex;
flex-direction: column;
gap: 1.5rem;
width: 150px;
}
.next-piece-panel {
background: #0b0e14;
border-radius: 1.5rem;
padding: 1rem 0.8rem;
box-shadow: inset 0 0 0 2px #2a2f3f, 0 8px 16px rgba(0,0,0,0.4);
text-align: center;
}
.next-piece-panel h3 {
margin: 0 0 0.8rem 0;
font-size: 0.9rem;
font-weight: 500;
letter-spacing: 2px;
text-transform: uppercase;
color: #9ba4b5;
}
canvas#nextCanvas {
display: block;
width: 112px;
height: 112px;
margin: 0 auto;
background-color: #0f121b;
border-radius: 0.8rem;
}
.stats {
background: #0b0e14;
border-radius: 1.5rem;
padding: 1rem 0.9rem;
box-shadow: inset 0 0 0 2px #2a2f3f, 0 8px 16px rgba(0,0,0,0.4);
color: #dbe1ed;
}
.stat-row {
display: flex;
justify-content: space-between;
font-size: 1rem;
margin-bottom: 0.5rem;
}
.stat-row:last-child {
margin-bottom: 0;
}
.stat-label {
color: #8f98aa;
font-weight: 400;
}
.stat-value {
font-weight: 700;
color: #e9edf5;
text-shadow: 0 0 6px rgba(120, 160, 255, 0.4);
}
/* 按钮 */
.btn-primary {
background: linear-gradient(145deg, #3e4a66, #2a3245);
border: none;
border-radius: 2rem;
padding: 0.8rem 1.2rem;
font-weight: 600;
font-size: 1rem;
color: #eef3ff;
letter-spacing: 1px;
cursor: pointer;
box-shadow: 0 8px 0 #151b26, 0 10px 20px rgba(0,0,0,0.4);
transition: all 0.07s ease;
text-transform: uppercase;
border: 1px solid #5b6b8c;
}
.btn-primary:active {
transform: translateY(6px);
box-shadow: 0 2px 0 #151b26, 0 8px 16px rgba(0,0,0,0.5);
}
/* 操作说明 */
.controls-panel {
margin-top: 1.2rem;
background: rgba(12, 16, 24, 0.7);
border-radius: 1.2rem;
padding: 1rem 1.2rem;
border: 1px solid #2d3445;
color: #adb7cc;
font-size: 0.85rem;
}
.controls-panel h4 {
margin: 0 0 0.6rem 0;
color: #b8c4dd;
font-weight: 500;
letter-spacing: 2px;
font-size: 0.8rem;
text-transform: uppercase;
}
.controls-grid {
display: flex;
flex-wrap: wrap;
gap: 0.5rem 1.2rem;
}
.control-item {
display: flex;
align-items: center;
gap: 0.4rem;
}
.key-badge {
background: #1f2533;
padding: 0.2rem 0.7rem;
border-radius: 0.6rem;
font-weight: 600;
font-family: monospace;
font-size: 0.85rem;
color: #cbd5e6;
box-shadow: inset 0 -2px 0 #0b0e14;
border: 1px solid #3b4257;
}
/* 遮罩 / 开始界面 & 结算界面 */
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(8, 10, 16, 0.85);
backdrop-filter: blur(6px);
display: flex;
justify-content: center;
align-items: center;
z-index: 100;
visibility: hidden;
opacity: 0;
transition: opacity 0.2s ease, visibility 0.2s;
}
.overlay.active {
visibility: visible;
opacity: 1;
}
.overlay-card {
background: linear-gradient(145deg, #1b212f, #121722);
padding: 2.5rem 3rem;
border-radius: 3rem;
text-align: center;
box-shadow: 0 30px 50px rgba(0, 0, 0, 0.8), inset 0 1px 1px rgba(255, 255, 255, 0.08);
border: 1px solid #354052;
min-width: 280px;
}
.overlay-card h2 {
font-size: 2.5rem;
margin: 0 0 0.5rem;
font-weight: 700;
background: linear-gradient(135deg, #c0d0ff, #8aa3ff);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
letter-spacing: 3px;
}
.overlay-card .score-display {
font-size: 3rem;
font-weight: 800;
color: #eef5ff;
margin: 0.8rem 0;
text-shadow: 0 0 20px #4060c0;
}
.overlay-card .sub {
color: #8e9ab0;
margin-bottom: 2rem;
font-size: 1rem;
}
.overlay-card button {
margin-top: 0.5rem;
}
.pause-hint {
font-size: 0.9rem;
color: #a6b2cc;
margin-top: 0.7rem;
letter-spacing: 1px;
}
/* 简单的响应式 */
@media (max-width: 700px) {
.game-wrapper {
padding: 1.2rem;
}
.game-container {
gap: 1.2rem;
}
canvas#boardCanvas {
width: 240px;
height: 480px;
}
.info-panel {
width: 120px;
}
canvas#nextCanvas {
width: 96px;
height: 96px;
}
}
</style>
</head>
<body>
<div class="game-wrapper">
<div class="game-container">
<!-- 左侧主棋盘 -->
<div class="play-area">
<canvas id="boardCanvas" width="300" height="600"></canvas>
</div>
<!-- 右侧面板 -->
<div class="info-panel">
<div class="next-piece-panel">
<h3>下一个</h3>
<canvas id="nextCanvas" width="120" height="120"></canvas>
</div>
<div class="stats">
<div class="stat-row">
<span class="stat-label">分数</span>
<span class="stat-value" id="scoreDisplay">0</span>
</div>
<div class="stat-row">
<span class="stat-label">等级</span>
<span class="stat-value" id="levelDisplay">0</span>
</div>
<div class="stat-row">
<span class="stat-label">消行</span>
<span class="stat-value" id="linesDisplay">0</span>
</div>
</div>
<button class="btn-primary" id="restartButton">🔄 重新开始</button>
</div>
</div>
<!-- 操作说明面板 -->
<div class="controls-panel">
<h4>操作说明</h4>
<div class="controls-grid">
<div class="control-item"><span class="key-badge">←</span> 左移</div>
<div class="control-item"><span class="key-badge">→</span> 右移</div>
<div class="control-item"><span class="key-badge">↓</span> 软降</div>
<div class="control-item"><span class="key-badge">↑</span> 旋转</div>
<div class="control-item"><span class="key-badge">空格</span> 硬降</div>
<div class="control-item"><span class="key-badge">P</span> 暂停</div>
</div>
</div>
</div>
<!-- 开始界面 -->
<div class="overlay active" id="startOverlay">
<div class="overlay-card">
<h2>俄罗斯方块</h2>
<div class="sub">经典 · 方块 · 挑战</div>
<button class="btn-primary" id="startButton">开始游戏</button>
<div class="pause-hint">按 P 键暂停</div>
</div>
</div>
<!-- 游戏结束 / 结算面板 -->
<div class="overlay" id="gameoverOverlay">
<div class="overlay-card">
<h2>游戏结束</h2>
<div class="sub">最终得分</div>
<div class="score-display" id="finalScore">0</div>
<button class="btn-primary" id="gameoverRestartButton">再来一局</button>
</div>
</div>
<script>
(function() {
// ---------- 常量与配置 ----------
const COLS = 10;
const ROWS = 20;
const BLOCK_SIZE = 30; // 主画布格子像素 (300/10 = 30)
const NEXT_BLOCK_SIZE = 24; // 预览画布格子大小 (120 / 5 = 24, 留边距,我们按5网格绘制)
// 下一个方块预览画布尺寸 120x120, 居中绘制 4x4 方块
// 七种经典方块 (形状矩阵)
const SHAPES = [
// I
[
[0,0,0,0],
[1,1,1,1],
[0,0,0,0],
[0,0,0,0]
],
// O
[
[0,0,0,0],
[0,1,1,0],
[0,1,1,0],
[0,0,0,0]
],
// T
[
[0,0,0,0],
[0,1,0,0],
[1,1,1,0],
[0,0,0,0]
],
// S
[
[0,0,0,0],
[0,1,1,0],
[1,1,0,0],
[0,0,0,0]
],
// Z
[
[0,0,0,0],
[1,1,0,0],
[0,1,1,0],
[0,0,0,0]
],
// J
[
[0,0,0,0],
[1,0,0,0],
[1,1,1,0],
[0,0,0,0]
],
// L
[
[0,0,0,0],
[0,0,1,0],
[1,1,1,0],
[0,0,0,0]
]
];
// 方块颜色 (明亮霓虹感)
const COLORS = [
'#0b0e14', // 0 空背景
'#00e5f0', // 1 I 青
'#f7e05c', // 2 O 黄
'#c084fc', // 3 T 紫
'#4ade80', // 4 S 绿
'#f87171', // 5 Z 红
'#60a5fa', // 6 J 蓝
'#fb923c' // 7 L 橙
];
// 计分规则 (消行数 -> 得分)
const SCORE_MAP = {
0: 0,
1: 100,
2: 300,
3: 500,
4: 800
};
// 每个等级的下落间隔 (毫秒)
const BASE_INTERVAL = 500; // 等级0 速度(ms) 每格
// DOM 元素
const boardCanvas = document.getElementById('boardCanvas');
const ctx = boardCanvas.getContext('2d');
const nextCanvas = document.getElementById('nextCanvas');
const nextCtx = nextCanvas.getContext('2d');
const scoreDisplay = document.getElementById('scoreDisplay');
const levelDisplay = document.getElementById('levelDisplay');
const linesDisplay = document.getElementById('linesDisplay');
const finalScoreEl = document.getElementById('finalScore');
const startOverlay = document.getElementById('startOverlay');
const gameoverOverlay = document.getElementById('gameoverOverlay');
const startButton = document.getElementById('startButton');
const restartButton = document.getElementById('restartButton');
const gameoverRestartButton = document.getElementById('gameoverRestartButton');
// ---------- 游戏状态变量 ----------
let board = []; // 二维 0/1..7 存储颜色索引
let currentPiece = null; // { shape, colorIdx, x, y }
let nextPiece = null; // { shape, colorIdx }
let score = 0;
let lines = 0;
let level = 0;
let gameActive = false; // 是否运行中 (暂停/结束/开始界面时为false)
let gamePaused = false; // 专用于P暂停
let gameOver = false; // 是否已结束
let dropInterval = BASE_INTERVAL;
let lastDropTime = 0;
let animationFrameId = null;
// 防止快速降落下落累计
let dropCounter = 0;
let lastTimestamp = 0;
// ---------- 工具函数 ----------
function createEmptyBoard() {
return Array(ROWS).fill().map(() => Array(COLS).fill(0));
}
// 随机生成一个方块 (返回形状和颜色索引)
function randomPiece() {
const type = Math.floor(Math.random() * SHAPES.length);
return {
shape: SHAPES[type].map(row => [...row]), // 深拷贝
colorIdx: type + 1 // 颜色索引 1-7
};
}
// 旋转矩阵 (顺时针90度)
function rotateShape(shape) {
const n = shape.length;
const rotated = Array(n).fill().map(() => Array(n).fill(0));
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
rotated[j][n - 1 - i] = shape[i][j];
}
}
return rotated;
}
// 碰撞检测 (针对给定的方块形状与位置)
function collides(shape, pieceX, pieceY) {
for (let r = 0; r < shape.length; r++) {
for (let c = 0; c < shape[r].length; c++) {
if (shape[r][c] !== 0) {
const boardX = pieceX + c;
const boardY = pieceY + r;
// 超出边界或已被占用
if (boardX < 0 || boardX >= COLS || boardY >= ROWS || boardY < 0) {
return true;
}
if (boardY >= 0 && board[boardY][boardX] !== 0) {
return true;
}
}
}
}
return false;
}
// 将当前方块固定到棋盘
function mergePiece() {
if (!currentPiece) return;
const { shape, colorIdx, x, y } = currentPiece;
for (let r = 0; r < shape.length; r++) {
for (let c = 0; c < shape[r].length; c++) {
if (shape[r][c] !== 0) {
const boardX = x + c;
const boardY = y + r;
if (boardY >= 0 && boardY < ROWS && boardX >= 0 && boardX < COLS) {
board[boardY][boardX] = colorIdx;
}
}
}
}
}
// 消除满行并更新分数
function clearFullRows() {
let rowsCleared = 0;
for (let row = ROWS - 1; row >= 0; ) {
const full = board[row].every(cell => cell !== 0);
if (full) {
// 移除该行,上方下移
for (let r = row; r > 0; r--) {
board[r] = [...board[r - 1]];
}
board[0] = Array(COLS).fill(0);
rowsCleared++;
// 继续检查同一行(不要递增row)
} else {
row--;
}
}
if (rowsCleared > 0) {
// 计分
const addScore = SCORE_MAP[rowsCleared] || 0;
score += addScore;
lines += rowsCleared;
// 等级: 每消除10行提升一级
const newLevel = Math.floor(lines / 10);
if (newLevel > level) {
level = newLevel;
// 下落间隔随等级变快: 基准 interval / (1 + level*0.25) 或者用 0.8^level
// 使用更平滑的: 500 * (0.85 ** level) 但下限 80ms
dropInterval = Math.max(80, BASE_INTERVAL * Math.pow(0.82, level));
}
updateUI();
}
return rowsCleared;
}
// 生成新方块 (从next取,并创建下一个)
function spawnNewPiece() {
if (!nextPiece) {
// 首次调用
nextPiece = randomPiece();
}
// 当前方块 = nextPiece
const newShape = nextPiece.shape.map(row => [...row]);
currentPiece = {
shape: newShape,
colorIdx: nextPiece.colorIdx,
x: Math.floor((COLS - newShape[0].length) / 2),
y: 0
};
// 生成下一个
nextPiece = randomPiece();
// 如果一出生就碰撞 -> 游戏结束
if (collides(currentPiece.shape, currentPiece.x, currentPiece.y)) {
gameOver = true;
gameActive = false;
showGameOver();
return false;
}
return true;
}
// ---------- 游戏操作函数 ----------
function movePiece(dx, dy) {
if (!gameActive || gamePaused || !currentPiece) return false;
const newX = currentPiece.x + dx;
const newY = currentPiece.y + dy;
if (!collides(currentPiece.shape, newX, newY)) {
currentPiece.x = newX;
currentPiece.y = newY;
return true;
}
// 如果是向下移动失败 (dy === 1) 则立刻固定
if (dy === 1) {
lockPiece();
}
return false;
}
function rotatePiece() {
if (!gameActive || gamePaused || !currentPiece) return;
const rotatedShape = rotateShape(currentPiece.shape);
// 踢墙简单处理:尝试左右微移
if (!collides(rotatedShape, currentPiece.x, currentPiece.y)) {
currentPiece.shape = rotatedShape;
} else {
// 左移一格尝试
if (!collides(rotatedShape, currentPiece.x - 1, currentPiece.y)) {
currentPiece.shape = rotatedShape;
currentPiece.x -= 1;
}
// 右移一格尝试
else if (!collides(rotatedShape, currentPiece.x + 1, currentPiece.y)) {
currentPiece.shape = rotatedShape;
currentPiece.x += 1;
}
// 还可以尝试上移? 但一般不需要,忽略
}
}
function hardDrop() {
if (!gameActive || gamePaused || !currentPiece) return;
// 一直向下直到碰撞
while (!collides(currentPiece.shape, currentPiece.x, currentPiece.y + 1)) {
currentPiece.y++;
}
lockPiece();
}
// 固定当前方块 + 消除行 + 生成新块
function lockPiece() {
if (!currentPiece) return;
mergePiece();
clearFullRows();
// 尝试生成新块
const success = spawnNewPiece();
if (!success) {
// gameOver 已经在spawn里设置
gameActive = false;
gameOver = true;
showGameOver();
}
updateUI();
}
// 更新计分板
function updateUI() {
scoreDisplay.textContent = score;
levelDisplay.textContent = level;
linesDisplay.textContent = lines;
}
// ---------- 绘制 ----------
function drawBoard() {
ctx.clearRect(0, 0, boardCanvas.width, boardCanvas.height);
// 绘制网格背景 + 已固定块
for (let row = 0; row < ROWS; row++) {
for (let col = 0; col < COLS; col++) {
const colorIdx = board[row][col];
const x = col * BLOCK_SIZE;
const y = row * BLOCK_SIZE;
if (colorIdx !== 0) {
ctx.fillStyle = COLORS[colorIdx];
ctx.fillRect(x, y, BLOCK_SIZE - 1, BLOCK_SIZE - 1);
// 添加微光效果
ctx.fillStyle = 'rgba(255,255,255,0.1)';
ctx.fillRect(x, y, BLOCK_SIZE - 1, 4);
} else {
// 空白格子画一点暗网格
ctx.fillStyle = '#131a24';
ctx.fillRect(x, y, BLOCK_SIZE - 1, BLOCK_SIZE - 1);
ctx.fillStyle = '#1c2533';
ctx.fillRect(x, y, BLOCK_SIZE - 1, 1);
ctx.fillRect(x, y, 1, BLOCK_SIZE - 1);
}
}
}
// 绘制当前方块 (如果存在且游戏活跃/暂停且未结束)
if (currentPiece && !gameOver) {
const { shape, colorIdx, x: pieceX, y: pieceY } = currentPiece;
for (let r = 0; r < shape.length; r++) {
for (let c = 0; c < shape[r].length; c++) {
if (shape[r][c] !== 0) {
const boardX = pieceX + c;
const boardY = pieceY + r;
if (boardY >= 0 && boardY < ROWS && boardX >= 0 && boardX < COLS) {
const px = boardX * BLOCK_SIZE;
const py = boardY * BLOCK_SIZE;
ctx.fillStyle = COLORS[colorIdx];
ctx.fillRect(px, py, BLOCK_SIZE - 1, BLOCK_SIZE - 1);
ctx.fillStyle = 'rgba(255,255,255,0.25)';
ctx.fillRect(px, py, BLOCK_SIZE - 1, 5);
}
}
}
}
}
// 如果暂停,绘制半透明遮罩
if (gamePaused && gameActive) {
ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
ctx.fillRect(0, 0, boardCanvas.width, boardCanvas.height);
ctx.fillStyle = '#ffffff';
ctx.font = 'bold 28px "Segoe UI", monospace';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText('暂停', boardCanvas.width / 2, boardCanvas.height / 2);
}
}
// 绘制下一个方块 (居中绘制在 120x120 画布)
function drawNext() {
nextCtx.clearRect(0, 0, nextCanvas.width, nextCanvas.height);
if (!nextPiece) return;
const shape = nextPiece.shape;
const colorIdx = nextPiece.colorIdx;
const blockSize = NEXT_BLOCK_SIZE; // 24px
// 计算方块实际占用的边界 (用于居中)
let minRow = 4, maxRow = -1, minCol = 4, maxCol = -1;
for (let r = 0; r < 4; r++) {
for (let c = 0; c < 4; c++) {
if (shape[r][c] !== 0) {
minRow = Math.min(minRow, r);
maxRow = Math.max(maxRow, r);
minCol = Math.min(minCol, c);
maxCol = Math.max(maxCol, c);
}
}
}
const pieceWidth = (maxCol - minCol + 1) * blockSize;
const pieceHeight = (maxRow - minRow + 1) * blockSize;
const offsetX = (nextCanvas.width - pieceWidth) / 2;
const offsetY = (nextCanvas.height - pieceHeight) / 2;
for (let r = minRow; r <= maxRow; r++) {
for (let c = minCol; c <= maxCol; c++) {
if (shape[r][c] !== 0) {
const x = offsetX + (c - minCol) * blockSize;
const y = offsetY + (r - minRow) * blockSize;
nextCtx.fillStyle = COLORS[colorIdx];
nextCtx.fillRect(x, y, blockSize - 1, blockSize - 1);
nextCtx.fillStyle = 'rgba(255,255,255,0.2)';
nextCtx.fillRect(x, y, blockSize - 1, 4);
}
}
}
}
// 主渲染循环
function render() {
drawBoard();
drawNext();
}
// ---------- 游戏循环 (基于时间) ----------
function gameLoop(timestamp) {
if (!gameActive || gamePaused || gameOver) {
// 如果未激活仍然绘制静态画面
render();
animationFrameId = requestAnimationFrame(gameLoop);
return;
}
if (!lastTimestamp) lastTimestamp = timestamp;
const delta = timestamp - lastTimestamp;
lastTimestamp = timestamp;
// 下落逻辑
dropCounter += delta;
if (dropCounter >= dropInterval) {
dropCounter = 0;
if (currentPiece) {
// 尝试向下移动,若移动失败内部会lockPiece
if (!movePiece(0, 1)) {
// movePiece内部在向下失败时调用了lockPiece, 无需额外操作
}
}
}
render();
animationFrameId = requestAnimationFrame(gameLoop);
}
// ---------- 重置/开始游戏 ----------
function resetGame() {
// 取消先前动画
if (animationFrameId) {
cancelAnimationFrame(animationFrameId);
animationFrameId = null;
}
board = createEmptyBoard();
score = 0;
lines = 0;
level = 0;
gameOver = false;
gamePaused = false;
gameActive = true;
dropInterval = BASE_INTERVAL;
lastTimestamp = 0;
dropCounter = 0;
// 生成初始方块
nextPiece = randomPiece();
const success = spawnNewPiece(); // 会设置 currentPiece 和下一个 nextPiece
if (!success) {
// 极端情况,极少发生
gameOver = true;
gameActive = false;
showGameOver();
}
updateUI();
// 隐藏遮罩
startOverlay.classList.remove('active');
gameoverOverlay.classList.remove('active');
// 重新启动循环 (如果已有循环则先取消)
if (animationFrameId) cancelAnimationFrame(animationFrameId);
lastTimestamp = 0;
animationFrameId = requestAnimationFrame(gameLoop);
}
// 显示游戏结束
function showGameOver() {
gameActive = false;
gameOver = true;
finalScoreEl.textContent = score;
gameoverOverlay.classList.add('active');
// 停止动画循环?保留循环用于绘制静态画面
render(); // 立即绘制一次
}
// 暂停切换
function togglePause() {
if (!gameActive || gameOver) return;
gamePaused = !gamePaused;
if (!gamePaused) {
// 恢复时重置时间戳防止Delta跳跃
lastTimestamp = 0;
dropCounter = 0;
}
render(); // 立即刷新暂停遮罩
}
// ---------- 键盘事件 ----------
function handleKeyDown(e) {
const key = e.key;
// 防止页面滚动
const preventKeys = ['ArrowUp', 'ArrowDown', 'ArrowLeft', 'ArrowRight', ' ', 'p', 'P'];
if (preventKeys.includes(key) || key === ' ') {
e.preventDefault();
}
// 开始界面:按任何键?但我们通过按钮开始。不必处理。
// 如果游戏结束或未激活,只有重新开始按钮有效。
if (!gameActive && !gameOver) return; // 开始界面时无操作
if (gameOver) return;
// P暂停
if (key === 'p' || key === 'P') {
togglePause();
return;
}
// 如果暂停中,不响应其他操作 (但P可以取消暂停)
if (gamePaused) return;
switch (key) {
case 'ArrowLeft': movePiece(-1, 0); break;
case 'ArrowRight': movePiece(1, 0); break;
case 'ArrowDown': movePiece(0, 1); break;
case 'ArrowUp': rotatePiece(); break;
case ' ': hardDrop(); e.preventDefault(); break;
default: break;
}
// 每次操作后重新渲染 (已经在循环中)
}
// ---------- 初始化与事件绑定 ----------
function init() {
// 初始绘制
board = createEmptyBoard();
render();
// 键盘监听
window.addEventListener('keydown', handleKeyDown);
// 按钮事件
startButton.addEventListener('click', () => {
resetGame();
});
restartButton.addEventListener('click', () => {
resetGame();
});
gameoverRestartButton.addEventListener('click', () => {
resetGame();
});
// 开始动画循环 (虽然未开始游戏,但用于绘制界面)
if (animationFrameId) cancelAnimationFrame(animationFrameId);
lastTimestamp = 0;
animationFrameId = requestAnimationFrame(gameLoop);
}
// 页面加载后初始化
window.addEventListener('load', init);
// 清理动画帧(非必须)
window.addEventListener('beforeunload', () => {
if (animationFrameId) cancelAnimationFrame(animationFrameId);
});
})();
</script>
</body>
</html>
```
### 核心玩法与操作说明
游戏遵循经典俄罗斯方块的规则,您可以快速上手。其核心机制围绕方块的移动、旋转与消除展开,并通过计分和等级系统提供持续挑战。
- **方块控制**:使用键盘的 **←/→** 键左右移动方块,**↑** 键旋转方块,**↓** 键让方块加速下落,**空格键** 则让方块直接落到底部。
- **游戏进程**:方块会随时间自动下落。您需要合理安排方块的位置,填满横向的一整行即可消除该行并得分。消除的行数越多,单次得分越高。
- **等级与速度**:游戏会记录您消除的总行数。每消除10行,等级会提升一级,同时方块的下落速度会加快,让挑战逐步升级。
- **界面与状态**:右侧面板清晰显示您的当前分数、等级和已消除行数。您还可以在这里看到下一个方块的预览,以便提前规划。游戏支持暂停(P键),并在结束时弹出结算面板,方便您查看最终得分并重新开始。
---
**优化建议:** 您可以在代码开头的“常量与配置”部分调整 `BASE_INTERVAL` 的值来改变游戏的基础下落速度,或修改 `SCORE_MAP` 对象来调整不同消行数对应的得分。实现要点
以下是一个简单的俄罗斯方块游戏的 HTML 和 JavaScript 代码。由于代码长度限制,我将代码分为几个部分,并在每个部分后提供注释。
这个代码创建了一个简单的俄罗斯方块游戏,包含了所有要求的功能。请将此代码保存为 `.html` 文件,并在浏览器中打开以运行游戏。
查看完整源码
以下是一个简单的俄罗斯方块游戏的 HTML 和 JavaScript 代码。由于代码长度限制,我将代码分为几个部分,并在每个部分后提供注释。
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tetris</title>
<style>
body { font-family: Arial, sans-serif; }
#game { position: relative; }
.board { width: 300px; height: 600px; background: #000; overflow: hidden; }
.board div { width: 30px; height: 30px; float: left; }
.tetromino { background: #fff; }
.tetromino.i { background: #f00; }
.tetromino.o { background: #0f0; }
.tetromino.t { background: #00f; }
.tetromino.s { background: #0ff; }
.tetromino.z { background: #f0f; }
.tetromino.j { background: #f0a; }
.tetromino.l { background: #fa0; }
#next { width: 100px; height: 200px; background: #000; margin-top: 10px; overflow: hidden; }
#next div { width: 30px; height: 30px; float: left; }
#score { margin-top: 10px; }
#start-screen, #game-over-screen { text-align: center; }
#start-screen button { padding: 10px 20px; cursor: pointer; }
#game-over-screen button { padding: 10px 20px; cursor: pointer; }
</style>
</head>
<body>
<div id="start-screen">
<h1>俄罗斯方块</h1>
<p>按P键开始游戏</p>
<button onclick="startGame()">开始游戏</button>
</div>
<div id="game-over-screen" style="display: none;">
<h1>游戏结束</h1>
<p>你的得分是:<span id="final-score">0</span></p>
<button onclick="resetGame()">重新开始</button>
</div>
<div id="game">
<div class="board" id="board"></div>
<div id="next"></div>
<div id="score">得分:0</div>
</div>
<div id="controls">
<p>方向键控制移动,空格键硬降,↑键旋转,↓键软降,P键暂停</p>
</div>
<script>
// 游戏设置
const boardWidth = 10;
const boardHeight = 20;
const blockSize = 30;
const tetrominoes = [
// I, O, T, S, Z, J, L
[
[[0, 0, 0, 0], [1, 1, 1, 1]],
[[0, 1], [0, 1], [0, 1], [0, 1]],
[[1, 1, 1, 1], [0, 0, 0, 0]],
[[0, 1], [0, 1], [0, 1], [0, 1]]
],
[
[[2, 2], [2, 2]],
[[2, 2], [2, 2]],
[[2, 2], [2, 2]],
[[2, 2], [2, 2]]
],
[
[[0, 3, 0], [3, 3, 3]],
[[3, 0], [3, 3], [0, 3]],
[[0, 3, 3], [3, 3, 0]],
[[3, 3], [0, 3], [0, 3]]
],
[
[[0, 4, 4], [4, 4, 0]],
[[4, 0], [4, 4], [0, 4]],
[[0, 4, 4], [4, 4, 0]],
[[4, 4], [0, 4], [0, 4]]
],
[
[[5, 0, 5], [5, 5, 5]],
[[5, 5], [0, 5], [5, 5]],
[[5, 5, 5], [0, 0, 5]],
[[5, 5], [5, 0], [5, 5]]
],
[
[[0, 6, 6], [6, 6, 0]],
[[6, 0], [6, 6], [0, 6]],
[[0, 6, 6], [6, 6, 0]],
[[6, 6], [0, 6], [0, 6]]
]
];
let board = [];
let currentPiece = null;
let nextPiece = null;
let gameInterval = null;
let score = 0;
let paused = false;
let gameOver = false;
function createBoard() {
for (let r = 0; r < boardHeight; r++) {
board[r] = [];
for (let c = 0; c < boardWidth; c++) {
board[r][c] = 0;
}
}
}
function drawBoard() {
const boardDiv = document.getElementById('board');
boardDiv.innerHTML = '';
for (let r = 0; r < boardHeight; r++) {
for (let c = 0; c < boardWidth; c++) {
const cell = document.createElement('div');
cell.className = 'tetromino';
if (board[r][c] !== 0) {
cell.className += ' ' + tetrominoes[board[r][c] - 1][0][0][0];
}
boardDiv.appendChild(cell);
}
}
}
function drawNextPiece() {
const nextDiv = document.getElementById('next');
nextDiv.innerHTML = '';
const shape = tetrominoes[nextPiece][0];
for (let r = 0; r < shape.length; r++) {
for (let c = 0; c < shape[r].length; c++) {
const cell = document.createElement('div');
cell.className = 'tetromino';
if (shape[r][c] !== 0) {
cell.className += ' ' + tetrominoes[nextPiece][0][0][0];
}
nextDiv.appendChild(cell);
}
}
}
function newPiece() {
currentPiece = nextPiece;
nextPiece = Math.floor(Math.random() * tetrominoes.length);
const shape = tetrominoes[nextPiece][0];
currentPiecePosition = {
x: (boardWidth - shape[0].length) / 2,
y: 0
};
if (checkCollision(currentPiecePosition.x, currentPiecePosition.y, shape)) {
endGame();
}
drawBoard();
drawNextPiece();
}
function rotate() {
const shape = tetrominoes[currentPiece][currentPieceRotation % tetrominoes[currentPiece].length];
if (!checkCollision(currentPiecePosition.x, currentPiecePosition.y, shape)) {
currentPieceRotation = (currentPieceRotation + 1) % tetrominoes[currentPiece].length;
const shape = tetrominoes[currentPiece][currentPieceRotation % tetrominoes[currentPiece].length];
if (checkCollision(currentPiecePosition.x, currentPiecePosition.y, shape)) {
rotate();
}
}
}
function moveLeft() {
if (!checkCollision(currentPiecePosition.x - 1, currentPiecePosition.y, tetrominoes[currentPiece][currentPieceRotation % tetrominoes[currentPiece].length])) {
currentPiecePosition.x--;
}
}
function moveRight() {
if (!checkCollision(currentPiecePosition.x + 1, currentPiecePosition.y, tetrominoes[currentPiece][currentPieceRotation % tetrominoes[currentPiece].length])) {
currentPiecePosition.x++;
}
}
function moveDown() {
if (!checkCollision(currentPiecePosition.x, currentPiecePosition.y + 1, tetrominoes[currentPiece][currentPieceRotation % tetrominoes[currentPiece].length])) {
currentPiecePosition.y++;
} else {
lockPiece();
}
}
function lockPiece() {
const shape = tetrominoes[currentPiece][currentPieceRotation % tetrominoes[currentPiece].length];
for (let r = 0; r < shape.length; r++) {
for (let c = 0; c < shape[r].length; c++) {
if (shape[r][c] !== 0) {
board[currentPiecePosition.y + r][currentPiecePosition.x + c] = currentPiece + 1;
}
}
}
clearLines();
newPiece();
}
function clearLines() {
for (let r = boardHeight - 1; r >= 0; r--) {
let lineFull = true;
for (let c = 0; c < boardWidth; c++) {
if (board[r][c] === 0) {
lineFull = false;
break;
}
}
if (lineFull) {
for (let c = 0; c < boardWidth; c++) {
for (let rr = r; rr > 0; rr--) {
board[rr] = board[rr - 1];
}
board[0] = [];
score += 10;
document.getElementById('score').textContent = '得分:' + score;
}
}
}
}
function checkCollision(x, y, shape) {
for (let r = 0; r < shape.length; r++) {
for (let c = 0; c < shape[r].length; c++) {
if (shape[r][c] !== 0 && (x + c < 0 || x + c >= boardWidth || y + r >= boardHeight || board[y + r][x + c] !== 0)) {
return true;
}
}
}
return false;
}
function endGame() {
clearInterval(gameInterval);
gameOver = true;
document.getElementById('game-over-screen').style.display = 'block';
document.getElementById('final-score').textContent = score;
}
function startGame() {
document.getElementById('start-screen').style.display = 'none';
document.getElementById('game-over-screen').style.display = 'none';
createBoard();
drawBoard();
newPiece();
gameInterval = setInterval(moveDown, 1000);
}
function resetGame() {
score = 0;
document.getElementById('score').textContent = '得分:0';
document.getElementById('final-score').textContent = 0;
document.getElementById('game-over-screen').style.display = 'none';
startGame();
}
function togglePause() {
if (paused) {
gameInterval = setInterval(moveDown, 1000);
paused = false;
} else {
clearInterval(gameInterval);
paused = true;
}
}
let currentPieceRotation = 0;
let currentPiecePosition = { x: 0, y: 0 };
document.addEventListener('keydown', function(e) {
if (gameOver) return;
if (e.keyCode === 37) moveLeft();
if (e.keyCode === 38) rotate();
if (e.keyCode === 39) moveRight();
if (e.keyCode === 40) moveDown();
if (e.keyCode === 32) lockPiece();
if (e.keyCode === 80) togglePause();
});
startGame();
</script>
</body>
</html>
```
这个代码创建了一个简单的俄罗斯方块游戏,包含了所有要求的功能。请将此代码保存为 `.html` 文件,并在浏览器中打开以运行游戏。调用失败:fetch failed
调用异常
- 豆包:fetch failed
评分结论
按「质量 70% + 性能 30%」加权,本场最佳:通义千问(综合分 8.2)。
常见问题
- 这份报告对比了哪些 AI 产品?
- 本次同题横评覆盖:智谱清言、Kimi、DeepSeek 对话、通义千问。同一任务、同一提示词并发调用,逐项指标并列对比。
- 这份横评报告的核心结论是什么?
- 本报告由「AI 大众点评 · 同题横评工作台」自动生成,同一任务并发调用多家大模型后对比输出。
- 这份横评报告是如何产生的?
- 报告来自同题横评工作台:注册会员输入任务并勾选 2-4 家模型并发调用,记录输出质量、耗时、Token 消耗与费用,打分后一键发布。生成产物可在页面内在线试玩验证。
评论(0)
评论加载中…


