본문 바로가기
자바스크립트(Java Script)/자바스크립트(Java Script) 강의 정리

제로초 JS 입문 강의 7강 정리 (가위바위보 순서도)

by 인생즐겜러 2024. 8. 13.
728x90
반응형

 

 

 

 

 

7 - 1 이미지 추가

 

background와 backgroundsize는 세트로 같이 가야 적용된다.

반복문 같은 곳에서 따로 쓰면 적용이 제대로 안된다.

 

<div id='com'></div>



const IMG_URL = './rsp.png'
$com.style.backgound = `url(${IMG_URL}) 0 0`; // 이미지변수 가로위치 세로위치
$com.style.backgoundsize = 'auto 200px'; // 가로너비 세로너비



6행을 사용하면 여러가지 이미지가 한 이미지로 있다고 하더라도
각각 위치 별로 세팅 후 너비 세팅하면 잘린 이미지를 가져올 수 있게 된다.

 

 

 

 

 

7 - 2~3 setInterval(함수, ms)

함수를 주기적으로 실행한다.

0.5초 단위로 가위 바위 보 이미지가 바뀌게 하려면 아래와 같다.

안의 코드가 끝나야 반복하기 때문에 적힌 주기대로 무조건 동작하지는 않는다.

 

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

 

 

 

clearInterval(아이디);

위 함수를 사용해야 setInterval 함수를 멈출 수 있다.

 

 

 

 

 

7 - 4 removeEventListener(이벤트타입 , 함수)

addEventListener 를 지우는 함수이다.

다만, 사용 시 조심해야하는 건

아래처럼 이벤트를 지웠다고 생각하겠지만 지워지지 않는다.

왜냐하면 위아래의 clickButton 은 각각 다른 객체이기 때문이다.

같은 객체를 지웠을 때만 비로소 이벤트가 지워진다.

 

$rock.addEventListener('click', clickButton);
$rock.removeEventListener('click', clickButton);
 
 
 
 
 
7 - 5 event.target 개념
 
<div id="yyy">메롱<div>

<script>
let test = document.getElementById("yyy");
test.addEventListener("click", function(event){
        alert("안녕 메롱");
    });
 </script>

 

 

console.log 로 찍어보면 나오는 결과값은 아래와 같다.

 

event.target.tagName  : div
event.target.id : yyy
event.target.textContent : 메롱

 

 

 

 

 


 

 

 

 

 

완성본.

이미지 파일이 없어서 이미지 파일 쪽은 따로 안나온다.

 

가위바위보
시작해보자, 너와 나의 죽음의 승부
3번 지면 너는 손목이 날아가는 거시여~



현재까지 0 승 / 0 패라네~

 

 

 

<html>

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

<body>
  <div>시작해보자, 너와 나의 죽음의 승부</div>
  <div>3번 지면 너는 손목이 날아가는 거시여~</div>
  <br>
  <div id="computer"></div>
  <br>
  <div>
    <button id="scissors" class="btn">가위</button>
    <button id="rock" class="btn">바위</button>
    <button id="paper" class="btn">보</button>
  </div>
  <br>
  <div id="result"></div>
  <div>현재까지 <span id="win">0</span> 승 / <span id="lose">0</span> 패라네~</div>

  <script>
    // 변수 세팅 ===============================================================================
    const $computer = document.querySelector("#computer");
    const $result = document.querySelector("#result");
    const $win = document.querySelector("#win");
    const $lose = document.querySelector("#lose");
    const $rock = document.querySelector("#rock");
    const $scissors = document.querySelector("#scissors");
    const $paper = document.querySelector("#paper");
    const IMG_URL = './gbb.png';
    let win = 0;
    let lose = 0;
    $computer.style.background = `url(${IMG_URL}) 0 0`;
    $computer.style.backgroundSize = `auto 200px`;

    // 모양에 따른 이미지 위치
    const rspX = {
      scissors: '0',
      rock: '-220px',
      paper: '-440px',
    };

    // 낸 값을 숫자로 변환
    const choiceTable = {
      scissors: 1,
      rock: 0,
      paper: -1,
    };



    // 함수 세팅 ===============================================================================

    // 컴퓨터 측 자동 모양 변환
    let computerChoice = 'scissors';    // 컴퓨터 측 결과값
    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`;
    }

    // 0.5초 단위로 모양 변환
    let intervalId = setInterval(changeComputerHand, 50);

    // 버튼 누르면 모양 멈춤
    // 클릭 후 3초 뒤에 재 클릭이 실행 될 수 있게
    let checkClick = true;
    const clickButton = () => {
      if (checkClick) {
        clearInterval(intervalId);  // 인터벌 클리어
        checkClick = false;         // 연속 클릭 안 되게 바꾸고

        // 내 클릭 값
        const myChoice = event.target.id === 'scissors' ? 'scissors'
          : event.target.id === 'rock' ? 'rock'
            : 'paper'

        // 결과 비교 변수 선언
        const diff = choiceTable[computerChoice] - choiceTable[myChoice];

        // 값 중간 확인
        console.log(computerChoice);
        console.log(myChoice);

        // 승부 값 체크
        if (diff === 0) {  // 비김
          $result.textContent = '이욜 어케 비겼누?';
        } else if (diff === -2 || diff === 1) { // 이김
          $result.textContent = '헐 뭐야 이겼어. 좀 치네?';
          ++win;
          $win.textContent = win;
        } else if (diff === -1 || diff === 2) { // 짐
          $result.textContent = '깔깔깔ㄲ깔깔깔ㄲㄲㄲㄲㄲㅋㅋㅋㅋㅋ';
          ++lose;
          $lose.textContent = lose;
        }

        // 5판 3선 승 체크
        if (lose === 3) {
          alert('게임 끝났어 임마. 넌 졌어 임마.');
        } else if (win === 3) {
          alert('이게 뭐여!!! 이걸 어케 이겼누!!!');
        } else {
          setTimeout(() => {
            checkClick = true;
            intervalId = setInterval(changeComputerHand, 50);
          }, 2500); // 2.5초 뒤에 
        }

      }
    };

    // 각 버튼을 눌렀을 때 이벤트 발생
    $rock.addEventListener('click', clickButton);
    $scissors.addEventListener('click', clickButton);
    $paper.addEventListener('click', clickButton);

  </script>
</body>

</html>

 

 

 

 

 

728x90
반응형

댓글