document.addEventListener('DOMContentLoaded', () => { const gameArea = document.getElementById('game-area'); const scoreElement = document.getElementById('score'); const startButton = document.getElementById('start-button');
let score = 0;
let gameInterval = null;
let isGameRunning = false;
// 创建一行方块
function createRow() {
const row = document.createElement('div');
row.className = 'row';
// 随机选择一个方块作为黑块
const blackIndex = Math.floor(Math.random() * 4);
for (let i = 0; i < 4; i++) {
const block = document.createElement('div');
block.className = 'block';
if (i === blackIndex) {
block.classList.add('black');
}
row.appendChild(block);
}
gameArea.insertBefore(row, gameArea.firstChild);
}
// 移除最后一行
function removeLastRow() {
if (gameArea.children.length > 6) {
const lastRow = gameArea.lastChild;
// 检查最后一行是否有未点击的黑块
for (const block of lastRow.children) {
if (block.classList.contains('black')) {
endGame();
return;
}
}
gameArea.removeChild(lastRow);
}
}
// 游戏主循环
function gameLoop() {
createRow();
removeLastRow();
}
// 开始游戏
function startGame() {
score = 0;
scoreElement.textContent = score;
gameArea.innerHTML = '';
isGameRunning = true;
startButton.disabled = true;
// 初始创建3行
for (let i = 0; i < 3; i++) {
createRow();
}
gameInterval = setInterval(gameLoop, 1000);
}
// 结束游戏
function endGame() {
clearInterval(gameInterval);
isGameRunning = false;
startButton.disabled = false;
alert(`游戏结束!你的得分是: ${score}`);
}
// 点击方块处理
gameArea.addEventListener('click', (e) => {
if (!isGameRunning) return;
const block = e.target;
if (block.classList.contains('black')) {
score++;
scoreElement.textContent = score;
block.classList.remove('black');
block.style.backgroundColor = '#ddd';
} else {
endGame();
}
});
startButton.addEventListener('click', startGame);
});