<button id="startBtn">スタート</button>
<p id="score">0点</p>
<p id="timer">10秒</p>
<div id="stage"></div>
#stage {
position: relative;
width: 300px;
height: 300px;
background: #8B4513;
border-radius: 8px;
margin-top: 10px;
}
.mole {
position: absolute;
font-size: 40px;
cursor: pointer;
user-select: none;
}
const startBtn = document.querySelector('#startBtn');
const score = document.querySelector('#score');
const timer = document.querySelector('#timer');
const stage = document.querySelector('#stage');
let count = 0;
let timeLeft = 10;
let gameInterval;
let timerInterval;
startBtn.addEventListener('click', function() {
count = 0;
timeLeft = 10;
score.textContent = '0点';
timer.textContent = '10秒';
stage.innerHTML = '';
startBtn.disabled = true;
// もぐらを出すインターバル
gameInterval = setInterval(function() {
const mole = document.createElement('div');
mole.textContent = '🐭';
mole.classList.add('mole');
mole.style.left = Math.random() * 250 + 'px';
mole.style.top = Math.random() * 250 + 'px';
stage.appendChild(mole);
mole.addEventListener('click', function() {
mole.remove();
count = count + 1;
score.textContent = count + '点';
});
// 1秒後に自動で消える
setTimeout(function() {
mole.remove();
}, 1000);
}, 800);
// タイマーのインターバル
timerInterval = setInterval(function() {
timeLeft = timeLeft - 1;
timer.textContent = timeLeft + '秒';
if (timeLeft === 0) {
clearInterval(gameInterval);
clearInterval(timerInterval);
stage.innerHTML = '';
startBtn.disabled = false;
timer.textContent = '終了!' + count + '点でした!';
}
}, 1000);
});