JAVASCRIPT

[JAVASCRIPT] Math๋ฅผ ์ด์šฉํ•œ ๋žœ๋ค ์ˆซ์ž ๋งž์ถ”๊ธฐ ๊ฒŒ์ž„

Arr_ 2021. 11. 1. 21:41

 

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      div * {
        padding: 10px;
        margin: 10px;
      }
      [readonly] {
        background-color: lightgrey;
      }
    </style>
  </head>
  <body>
    <h3>์ˆซ์ž๋งž์ถ”๊ธฐ ๊ฒŒ์ž„</h3>
    <p>
      ์ด ๊ฒŒ์ž„์€ ์ปดํ“จํ„ฐ๊ฐ€ ์ƒ์„ฑํ•œ ์ˆซ์ž๋ฅผ ๋งž์ถ”๋Š” ๊ฒŒ์ž„์ž…๋‹ˆ๋‹ค.<br />
      ์ˆซ์ž๋Š” 1๋ถ€ํ„ฐ 100์‚ฌ์ด์— ์žˆ์Šต๋‹ˆ๋‹ค.
    </p>
    <div>
      <label for="num1">์ˆซ์ž</label>
      <input type="text" id="num1" name="num1" size="5" />
      <button type="button" onclick="guess()">ํ™•์ธ</button>
    </div>
    <div>
      <label for="count">์ถ”์ธกํšŸ์ˆ˜</label>
      <input type="text" id="count" name="conut" size="5" readonly />
    </div>
    <div>
      <label for="hint">ํžŒํŠธ</label>
      <input type="text" id="hint" name="hint" readonly />
    </div>
    <script>
      //random,nGuess ๋ณ€์ˆ˜๊ฐ€ ํ•จ์ˆ˜ ๋ฐ–์— ์„ ์–ธ๋œ ์ด์œ ๋Š” ํ•จ์ˆ˜ ์•ˆ์ชฝ์— ์„ ์–ธํ•  ๊ฒฝ์šฐ,
      //๋ฒ„ํŠผ์„ ๋ˆ„๋ฅผ ๋•Œ๋งˆ๋‹ค ์ˆซ์ž๋Š” ๋ณ€๊ฒฝ๋˜๊ณ , ์ถ”์ธกํšŸ์ˆ˜๋Š” 0์„ ๊ฐ€์ง€๊ธฐ ๋•Œ๋ฌธ

      //์ปดํ“จํ„ฐ๊ฐ€ 1๋ถ€ํ„ฐ 100์‚ฌ์ด์˜ ์ž„์˜์˜ ๊ฐ’์„ ๊ฐ€์ง€๋„๋ก ์„ค์ •
      const random = Math.floor(Math.random() * 100) + 1;

      //์ถ”์ธก ํšŸ์ˆ˜ ๋ณ€์ˆ˜ ์„ค์ •
      let nGuess = 0;

      function guess() {
      
        //ํ™•์ธ๋ฒ„ํŠผ์„ ํด๋ฆญํ•˜๋ฉด ์‚ฌ์šฉ์ž๊ฐ€ ์ž…๋ ฅํ•œ ์ˆซ์ž๋ฅผ ๊ฐ€์ ธ์˜ค๊ธฐ
        let num1 = document.querySelector("#num1").value;

        //์ถ”์ธกํšŸ์ˆ˜ ์ฆ๊ฐ€ ํ›„ ์ถ”์ธกํšŸ์ˆ˜ ๋ž€์— ๋ณด์—ฌ์ฃผ๊ธฐ
        nGuess++;
        document.querySelector("#count").value = nGuess;

        let result = "";
        
        //๊ฐ€์ ธ์˜จ ๊ฐ’๊ณผ ์ปดํ“จํ„ฐ์˜ ๊ฐ’์„ ๋น„๊ตํ•˜์—ฌ
        if (num1 < random) {
          //๊ฐ€์ ธ์˜จ ๊ฐ’์ด ์ปดํ“จํ„ฐ์˜ ๊ฐ’๋ณด๋‹ค ์ž‘๋‹ค๋ฉด ํžŒํŠธ๋ž€์˜ '์ถ”์ธก๊ฐ’์ด ์ž‘์Šต๋‹ˆ๋‹ค.'
          result = "์ถ”์ธก๊ฐ’์ด ์ž‘์Šต๋‹ˆ๋‹ค.";
        } else if (num1 > random) {
          //ํฌ๋‹ค๋ฉด ํžŒํŠธ๋ž€์˜ '์ถ”์ธก๊ฐ’์ด ํฝ๋‹ˆ๋‹ค.'
          result = "์ถ”์ธก๊ฐ’์ด ํฝ๋‹ˆ๋‹ค.";
        } else if (num1 == random) {
          //๊ฐ™๋‹ค๋ฉด ํžŒํŠธ๋ž€์˜ '์ •๋‹ต์ž…๋‹ˆ๋‹ค.'
          result = "์ •๋‹ต์ž…๋‹ˆ๋‹ค.";
        }
        // ๋ผ๋Š” ๋ฉ”์‹œ์ง€ ์ถœ๋ ฅ
        document.querySelector("#hint").value = result;
      }
    </script>
  </body>
</html>

 

 

 

- ๋ธŒ๋ผ์šฐ์ € ์ถœ๋ ฅ