JAVA script

[JavaScript] 랜덤 가위바위보 게임 만들기

peach_h 2023. 9. 5. 20:05
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>가위바위보</title>
    <style>
      h1 {
        font-size: 200px;
        font-weight: bold;
      }
      button {
        font-size: 20px;
        padding: 10px 30px;
        cursor: pointer;
      }
    </style>
    <script>
      window.onload = function () {
        var button = document.querySelector(".startBtn");
        // 첫번째 h1 태그를 선택
        var h1 = document.getElementsByTagName("h1")[0];

        var handArr = ["가위", "바위", "보"];
        button.addEventListener("click", function () {
          // 배열 개수를 센 후, 소수를 반올림
          var num = Math.round(Math.random() * (handArr.length - 1));
          h1.innerHTML = handArr[num];
        });
      };
    </script>
  </head>
  <body>
    <button type="button" class="startBtn">리셋</button>
    <h1>가위</h1>
  </body>
</html>

리셋 버튼을 누르면 랜덤하게 가위 바위 보가 출력된다 !