상세 컨텐츠

본문 제목

16_ 두더지잡기

Javascript

by 모모87 2021. 4. 26. 11:34

본문

 

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Whack A Mole!</title>
        <link
            href="https://fonts.googleapis.com/css?family=Amatic+SC:400,700"
            rel="stylesheet"
            type="text/css"
        />
        <link rel="stylesheet" href="style.css" />
    </head>
    <body>
        <h1>두더지를 잡아라!! <span class="score">0</span></h1>
        <button onClick="startGame()" class="btn-start">시작!</button>

        <div class="game">
            <div class="hole hole1">
                <div class="mole"></div>
            </div>
            <div class="hole hole2">
                <div class="mole"></div>
            </div>
            <div class="hole hole3">
                <div class="mole"></div>
            </div>
            <div class="hole hole4">
                <div class="mole"></div>
            </div>
            <div class="hole hole5">
                <div class="mole"></div>
            </div>
            <div class="hole hole6">
                <div class="mole"></div>
            </div>
        </div>

        <script>
            const holes = document.querySelectorAll('.hole');
            const scoreBoard = document.querySelector('.score');
            const moles = document.querySelectorAll('.mole');
            let lastHole;
            lastTimeUp = 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('또나왔네');
                    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;
                score++;
                this.classList.remove('up');
                scoreBoard.textContent = score;
            }
            moles.forEach((mole) => mole.addEventListener('click', bonk));
        </script>
    </body>
</html>
반응형

관련글 더보기