<내 코드>
const holes = document.querySelectorAll('.hole');
const scoreBoard = document.querySelector('.score');
const moles = document.querySelectorAll('.mole');
let holeup;
let randHole;
let time;
let showCount = 0;
let catchCount = 0;
function startGame() {
pickHole();
upTime();
showMole();
console.log(showCount);
}
function pickHole() {
// 1에서 6사이의 랜덤 숫자 뽑기
randHole = Math.floor(Math.random() * 6 + 1);
}
function upTime() {
//0 ~ 2초 사이 시간 뽑기
time = Math.random() * 2;
}
function showMole() {
const holeAppear = document.querySelector(`.hole${randHole}`);
holeAppear.classList.add('up');
holeup = document.querySelector('.hole.up');
showCount++;
setTimeout(() => {
holeAppear.classList.remove('up');
if (showCount < 10) startGame();
}, time * 1000);
}
function catchMole() {
catchCount++;
scoreBoard.textContent = catchCount;
}
moles.forEach((mole) => mole.addEventListener('click', catchMole));
<정답코드>
const holes = document.querySelectorAll('.hole');
const scoreBoard = document.querySelector('.score');
const moles = document.querySelectorAll('.mole');
let lastHole;
let timeUp = false;
let score = 0;
function randomTime(min, max) {
return Math.round(Math.random() * (max - min) + min);
}
function randomHole(holes) {
const idx = Math.floor(Math.random() * holes.length);
const hole = holes[idx];
if (hole === lastHole) {
console.log('Ah nah thats the same one bud');
return randomHole(holes);
}
lastHole = hole;
return hole;
}
function peep() {
const time = randomTime(200, 1000);
const hole = randomHole(holes);
hole.classList.add('up');
setTimeout(() => {
hole.classList.remove('up');
if (!timeUp) peep();
}, time);
}
function startGame() {
scoreBoard.textContent = 0;
timeUp = false;
score = 0;
peep();
setTimeout(() => (timeUp = true), 10000);
}
function bonk(e) {
if (!e.isTrusted) return; // cheater!
score++;
this.parentNode.classList.remove('up');
scoreBoard.textContent = score;
}
moles.forEach((mole) => mole.addEventListener('click', bonk));
setTimeout(() => {
holeAppear.classList.remove('up');
if (showCount < 10) startGame();
}, time * 1000);
function randomTime(min, max) {
return Math.round(Math.random() * (max - min) + min);
}