fix: 空格在开始界面/结束后也能开始游戏

This commit is contained in:
2026-09-24 03:42:00 +00:00
parent fb807dbd3d
commit c3cf19c17e
+4 -743
View File
@@ -1,755 +1,16 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
<meta name="theme-color" content="#05070f">
<title>霓虹俄罗斯方块 · Neon Tetris</title>
<style>
:root{
--neon:#39ffd0;
--violet:#7c5cff;
--gold:#ffd54a;
--bg:#05070f;
--muted:#8ea6c0;
--panel:rgba(124,92,255,.07);
--line:rgba(124,92,255,.3);
--reserve:280px;
}
*{box-sizing:border-box}
html,body{height:100%}
body{
margin:0;padding:10px 12px 14px;
min-height:100dvh;
display:flex;flex-direction:column;align-items:center;gap:9px;
overflow-x:hidden;
background:radial-gradient(circle at 50% -15%, #17224a 0%, var(--bg) 58%);
color:#e9f4ff;
font-family:ui-sans-serif,system-ui,-apple-system,"PingFang SC","Microsoft YaHei",sans-serif;
-webkit-tap-highlight-color:transparent;
user-select:none;
}
.topbar{
width:min(94vw,320px);
display:flex;align-items:flex-end;justify-content:space-between;gap:8px;
}
.stats{display:flex;gap:14px}
.stat{display:flex;flex-direction:column;gap:2px;line-height:1}
.stat span{font-size:9px;letter-spacing:.16em;color:var(--muted)}
.stat b{font-size:15px;font-variant-numeric:tabular-nums;color:var(--neon)}
.stat.k2 b{color:var(--gold)}
.stat.k3 b{color:#c86bff}
.icon{
font:inherit;color:inherit;cursor:pointer;
background:rgba(124,92,255,.14);border:1px solid var(--line);
border-radius:9px;padding:5px 9px;font-size:13px;line-height:1;
}
.icon:hover{background:rgba(124,92,255,.3)}
.tray{
width:min(94vw,320px);
display:flex;align-items:center;justify-content:space-between;gap:6px;
padding:7px 9px;border-radius:13px;
background:var(--panel);border:1px solid var(--line);
}
.slot{display:flex;align-items:center;gap:6px}
.tray h4{margin:0;font-size:9px;letter-spacing:.15em;color:var(--muted);font-weight:600}
.col{display:flex;flex-direction:column;gap:3px;align-items:center}
canvas.mini{width:44px;height:44px;display:block}
#holdBox{
padding:3px;border-radius:10px;border:1px dashed rgba(57,255,208,.28);
background:rgba(57,255,208,.05);cursor:pointer;
}
#holdBox:active{background:rgba(57,255,208,.2)}
.stack{
width:min(94vw, 320px, calc((100vh - var(--reserve)) / 2));
width:min(94vw, 320px, calc((100dvh - var(--reserve)) / 2));
min-width:132px;
}
.stage{position:relative;width:100%;aspect-ratio:1/2}
#game{
width:100%;height:100%;display:block;
border-radius:13px;
border:1px solid rgba(57,255,208,.22);
box-shadow:0 0 52px rgba(57,255,208,.1), inset 0 0 40px rgba(0,0,0,.7);
touch-action:none;
}
#overlay{
position:absolute;inset:0;border-radius:13px;padding:16px;
display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;
text-align:center;background:rgba(5,7,15,.82);backdrop-filter:blur(6px);
}
#overlay.hidden{display:none}
#overlay h2{margin:0;font-size:clamp(17px,4.6vw,24px);letter-spacing:.05em}
#overlay p{margin:0;font-size:12.5px;line-height:1.75;color:var(--muted);max-width:30ch}
#overlay b{color:var(--neon)}
#playBtn{
margin-top:4px;padding:11px 28px;border:none;border-radius:999px;
font:inherit;font-weight:700;letter-spacing:.1em;color:#04120e;cursor:pointer;
background:linear-gradient(135deg,var(--neon),#4ad9ff);
box-shadow:0 8px 26px rgba(57,255,208,.32);
}
#playBtn:active{transform:scale(.96)}
.pad{
display:grid;grid-template-columns:repeat(3,1fr);gap:7px;
width:min(94vw,320px);
}
.padBtn{
font:inherit;height:44px;border-radius:11px;cursor:pointer;
border:1px solid rgba(57,255,208,.26);
background:rgba(57,255,208,.07);
color:var(--neon);font-size:16px;
display:flex;align-items:center;justify-content:center;
}
.padBtn:active{background:rgba(57,255,208,.28)}
footer{font-size:11px;color:#5c728a;text-align:center;line-height:1.6}
@media (hover:hover) and (pointer:fine){
:root{--reserve:190px}
.pad{display:none}
}
</style>
</head>
<body>
<div class="topbar">
<div class="stats">
<div class="stat"><span>SCORE</span><b id="score">0</b></div>
<div class="stat k2"><span>LEVEL</span><b id="level">1</b></div>
<div class="stat k3"><span>LINES</span><b id="lines">0</b></div>
</div>
<button class="icon" id="muteBtn" title="音效开关">🔊</button>
</div>
<div class="tray">
<div class="slot">
<div class="col"><h4>HOLD</h4></div>
<div id="holdBox"><canvas class="mini" id="holdCv"></canvas></div>
</div>
<div class="slot">
<div class="col"><h4>NEXT</h4></div>
<canvas class="mini" id="nextCv0"></canvas>
<canvas class="mini" id="nextCv1"></canvas>
<canvas class="mini" id="nextCv2"></canvas>
</div>
</div>
<div class="stack">
<div class="stage">
<canvas id="game"></canvas>
<div id="overlay">
<h2 id="ovTitle">霓虹俄罗斯方块</h2>
<p id="ovText"></p>
<button id="playBtn">开始游戏</button>
</div>
</div>
</div>
<div class="pad">
<button class="padBtn" data-act="ccw">↺</button>
<button class="padBtn" data-act="cw">↻</button>
<button class="padBtn" data-act="hard">⤓</button>
<button class="padBtn" data-act="left">←</button>
<button class="padBtn" data-act="soft">↓</button>
<button class="padBtn" data-act="right">→</button>
</div>
<footer>← → 移动 · ↓ 软降 · 空格 硬降 · ↑/X 顺时针 · Z 逆时针 · C 暂存 · P 暂停</footer>
<script>
(() => {
'use strict';
/* ============ 常量 ============ */
const COLS = 10, ROWS = 20, CELL = 30;
const W = COLS * CELL, H = ROWS * CELL;
const DPR = Math.min(window.devicePixelRatio || 1, 2);
const COLORS = {
I:'#4ee1ff', J:'#5a7bff', L:'#ff9f43', O:'#ffd54a',
S:'#39ffa0', T:'#c86bff', Z:'#ff5f7e'
};
// SRS 标准出生朝向
const SHAPES = {
I: [[0,0,0,0],[1,1,1,1],[0,0,0,0],[0,0,0,0]],
J: [[1,0,0],[1,1,1],[0,0,0]],
L: [[0,0,1],[1,1,1],[0,0,0]],
O: [[1,1],[1,1]],
S: [[0,1,1],[1,1,0],[0,0,0]],
T: [[0,1,0],[1,1,1],[0,0,0]],
Z: [[1,1,0],[0,1,1],[0,0,0]]
};
const SPAWN_X = { I:3, J:3, L:3, O:4, S:3, T:3, Z:3 };
const TYPES = ['I','J','L','O','S','T','Z'];
// SRS 踢墙表,已换算成「屏幕坐标」(y 向下为正)
const KICKS = {
JLSTZ: {
'0>1': [[0,0],[-1,0],[-1,-1],[0,2],[-1,2]],
'1>0': [[0,0],[1,0],[1,1],[0,-2],[1,-2]],
'1>2': [[0,0],[1,0],[1,1],[0,-2],[1,-2]],
'2>1': [[0,0],[-1,0],[-1,-1],[0,2],[-1,2]],
'2>3': [[0,0],[1,0],[1,-1],[0,2],[1,2]],
'3>2': [[0,0],[-1,0],[-1,1],[0,-2],[-1,-2]],
'3>0': [[0,0],[-1,0],[-1,1],[0,-2],[-1,-2]],
'0>3': [[0,0],[1,0],[1,-1],[0,2],[1,2]]
},
I: {
'0>1': [[0,0],[-2,0],[1,0],[-2,1],[1,-2]],
'1>0': [[0,0],[2,0],[-1,0],[2,-1],[-1,2]],
'1>2': [[0,0],[-1,0],[2,0],[-1,-2],[2,1]],
'2>1': [[0,0],[1,0],[-2,0],[1,2],[-2,-1]],
'2>3': [[0,0],[2,0],[-1,0],[2,-1],[-1,2]],
'3>2': [[0,0],[-2,0],[1,0],[-2,1],[1,-2]],
'3>0': [[0,0],[1,0],[-2,0],[1,2],[-2,-1]],
'0>3': [[0,0],[-1,0],[2,0],[-1,-2],[2,1]]
}
};
const GRAV = [700,620,530,450,370,300,240,180,140,110,90,80,70,60,50,50,50,50,50,50];
const LOCK_MS = 500, MAX_RESET = 15, CLEAR_MS = 190, SOFT_MS = 45;
const LINE_SCORE = [0,100,300,500,800];
/* ============ DOM ============ */
const canvas = document.getElementById('game');
const ctx = canvas.getContext('2d');
canvas.width = W * DPR;
canvas.height = H * DPR;
const overlay = document.getElementById('overlay');
const ovTitle = document.getElementById('ovTitle');
const ovText = document.getElementById('ovText');
const playBtn = document.getElementById('playBtn');
const scoreEl = document.getElementById('score');
const levelEl = document.getElementById('level');
const linesEl = document.getElementById('lines');
const muteBtn = document.getElementById('muteBtn');
const holdCv = document.getElementById('holdCv');
const nextCvs = [0,1,2].map(i => document.getElementById('nextCv' + i));
const holdBox = document.getElementById('holdBox');
// 面板图层:棋盘只在变化时重画,省掉每帧 200 次阴影开销
const boardCv = document.createElement('canvas');
boardCv.width = W * DPR;
boardCv.height = H * DPR;
const bctx = boardCv.getContext('2d');
bctx.setTransform(DPR, 0, 0, DPR, 0, 0);
// 小面板画布
const MINI_CELL = 11, MINI_N = 4;
[...nextCvs, holdCv].forEach(cv => {
cv.width = MINI_CELL * MINI_N * DPR;
cv.height = MINI_CELL * MINI_N * DPR;
});
/* ============ 状态 ============ */
let board, cur, holdType, canHold, bag, nextQueue;
let score, lines, level, combo;
let dropTimer, lockTimer, lockResets, softDrop;
let clearAnim, shake, boardDirty;
let state = 'ready';
let best = Number(localStorage.getItem('neon-tetris-best') || 0);
let muted = localStorage.getItem('neon-tetris-muted') === '1';
let actx = null;
/* ============ 音效 ============ */
function unlockAudio(){
if (actx){ if (actx.state === 'suspended') actx.resume(); return; }
const AC = window.AudioContext || window.webkitAudioContext;
if (AC) actx = new AC();
}
function tone(freq, dur, type, vol, delay){
if (!actx || muted) return;
const t = actx.currentTime + (delay || 0);
const osc = actx.createOscillator(), g = actx.createGain();
osc.type = type || 'square';
osc.frequency.setValueAtTime(freq, t);
g.gain.setValueAtTime(vol || 0.045, t);
g.gain.exponentialRampToValueAtTime(0.0001, t + dur);
osc.connect(g).connect(actx.destination);
osc.start(t); osc.stop(t + dur);
}
function sfx(name){
switch(name){
case 'move': tone(220, .04, 'square', .022); break;
case 'rotate': tone(380, .05, 'triangle', .03); break;
case 'drop': tone(150, .09, 'sawtooth', .035); break;
case 'lock': tone(120, .07, 'square', .03); break;
case 'clear': tone(520, .09, 'triangle', .05); tone(780, .1, 'triangle', .045, .06); break;
case 'tetris': [523,659,784,1046].forEach((f,i) => tone(f, .16, 'triangle', .055, i*.06)); break;
case 'hold': tone(660, .06, 'triangle', .035); break;
case 'over': [440,330,260,190].forEach((f,i) => tone(f, .28, 'sawtooth', .05, i*.13)); break;
}
}
/* ============ 工具 ============ */
function roundRect(c, x, y, w, h, r){
r = Math.min(r, w / 2, h / 2);
c.beginPath();
c.moveTo(x + r, y);
c.arcTo(x + w, y, x + w, y + h, r);
c.arcTo(x + w, y + h, x, y + h, r);
c.arcTo(x, y + h, x, y, r);
c.arcTo(x, y, x + w, y, r);
c.closePath();
}
function hex2rgb(h){
const n = parseInt(h.slice(1), 16);
return [n >> 16 & 255, n >> 8 & 255, n & 255];
}
function mix(a, b, t){
const A = hex2rgb(a), B = hex2rgb(b);
return `rgb(${Math.round(A[0]+(B[0]-A[0])*t)},${Math.round(A[1]+(B[1]-A[1])*t)},${Math.round(A[2]+(B[2]-A[2])*t)})`;
}
function drawBlock(c, x, y, size, color, glow){
const pad = Math.max(1, size * 0.05);
const r = size * 0.2;
c.save();
if (glow){ c.shadowColor = color; c.shadowBlur = size * 0.42; }
const g = c.createLinearGradient(x, y, x + size, y + size);
g.addColorStop(0, mix(color, '#ffffff', 0.45));
g.addColorStop(0.55, color);
g.addColorStop(1, mix(color, '#000000', 0.3));
c.fillStyle = g;
roundRect(c, x + pad, y + pad, size - pad * 2, size - pad * 2, r);
c.fill();
c.restore();
c.save();
c.strokeStyle = 'rgba(255,255,255,.3)';
c.lineWidth = Math.max(1, size * 0.05);
roundRect(c, x + pad + 1.6, y + pad + 1.6, size - pad * 2 - 3.2, size - pad * 2 - 3.2, r * 0.72);
c.stroke();
c.restore();
}
function setText(el, v){ const s = String(v); if (el.textContent !== s) el.textContent = s; }
function rotateCW(m){
const n = m.length, r = [];
for (let y = 0; y < n; y++){
r.push([]);
for (let x = 0; x < n; x++) r[y].push(m[n - 1 - x][y]);
}
return r;
}
/* ============ 方块 ============ */
function newPiece(type){
return { type, m: SHAPES[type].map(row => row.slice()), x: SPAWN_X[type], y: 0, rot: 0 };
}
function collides(m, px, py){
for (let y = 0; y < m.length; y++){
for (let x = 0; x < m[y].length; x++){
if (!m[y][x]) continue;
const bx = px + x, by = py + y;
if (bx < 0 || bx >= COLS || by >= ROWS) return true;
if (by >= 0 && board[by][bx]) return true;
}
}
return false;
}
function refill(){
while (nextQueue.length < 5){
if (!bag.length) bag = TYPES.slice().sort(() => Math.random() - 0.5); // 7-bag
nextQueue.push(bag.pop());
}
}
/* ============ 游戏流程 ============ */
function startGame(){
board = Array.from({length: ROWS}, () => new Array(COLS).fill(null));
bag = []; nextQueue = []; holdType = null; canHold = true;
score = 0; lines = 0; level = 1; combo = -1;
dropTimer = 0; lockTimer = 0; lockResets = 0; softDrop = false;
clearAnim = null; shake = 0; boardDirty = true;
cur = null;
state = 'playing';
hideOverlay();
refill();
renderNext(); renderHold(); updateHud();
spawn();
}
function spawn(){
refill();
const type = nextQueue.shift();
refill();
cur = newPiece(type);
dropTimer = 0; lockTimer = 0; lockResets = 0; canHold = true;
renderNext();
if (collides(cur.m, cur.x, cur.y)) gameOver();
}
function gravityMs(){ return GRAV[Math.min(level - 1, GRAV.length - 1)]; }
function resetLock(){
if (lockTimer > 0 && lockResets < MAX_RESET){ lockTimer = 0; lockResets++; }
}
function tryMove(dx, dy){
if (collides(cur.m, cur.x + dx, cur.y + dy)) return false;
cur.x += dx; cur.y += dy;
if (dx !== 0) resetLock();
return true;
}
function rotate(dir){
if (cur.type === 'O') return false;
const from = cur.rot;
const to = (from + (dir > 0 ? 1 : 3)) % 4;
let m = cur.m;
for (let i = 0; i < (dir > 0 ? 1 : 3); i++) m = rotateCW(m);
const table = (cur.type === 'I' ? KICKS.I : KICKS.JLSTZ)[from + '>' + to] || [[0,0]];
for (const k of table){
if (!collides(m, cur.x + k[0], cur.y + k[1])){
cur.m = m; cur.x += k[0]; cur.y += k[1]; cur.rot = to;
resetLock();
sfx('rotate');
return true;
}
}
return false;
}
function hardDrop(){
let d = 0;
while (!collides(cur.m, cur.x, cur.y + 1)){ cur.y++; d++; }
score += d * 2;
shake = Math.max(shake, 3);
sfx('drop');
lockPiece();
}
function doHold(){
if (!canHold || !cur) return;
const t = cur.type;
if (holdType == null){ holdType = t; spawn(); }
else {
const h = holdType; holdType = t;
cur = newPiece(h);
dropTimer = 0; lockTimer = 0; lockResets = 0;
if (collides(cur.m, cur.x, cur.y)) gameOver();
}
canHold = false;
renderHold();
sfx('hold');
}
function lockPiece(){
const m = cur.m;
for (let y = 0; y < m.length; y++)
for (let x = 0; x < m[y].length; x++)
if (m[y][x] && cur.y + y >= 0) board[cur.y + y][cur.x + x] = COLORS[cur.type];
boardDirty = true;
const full = [];
for (let y = 0; y < ROWS; y++) if (board[y].every(Boolean)) full.push(y);
if (full.length){
const n = full.length;
combo++;
lines += n;
let gain = LINE_SCORE[n] * level;
if (combo > 0) gain += 50 * combo * level;
score += gain;
level = Math.min(20, Math.floor(lines / 10) + 1);
shake = n === 4 ? 12 : 5;
clearAnim = {rows: full, t: 0};
state = 'clearing';
sfx(n === 4 ? 'tetris' : 'clear');
} else {
combo = -1;
sfx('lock');
spawn();
}
updateHud();
}
function finishClear(){
const rows = clearAnim.rows;
const n = rows.length;
clearAnim = null;
board = board.filter((_, y) => rows.indexOf(y) === -1);
for (let i = 0; i < n; i++) board.unshift(new Array(COLS).fill(null));
boardDirty = true;
state = 'playing';
spawn();
}
function gameOver(){
state = 'over';
shake = 14;
sfx('over');
if (score > best){ best = score; localStorage.setItem('neon-tetris-best', String(best)); }
updateHud();
showOverlay('游戏结束',
`得分 <b>${score}</b> · 消行 <b>${lines}</b> · 等级 <b>${level}</b><br>历史最高 <b>${best}</b>`,
'再来一局');
}
function togglePause(){
if (state === 'playing'){
state = 'paused';
showOverlay('已暂停', '按 P 或点击按钮继续', '继续');
} else if (state === 'paused'){
state = 'playing';
hideOverlay();
}
}
/* ============ 输入 ============ */
function act(a){
unlockAudio();
if (state !== 'playing') return;
switch(a){
case 'left': if (tryMove(-1, 0)) sfx('move'); break;
case 'right': if (tryMove(1, 0)) sfx('move'); break;
case 'soft': softDrop = true; break;
case 'cw': rotate(1); break;
case 'ccw': rotate(-1); break;
case 'hard': hardDrop(); break;
case 'hold': doHold(); break;
}
}
function primary(){
unlockAudio();
if (state === 'ready' || state === 'over') startGame();
else togglePause();
}
const KEYMAP = {
ArrowLeft:'left', ArrowRight:'right', ArrowDown:'soft', ArrowUp:'cw',
' ':'hard', Enter:'start',
a:'left', d:'right', s:'soft', w:'cw',
x:'cw', z:'ccw', c:'hold',
p:'pause', P:'pause', Escape:'pause'
};
window.addEventListener('keydown', e => {
const k = e.key;
const a = KEYMAP[k] || (k.length === 1 ? KEYMAP[k.toLowerCase()] : null);
if (!a) return;
if (k === ' ' || k.indexOf('Arrow') === 0) e.preventDefault();
if (e.repeat && (a === 'cw' || a === 'ccw' || a === 'hold' || a === 'hard')) return;
if (a === 'start'){
e.preventDefault();
if (state === 'ready' || state === 'over') startGame();
// 开始 / 重来
if (a === 'start' || ((state === 'ready' || state === 'over') && a === 'hard')){
if (state === 'ready' || state === 'over'){ startGame(); return; }
return;
}
if (a === 'pause'){ togglePause(); return; }
if (e.repeat && (a === 'cw' || a === 'ccw' || a === 'hold' || a === 'hard')) return;
if (state !== 'playing') return;
act(a);
}, {passive: false});
window.addEventListener('keyup', e => {
if (e.key === 'ArrowDown' || e.key === 's' || e.key === 'S') softDrop = false;
});
document.querySelectorAll('.padBtn').forEach(btn => {
const a = btn.dataset.act;
let rep = null;
const stop = () => { clearTimeout(rep); rep = null; if (a === 'soft') softDrop = false; };
btn.addEventListener('pointerdown', e => {
e.preventDefault();
unlockAudio();
if (state === 'ready' || state === 'over'){ if (a === 'hard') primary(); return; }
act(a);
if (a === 'left' || a === 'right'){
const tick = () => { act(a); rep = setTimeout(tick, 65); };
rep = setTimeout(tick, 170);
}
});
btn.addEventListener('pointerup', stop);
btn.addEventListener('pointercancel', stop);
btn.addEventListener('pointerleave', stop);
});
playBtn.addEventListener('click', e => { e.currentTarget.blur(); primary(); });
holdBox.addEventListener('pointerdown', e => { e.preventDefault(); unlockAudio(); if (state === 'playing') act('hold'); });
muteBtn.addEventListener('click', e => {
e.currentTarget.blur();
muted = !muted;
localStorage.setItem('neon-tetris-muted', muted ? '1' : '0');
muteBtn.textContent = muted ? '🔇' : '🔊';
if (!muted){ unlockAudio(); tone(880, .07, 'triangle', .05); }
});
document.addEventListener('visibilitychange', () => {
if (document.hidden && state === 'playing') togglePause();
});
/* ============ 更新 ============ */
function update(dt){
if (shake > 0) shake = Math.max(0, shake - dt * 0.035);
if (state === 'clearing'){
clearAnim.t += dt;
if (clearAnim.t >= CLEAR_MS) finishClear();
return;
}
if (state !== 'playing' || !cur) return;
const g = softDrop ? Math.min(SOFT_MS, gravityMs()) : gravityMs();
dropTimer += dt;
while (dropTimer >= g){
dropTimer -= g;
if (tryMove(0, 1)){
if (softDrop) score += 1;
} else {
dropTimer = 0;
break;
}
}
if (collides(cur.m, cur.x, cur.y + 1)){
lockTimer += dt;
if (lockTimer >= LOCK_MS) lockPiece();
} else {
lockTimer = 0;
}
updateHud();
}
/* ============ 绘制 ============ */
function renderBoardLayer(){
bctx.clearRect(0, 0, W, H);
for (let y = 0; y < ROWS; y++)
for (let x = 0; x < COLS; x++){
const c = board[y][x];
if (c) drawBlock(bctx, x * CELL, y * CELL, CELL, c, true);
}
boardDirty = false;
}
function draw(){
ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
const bg = ctx.createLinearGradient(0, 0, 0, H);
bg.addColorStop(0, '#0b1327');
bg.addColorStop(1, '#05070f');
ctx.fillStyle = bg;
ctx.fillRect(0, 0, W, H);
ctx.save();
if (shake > 0.3) ctx.translate((Math.random() - .5) * shake, (Math.random() - .5) * shake);
ctx.strokeStyle = 'rgba(120,170,255,.07)';
ctx.lineWidth = 1;
ctx.beginPath();
for (let x = 1; x < COLS; x++){ ctx.moveTo(x * CELL + .5, 0); ctx.lineTo(x * CELL + .5, H); }
for (let y = 1; y < ROWS; y++){ ctx.moveTo(0, y * CELL + .5); ctx.lineTo(W, y * CELL + .5); }
ctx.stroke();
if (boardDirty) renderBoardLayer();
ctx.drawImage(boardCv, 0, 0, W, H);
if (cur && (state === 'playing' || state === 'paused')){
// 幽灵块
let gy = cur.y;
while (!collides(cur.m, cur.x, gy + 1)) gy++;
if (gy !== cur.y){
ctx.save();
ctx.strokeStyle = COLORS[cur.type];
ctx.fillStyle = COLORS[cur.type];
ctx.lineWidth = 2;
for (let y = 0; y < cur.m.length; y++)
for (let x = 0; x < cur.m[y].length; x++){
if (!cur.m[y][x]) continue;
const bx = (cur.x + x) * CELL, by = (gy + y) * CELL;
roundRect(ctx, bx + 3, by + 3, CELL - 6, CELL - 6, CELL * 0.18);
ctx.globalAlpha = .12; ctx.fill();
ctx.globalAlpha = .4; ctx.stroke();
}
ctx.restore();
}
// 当前方块
for (let y = 0; y < cur.m.length; y++)
for (let x = 0; x < cur.m[y].length; x++){
if (!cur.m[y][x]) continue;
drawBlock(ctx, (cur.x + x) * CELL, (cur.y + y) * CELL, CELL, COLORS[cur.type], true);
}
}
if (state === 'clearing' && clearAnim){
const p = Math.min(1, clearAnim.t / CLEAR_MS);
for (const y of clearAnim.rows){
ctx.fillStyle = `rgba(255,255,255,${0.9 * (1 - p)})`;
ctx.fillRect(0, y * CELL, W, CELL);
ctx.fillStyle = `rgba(57,255,208,${0.55 * (1 - p)})`;
ctx.fillRect(0, y * CELL + CELL * 0.4 * p, W, CELL * 0.2);
}
}
ctx.restore();
ctx.strokeStyle = 'rgba(57,255,208,.22)';
ctx.lineWidth = 2;
ctx.strokeRect(1, 1, W - 2, H - 2);
}
function drawMini(cv, type){
const c = cv.getContext('2d');
c.setTransform(DPR, 0, 0, DPR, 0, 0);
c.clearRect(0, 0, MINI_CELL * MINI_N, MINI_CELL * MINI_N);
if (!type) return;
const m = SHAPES[type];
let minX = 9, maxX = -1, minY = 9, maxY = -1;
for (let y = 0; y < m.length; y++)
for (let x = 0; x < m[y].length; x++)
if (m[y][x]){
if (x < minX) minX = x;
if (x > maxX) maxX = x;
if (y < minY) minY = y;
if (y > maxY) maxY = y;
}
const ox = (MINI_N - (maxX - minX + 1)) / 2;
const oy = (MINI_N - (maxY - minY + 1)) / 2;
for (let y = 0; y < m.length; y++)
for (let x = 0; x < m[y].length; x++){
if (!m[y][x]) continue;
drawBlock(c,
(ox + x - minX) * MINI_CELL,
(oy + y - minY) * MINI_CELL,
MINI_CELL, COLORS[type], false);
}
}
function renderNext(){
for (let i = 0; i < 3; i++) drawMini(nextCvs[i], nextQueue[i] || null);
}
function renderHold(){ drawMini(holdCv, holdType); }
/* ============ 界面 ============ */
function updateHud(){
setText(scoreEl, score);
setText(levelEl, level);
setText(linesEl, lines);
}
function showOverlay(title, text, btn){
ovTitle.textContent = title;
ovText.innerHTML = text;
playBtn.textContent = btn;
overlay.classList.remove('hidden');
}
function hideOverlay(){ overlay.classList.add('hidden'); }
/* ============ 主循环 ============ */
let last = performance.now();
function loop(now){
const dt = Math.min(now - last, 120);
last = now;
update(dt);
draw();
requestAnimationFrame(loop);
}
/* ============ 启动 ============ */
muteBtn.textContent = muted ? '🔇' : '🔊';
board = Array.from({length: ROWS}, () => new Array(COLS).fill(null));
bag = []; nextQueue = []; holdType = null;
score = 0; lines = 0; level = 1; combo = -1;
dropTimer = 0; lockTimer = 0; lockResets = 0; softDrop = false;
clearAnim = null; shake = 0; boardDirty = true; cur = null;
renderNext(); renderHold(); updateHud();
showOverlay('霓虹俄罗斯方块',
'← → 移动 · ↓ 软降 · 空格 硬降 · ↑/X 顺时针 · Z 逆时针<br>C 暂存 · P 暂停<br>右侧 <b>NEXT</b> 显示接下来三个方块,<b>HOLD</b> 可点击暂存<br>一次消 4 行是 Tetris,连消还有额外加分',
'开始游戏');
requestAnimationFrame(loop);
})();
</script>
</body>
</html>