JS를 이용한 가위바위보 게임

2020. 1. 10. 21:01JAVASCRIPT

실행: https://codepen.io/ffuqgvsz/pen/rNavNrw

 

가위바위보게임

...

codepen.io

공부: object.entries(객체)로 객체를 배열모양로 바꿀 수 있습니다.
배열.find는 반복문이지만 원하는 것을 찾으면(return이 true) 멈춥니다.
※ 1차원 배열에서는 indexOf를 주로쓰고 2차원 배열에서는 find(), findIndex()를 주로쓴다.
배열 .includes로 || 관계를 줄일 수 있다.

 

<!DOCTYPE html>

<html lang="ko">

  <head>

    <meta charset="UTF-8" />

    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <meta http-equiv="X-UA-Compatible" content="ie=edge" />

    <title>가위바위보</title>

    <style>

      #computer {

        width208px;

        height218px;

        backgroundurl("https://steemitimages.com/640x0/https://steemitimages.com/DQmVDkcxCxbuJJtwRiGv2xLoKt1eDMoznW1wYZyqJ9gQgCv/%EA%B0%80%EC%9C%846%5B1%5D.png"-3px

          0;

      }

    </style>

  </head>

  <body>

    <div id="computer"></div>

    <div>

      <button id="scissor" class="btn">가위</button>

      <button id="rock" class="btn">바위</button>

      <button id="paper" class="btn"></button>

    </div>

    <h1>결과는?</h1>

    <script>

      var h1 = document.querySelector("h1");

      var imgLocation = 0//이미지좌표 변수

      var RockScissorPaper = {

        //딕셔너리 자료구조

        바위: "0",

        가위: "-203px",

        보: "-414px"

      };

      console.log(Object.entries(RockScissorPaper)); //객체를 2차원 배열로 만든 값

      function comChoose(imgLocation) {

        //배열안에서 이미지좌표값을 확인하고 가위바위보를 추출

        return Object.entries(RockScissorPaper).find(function(v) {

          return v[1] === imgLocation;

        })[0];

      }

 

      var interval;

      function intervalMake() {

        clearInterval(interval); //이미지를 멈춘다

        interval = setInterval(function() {

          if (imgLocation === RockScissorPaper.바위) {

            imgLocation = RockScissorPaper.가위;

          } else if (imgLocation === RockScissorPaper.가위) {

            imgLocation = RockScissorPaper.;

          } else {

            imgLocation = RockScissorPaper.바위;

          }

          //이미지 스프라이트

          document.querySelector("#computer").style.background =

            "url(https://steemitimages.com/640x0/https://steemitimages.com/DQmVDkcxCxbuJJtwRiGv2xLoKt1eDMoznW1wYZyqJ9gQgCv/%EA%B0%80%EC%9C%846%5B1%5D.png) " +

            imgLocation +

            " 0";

        }, 100);

      }

      intervalMake();

 

      var score = {

        바위: 0,

        가위: 1,

        보: -1

      };

 

      //querySelectorAll은 forEach로 각각 클래스에 이벤트를 넣어줘야한다.

      document.querySelectorAll(".btn").forEach(function(btn) {

        btn.addEventListener("click"function() {

          clearInterval(interval); //이미지를 멈춘다

          setTimeout(function() {

            //1.5초 뒤 다시 이미지 실행

            intervalMake();

          }, 1000);

          var myChoose = this.textContent//내가 고른 변수

          var myValue = score[myChoose]; //내가 선택한 score객체 값

          var comValue = score[comChoose(imgLocation)]; //컴퓨터가 선택한 score객체 값

          if (myValue - comValue === 0) {

            h1.innerText = "비겼습니다.";

          } else if (

            // score[myChoose] - score[comChoose(imgLocation)] === -1 ||

            // score[myChoose] - score[comChoose(imgLocation)] === 2

            [-12].includes(myValue - comValue)

          ) {

            h1.innerText = "이겼습니다.";

          } else {

            h1.innerText = "졌습니다.";

          }

        });

      });

 

      // 가위=1 바위=0 보=-1를 이용해서 표로 작성

      //*뺀 값이 0이나오면 비긴거 -1,2가 나오면 이긴거 -2,1이 나오면 진거*

      // 나/컴퓨터  가위  바위    보

      //    가위    1 1   1 0   1 -1

      //    바위    0 1   0 0   0 -1

      //     보    -1 1  -1 0  -1 -1

    </script>

  </body>

</html>

 

'JAVASCRIPT' 카테고리의 다른 글

JS Promise란  (0) 2020.01.14
jQuery를 이용한 탭 메뉴 기능  (0) 2020.01.12
동기와 비동기  (0) 2020.01.09
JS로 만든 숫자야구게임  (0) 2020.01.09
클로저의 의미와 사용하는 이유  (2) 2020.01.07