79 lines
2.0 KiB
JavaScript
79 lines
2.0 KiB
JavaScript
const gridDiv = document.getElementById('grid');
|
|
const scoreSpan = document.getElementById('score-value');
|
|
const timerSpan = document.getElementById('timer-value');
|
|
const startBtn = document.getElementById('start-btn');
|
|
const endMessageDiv = document.getElementById('end-message');
|
|
|
|
const TOTAL_TIME = 30;
|
|
const GRID_SIZE = 16;
|
|
const MOLE_SYMBOL = '🦦';
|
|
|
|
let score = 0, moleIdx = null, timer = TOTAL_TIME, intervalId, moleTimeoutId, playing = false;
|
|
|
|
function createGrid() {
|
|
gridDiv.innerHTML = '';
|
|
for (let i = 0; i < GRID_SIZE; i++) {
|
|
const cell = document.createElement('div');
|
|
cell.className = 'cell';
|
|
cell.dataset.idx = i;
|
|
cell.onclick = () => hitCell(i);
|
|
gridDiv.appendChild(cell);
|
|
}
|
|
}
|
|
|
|
function startGame() {
|
|
score = 0;
|
|
timer = TOTAL_TIME;
|
|
scoreSpan.textContent = score;
|
|
timerSpan.textContent = timer;
|
|
endMessageDiv.textContent = '';
|
|
startBtn.disabled = true;
|
|
playing = true;
|
|
createGrid();
|
|
spawnMole();
|
|
intervalId = setInterval(() => {
|
|
timer--;
|
|
timerSpan.textContent = timer;
|
|
if (timer <= 0) endGame();
|
|
}, 1000);
|
|
}
|
|
|
|
function endGame() {
|
|
playing = false;
|
|
clearInterval(intervalId);
|
|
clearTimeout(moleTimeoutId);
|
|
startBtn.disabled = false;
|
|
removeMole();
|
|
endMessageDiv.innerHTML = `¡Fin del juego! Tu puntaje: <b>${score}</b>`;
|
|
}
|
|
|
|
function spawnMole() {
|
|
removeMole();
|
|
if (!playing) return;
|
|
moleIdx = Math.floor(Math.random() * GRID_SIZE);
|
|
const cell = gridDiv.children[moleIdx];
|
|
cell.classList.add('mole');
|
|
cell.textContent = MOLE_SYMBOL;
|
|
moleTimeoutId = setTimeout(spawnMole, Math.floor(Math.random() * 700) + 600); // aparecer entre 0.6-1.3s
|
|
}
|
|
|
|
function removeMole() {
|
|
if (moleIdx !== null) {
|
|
const cell = gridDiv.children[moleIdx];
|
|
cell.classList.remove('mole');
|
|
cell.textContent = '';
|
|
moleIdx = null;
|
|
}
|
|
}
|
|
|
|
function hitCell(idx) {
|
|
if (!playing) return;
|
|
if (idx === moleIdx) {
|
|
score++;
|
|
scoreSpan.textContent = score;
|
|
removeMole();
|
|
}
|
|
}
|
|
|
|
startBtn.onclick = startGame;
|
|
createGrid(); |