tetris/game.js
2025-03-02 22:56:48 +08:00

270 lines
7.1 KiB
JavaScript

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
const nextCanvas = document.getElementById('nextCanvas');
const nextCtx = nextCanvas.getContext('2d');
const scoreElement = document.getElementById('score');
const startBtn = document.getElementById('startBtn');
const pauseBtn = document.getElementById('pauseBtn');
// 方块形状
const SHAPES = [
[[1, 1, 1, 1]], // I
[[1, 1], [1, 1]], // O
[[1, 1, 1], [0, 1, 0]], // T
[[1, 1, 1], [1, 0, 0]], // L
[[1, 1, 1], [0, 0, 1]], // J
[[1, 1, 0], [0, 1, 1]], // S
[[0, 1, 1], [1, 1, 0]] // Z
];
// 方块颜色
const COLORS = [
'#00f0f0', '#f0f000', '#a000f0',
'#f0a000', '#0000f0', '#00f000', '#f00000'
];
// 游戏配置
const BLOCK_SIZE = 30;
const COLS = 10;
const ROWS = 20;
canvas.width = COLS * BLOCK_SIZE;
canvas.height = ROWS * BLOCK_SIZE;
// 计算预览区域尺寸
const maxShapeWidth = Math.max(...SHAPES.map(shape => shape[0].length));
const maxShapeHeight = Math.max(...SHAPES.map(shape => shape.length));
nextCanvas.width = maxShapeWidth * BLOCK_SIZE;
nextCanvas.height = maxShapeHeight * BLOCK_SIZE;
let board = [];
let currentPiece = null;
let nextPiece = null;
let score = 0;
let gameLoop = null;
let gameSpeed = 1000;
let gameOver = false;
function initBoard() {
board = Array(ROWS).fill().map(() => Array(COLS).fill(0));
}
function createPiece() {
const index = Math.floor(Math.random() * SHAPES.length);
return {
shape: SHAPES[index],
color: COLORS[index],
x: Math.floor(COLS/2) - 1,
y: 0
};
}
function drawBlock(ctx, x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x * BLOCK_SIZE, y * BLOCK_SIZE, BLOCK_SIZE-1, BLOCK_SIZE-1);
}
function drawBoard() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制已落下的方块
for (let y = 0; y < ROWS; y++) {
for (let x = 0; x < COLS; x++) {
if (board[y][x]) {
drawBlock(ctx, x, y, board[y][x]);
}
}
}
// 绘制当前下落的方块
if (currentPiece) {
currentPiece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value) {
drawBlock(ctx, currentPiece.x + x, currentPiece.y + y, currentPiece.color);
}
});
});
}
}
function drawNextPiece() {
nextCtx.clearRect(0, 0, nextCanvas.width, nextCanvas.height);
const shapeWidth = nextPiece.shape[0].length;
const shapeHeight = nextPiece.shape.length;
const startX = (maxShapeWidth - shapeWidth) / 2;
const startY = (maxShapeHeight - shapeHeight) / 2;
nextPiece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value) {
drawBlock(nextCtx, startX + x, startY + y, nextPiece.color);
}
});
});
}
function isValidMove(piece, newX, newY) {
return piece.shape.every((row, dy) => {
return row.every((value, dx) => {
let x = newX + dx;
let y = newY + dy;
return (
value === 0 ||
(x >= 0 && x < COLS && y < ROWS && !board[y][x])
);
});
});
}
function rotatePiece() {
const rotated = currentPiece.shape[0].map((_, i) =>
currentPiece.shape.map(row => row[i]).reverse()
);
const previousShape = currentPiece.shape;
currentPiece.shape = rotated;
if (!isValidMove(currentPiece, currentPiece.x, currentPiece.y)) {
currentPiece.shape = previousShape;
}
}
function mergePiece() {
currentPiece.shape.forEach((row, y) => {
row.forEach((value, x) => {
if (value) {
board[currentPiece.y + y][currentPiece.x + x] = currentPiece.color;
}
});
});
}
function clearLines() {
let linesCleared = 0;
for (let y = ROWS - 1; y >= 0; y--) {
if (board[y].every(cell => cell !== 0)) {
board.splice(y, 1);
board.unshift(Array(COLS).fill(0));
linesCleared++;
y++;
}
}
if (linesCleared > 0) {
score += linesCleared * 100;
scoreElement.textContent = score;
gameSpeed = Math.max(100, gameSpeed - 50);
}
}
// 在dropPiece函数中增加暂停按钮隐藏逻辑
function dropPiece() {
if (isValidMove(currentPiece, currentPiece.x, currentPiece.y + 1)) {
currentPiece.y++;
} else {
mergePiece();
clearLines();
currentPiece = nextPiece;
nextPiece = createPiece();
drawNextPiece();
if (!isValidMove(currentPiece, currentPiece.x, currentPiece.y)) {
gameOver = true;
clearInterval(gameLoop);
startBtn.textContent = '重新开始';
startBtn.style.display = 'block';
pauseBtn.style.display = 'none';
}
}
}
function moveHorizontal(dx) {
const newX = currentPiece.x + dx;
if (isValidMove(currentPiece, newX, currentPiece.y)) {
currentPiece.x = newX;
}
}
function handleKeyPress(e) {
if (gameOver) return;
switch(e.key) {
case 'ArrowLeft': moveHorizontal(-1); break;
case 'ArrowRight': moveHorizontal(1); break;
case 'ArrowDown': dropPiece(); break;
case 'ArrowUp': rotatePiece(); break;
}
drawBoard();
}
// 移动端控制
document.getElementById('left').addEventListener('click', () => {
moveHorizontal(-1);
drawBoard();
});
document.getElementById('right').addEventListener('click', () => {
moveHorizontal(1);
drawBoard();
});
document.getElementById('rotate').addEventListener('click', () => {
rotatePiece();
drawBoard();
});
document.getElementById('down').addEventListener('click', () => {
dropPiece();
drawBoard();
});
startBtn.addEventListener('click', () => {
initBoard();
score = 0;
gameSpeed = 1000;
gameOver = false;
scoreElement.textContent = score;
startBtn.style.display = 'none';
currentPiece = createPiece();
nextPiece = createPiece();
drawNextPiece();
if (gameLoop) clearInterval(gameLoop);
gameLoop = setInterval(() => {
dropPiece();
drawBoard();
}, gameSpeed);
});
// 初始化游戏
document.addEventListener('keydown', handleKeyPress);
initBoard();
drawBoard();
// 新增暂停功能
let isPaused = false;
pauseBtn.addEventListener('click', () => {
if (gameOver) return;
isPaused = !isPaused;
if (isPaused) {
clearInterval(gameLoop);
pauseBtn.textContent = '继续';
} else {
gameLoop = setInterval(gameStep, gameSpeed);
pauseBtn.textContent = '暂停';
}
});
function gameStep() {
dropPiece();
drawBoard();
}
startBtn.addEventListener('click', () => {
initBoard();
score = 0;
gameSpeed = 1000;
gameOver = false;
isPaused = false;
scoreElement.textContent = score;
startBtn.style.display = 'none';
pauseBtn.style.display = 'inline-block';
pauseBtn.textContent = '暂停';
currentPiece = createPiece();
nextPiece = createPiece();
drawNextPiece();
if (gameLoop) clearInterval(gameLoop);
gameLoop = setInterval(gameStep, gameSpeed);
});