관리 메뉴

샐님은 개발중

7강 가위바위보 - 타이머(setInterval), removeEventListener 본문

자바스크립트/인프런강의-렛츠기릿 자바스크립트

7강 가위바위보 - 타이머(setInterval), removeEventListener

샐님 2023. 7. 5. 16:43
728x90
반응형

1. 이미지 파일 적용

    const Img_url = './rsp.png'; // ./(상대경로) : 현재 폴더를 기준으로 하는 경로   ../  : 부모폴더를 기준  ex) ../../../rsp.png
        //     /(루트폴더) : 윈도우는 보통 c드라이브가 루트폴더가 된다.
        $computer.style.background = `url(${Img_url}) -464px 0`; // url(url,가로 ,세로)

2. 공통점있는 변수 객체로 묶기

 const scissorsX = '-0' //가위
        const rockX = '-232px' //바위
        const paperX = '-431px' //보
            // 이 변수들은 X 좌표라는 공통점이 있다. 따라서 객체로 묶어서 표현가능
        const rspX = {
            scissorsX: '-0',
            rockX: '-232px',
            paperX: '-431px',
        }

3.일정시간마다 반복

   const rspX = {
            scissors: '-0',
            rock: '-232px',
            paper: '-431px',
        }
        let coord = '0';
        setInterval
            (() => {
                if (coord === rspX.scissors) { //가위면
                    $computer.style.background = `url(${Img_url} ${rspX.rock} 0)`;
                    $computer.style.backgroundSize = 'auto 200px';
                } else if (coord === rspX.rock) { //바위면
                    $computer.style.background = `url(${Img_url} ${rspX.paper} 0)`;
                    $computer.style.backgroundSize = 'auto 200px';
                } else if (coord === rspX.paper) { //보면
                    $computer.style.background = `url(${Img_url} ${rspX.scissors} 0)`;
                    $computer.style.backgroundSize = 'auto 200px';
                }
            }, 50);

 - 사람이 읽기 쉽게 코드를 변경해보자

   let computerChoice = 'scissors';
        setInterval
            (() => {
                if (computerChoice === 'scissors') { //가위면
                    computerChoice = 'rock';
                } else if (computerChoice === 'rock') { //바위면
                    computerChoice = 'paper';
                } else if (computerChoice === 'paper') { //보면
                    computerChoice = 'scissors';
                }
                $computer.style.background = `url(${Img_url} ${rspX[computerChoice]} 0)`;
                $computer.style.backgroundSize = 'auto 200px';
            }, 50);

4. setInterval 함수는 반환값이 있고 이 반환값은 타이머에 대한 아이디로이 값을 사용해 타이머를 제거할수 있다.

 
const clickButton = () => {
            clearInterval(intervalId);
            setTimeout(() => {
                    clearInterval(intervalId);
                    // 버튼을 누를수록 속도가 점점 빨라지는 버그 -> 인터벌이 여러개 생겨서 지워지지않음.
                   // 한번더 clearInterval 을 호출해서 남아있는 겻을 지워준다. * 어려워서 나중에 다시 복습하기.    
                    intervalId = setInterval(changeComputerHand, 50);
                },
                1000);
        };
        $rock.addEventListener('click', clickButton);
        $scissors.addEventListener('click', clickButton);
        $paper.addEventListener('click', clickButton);

5. removeEventListener


        const fun = (num) => () => {
            console.log('고차함수힙니다', num)
        }
        태그.addEventListener('click', fun(1));
        태그.removeEventListener('click', fun(1));
        fun(1) === fun(1); // false
        // 함수도 객체이기 떄문에 서로 다른 객체라서 false값이 나온다. 그래서 변수를 만들어 참조하는 식으로 해야 같은 객체를 바라보게 할수 있다.
        const fun1 = fun(1);
        fun1 === fun1; // true
        태그.addEventListener('click', fun1);
        태그.removeEventListener('click', fun1);
 

 

6. 전체 소스

<html>

<head>
    <meta charset="utf-8" />
    <title>가위바위보</title>
    <style>
        #computer {
            width: 142px;
            height: 200px;
        }
    </style>
</head>

<body>
    <div id="computer"></div>
    <div>
        <button id="scissors" class="btn">가위</button>
        <button id="rock" class="btn">바위</button>
        <button id="paper" class="btn"></button>
    </div>
    <div id="score">0</div>
    <script>
        const $computer = document.querySelector("#computer");
        const $scissors = document.querySelector("#scissors");
        const $rock = document.querySelector("#rock");
        const $paper = document.querySelector("#paper");
        const $score = document.querySelector('#score');
        const Img_url = './rsp.png'; // ./(상대경로) : 현재 폴더를 기준으로 하는 경로   ../  : 부모폴더를 기준  ex) ../../../rsp.png
        //     /(루트폴더) : 윈도우는 보통 c드라이브가 루트폴더가 된다.
        $computer.style.background = `url(${Img_url}) -464px 0`; // url(url,가로 ,세로)
        $computer.style.backgroundSize = 'auto 200px'; // '넓이 높이' auto는 높이에 따라 자동으로 넓이가 맞추어진다.
        // 위치 :  가위 0 바위  -232px보 -431px
        $computer.style.background = `url(${Img_url}) -0 0`; //가위
        $computer.style.background = `url(${Img_url}) -232px 0`; //바위
        $computer.style.background = `url(${Img_url}) -431px 0`; //보

        // 이 변수들은 X 좌표라는 공통점이 있다. 따라서 객체로 묶어서 표현가능
        const rspX = {
            scissors: '-0',
            rock: '-232px',
            paper: '-431px',
        }
        let computerChoice = 'scissors';
        let score = 0;
        const changeComputerHand = () => {
            if (computerChoice === 'scissors') { //가위면
                computerChoice = 'rock';
            } else if (computerChoice === 'rock') { //바위면
                computerChoice = 'paper';
            } else if (computerChoice === 'paper') { //보면
                computerChoice = 'scissors';
            }
            $computer.style.background = `url(${Img_url}) ${rspX[computerChoice]} 0`;
            $computer.style.backgroundSize = 'auto 200px';
        }
        let intervalId = setInterval(changeComputerHand, 50);
        const scoreTable = {
            rock: 0,
            scissors: 1,
            paper: -1,
        };

        // setInterval 함수는 반환값이 있고 이 반환값은 타이머에 대한 아이디로이 값을 사용해 타이머를 제거할수 있다.
        const clickButton = () => {
            clearInterval(intervalId);
            // 점수 계산 및 화면 표시


            let message;
            const myChoice = event.target.textContent === '바위' ?
                'rock' :
                event.target.textContent === '가위' ?
                'scissors' :
                'paper';
            // 2, -1은 승리조건이고, -2, 1은 패배조건, 점수표 참고
            const myScore = scoreTable[myChoice];
            const computerScore = scoreTable[computerChoice];
            const diff = myScore - computerScore;
            if ([2, -1].includes(diff)) {
                score += 1;
                message = '승리';
            } else if ([-2, 1].includes(diff)) {
                score -= 1;
                message = '패배';
            } else {
                message = '무승부';
            }
            alert(score)
            $score.textContent = `${message} 총: ${score}`;


            setTimeout(() => {
                    clearInterval(intervalId);
                    intervalId = setInterval(changeComputerHand, 50);
                },
                1000);
        };
        $rock.addEventListener('click', clickButton);
        $scissors.addEventListener('click', clickButton);
        $paper.addEventListener('click', clickButton);
    </script>
</body>

</html>
728x90
반응형