자바스크립트 정리(4)

조이연·2023년 1월 5일
0

JSP

목록 보기
19/19
  • Math.floor(): Math.floor()는 어떤 수보다 크지 않은 최대의 정수를 반환합니다.

<Math 내장객체: 랜덤>

 <script>
        //  Math.random()을 이용해 0~100사이의 임의의 실수를 출력하시오.
        Math.random()*100;
        //0~100사이의 임의의 정수
        Math.floor(Math.random()*101);

        //Math.random()을 이용해 "홀 입니다. "또는 "짝입니다"를 출력하는 함수
        const func=()=>{
            const num=Math.floor(Math.random()*2);
            if(num%2==0)
            {
                console.log('짝입니다.');
            }else{
                console.log('홀입니다.');
            }
        }
        for(let i=0;i<10;i++)
        {
            func();
        }
        
    </script>

<홀짝게임>
[1]

<!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" />
    <script src="https://sports.news.naver.com/wfootball/index"></script>
    <title>홀짝게임</title>
  </head>
  <body>
    <!-- <input type="text" id="user">
    값이 정해져 있는경우(홀,짝) select를 사용한다. inputtype 대신-->
    <select id="user">
      <option selected disabled>
        홀,짝을 선택하고 승부 버튼을 클릭하세요.
      </option>
      <option value="1"></option>
      <option value="0"></option>
      <!--값을 써서 넘기는 경우 가급적이면 숫자로 넘긴다(value 사용)-->
    </select>
    <button id="panjung" disabled>승부</button>
    <!--disabled은 <input>요소가 비활성화됨을 명시(클릭이 안됨)-->
    <script>
      // 1. 사용자가 홀짝을 선택하면 버튼을 활성화하자
      $("#user").on("change", function () {
        //속성 중 selected, disabled, readonly, checked 속성은 값이 아니라 속성이 있으면 적용된다
        //즉 disabled를 취소하면 disabled = 'false'가 아니라 disabled를 없애야 한다
        //jQuery에서 위 네 속성 전용 메소드가 prop
        $("#pangjung").prop("disabled", false);
      });
    </script>
  </body>
</html>
  • 값이 정해져 있는경우(홀,짝) select를 사용한다. (고정멘트)
  • 값을 써서 넘기는 경우 가급적이면 숫자로 넘긴다(value 사용)
  • 속성 중 selected, disabled, readonly, checked 속성은 값이 아니라 속성이 있으면 적용된다
    즉 disabled를 취소하면 disabled = 'false'가 아니라 disabled를 없애야 한다

[2]

<!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>홀짝 게임2</title>
    <style>
      #hol,
      #jjack {
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
        color: white;
        font-weight: bold;
        display: inline-block;
        margin-right: 20px;
      }
      #hol {
        background-color: blueviolet;
      }
      #jjack {
        background-color: hotpink;
      }
      #game {
        width: 300px;
        margin: 0 auto;
      }
    </style>
  </head>
  <body>
    <div id="game">
      <div id="hol"></div>
      <div id="jjack"></div>
      <div id="result">
        <p>버튼을 시작하면 게임이 시작됩니다.</p>
      </div>
    </div>
  </body>
</html>
<script>
      // html이 모두 로딩되면 -> onload
      window.onload = function () {
        console.log("onload 이벤트 1");
      };
      window.onload = function () {
        console.log("onload 이벤트 2");
      };
      // jquery는 ready 이벤트
      $(document).ready(function () {
        console.log("ready 이벤트 1");
      });
      $(function () {
        console.log("ready 이벤트 2");
      });
    </script>
  • window.onload(): 바스크립트가 문서가 준비된 상황 이후에 발동하도록만 한다면 문서 앞에 선언해도 상관없게 되는데 이것이 바로 window.onload입니다.
  • html이 모두 로딩되면 -> onload
  • jquery는 ready 이벤트

[3]

<!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" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <title>홀짝 게임2 - -입력을 확인하자</title>
    <style>
      #hol,
      #jjack {
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
        color: white;
        font-weight: bold;
        display: inline-block;
        margin-right: 20px;
      }
      #hol {
        background-color: blueviolet;
      }
      #jjack {
        background-color: hotpink;
      }
      #game {
        width: 300px;
        margin: 0 auto;
      }
    </style>
    <script>
      window.onload = function () {
        //홀 또는 짝을 선택하면 콘솔에 선택했어요 라고 출력하시오
        $("#hol, #jjack").on("click", function (e) {
          //const choice = e.target.innerHTML;
          const choice = $(e.target).text();

          //사용자와 소통하는 함수 : alert, prompt(입력), confirm(선택)
          const result = confirm(`${choice}를 선택하셨습니다?`);
          //console.log(result);
          if (result == false) return;

          //랜덤한 0 또는 1 발생
          const computer = Math.floor(Math.random() * 2);
          const user = choice === "홀" ? 1 : 0;

          console.log(`computer: ${computer}, user : ${user}`);
        });

        // 홀을 선택하면 콘솔에 "홀","짝"을 선택하면 콘솔에 "짝"
        $("#hol").on("click", function () {
          console.log("홀");
        });
        $("#jjack").on("click", function () {
          console.log("짝");
        });
      };
    </script>
  </head>
  <body>
    <div id="game">
      <div id="hol"></div>
      <div id="jjack"></div>
      <div id="result">
        <p>버튼을 시작하면 게임이 시작됩니다.</p>
      </div>
    </div>
  </body>
</html>
  • 사용자와 소통하는 함수 : alert, prompt(입력), confirm(선택)
    [4]
<!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" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <title>홀짝 게임2 - -입력을 확인하자</title>
    <style>
      #hol,
      #jjack {
        width: 100px;
        height: 100px;
        line-height: 100px;
        text-align: center;
        color: white;
        font-weight: bold;
        display: inline-block;
        margin-right: 20px;
      }
      #hol {
        background-color: blueviolet;
      }
      #jjack {
        background-color: hotpink;
      }
      #game {
        width: 300px;
        margin: 0 auto;
      }
    </style>
    <script>
       let win =0,lose=0,count=0;  //변수 생성
      window.onload = function () {
        //홀 또는 짝을 선택하면 콘솔에 선택했어요 라고 출력하시오
        $("#hol, #jjack").on("click", function (e) {
            //10판했으면 진행 불가
            if(count<=0)
            {
                alert('게임이 종료되었습니다.');
                return;
                
            }
            //사용자가 취소 누르면 진행 X
          //const choice = e.target.innerHTML;
          const choice = $(e.target).text();

          //사용자와 소통하는 함수 : alert, prompt(입력), confirm(선택)
          const result = confirm(`${choice}를 선택하셨습니다?`);
          //console.log(result);
          if (result == false) return;
            count--;
          //랜덤한 0 또는 1 발생
          const computer = Math.floor(Math.random() * 2);
          const user = choice === "홀" ? 1 : 0;

          $('#result').empty();
          if (computer === user)
         { win++;
           $("#result").append(`<p>당신의 승리.${win}승 ${lose}패</P>`);}
          else {
            lose++;
            $("#result").append(`<p>당신의 패배. ${win}승 ${lose}패<</p>`);
          //console.log(`computer: ${computer}, user : ${user}`);
        }

        //panel에 게임 정보 출력
        count--;
        $('#panel').empty();
        if(count>0){
            $('#panel').append(`<p>게임이 ${count}판 남았습니다.`);
        }else{
         
            $('#panel').append(`<p>게임이 종료되었습니다.</p>`);
        }
    });
};

<숫자 맞추기 게임>

<!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" />
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
   <title>Document</title>
   <script>
     //회수를 3부터 감소 -> 0회가 되면 남은 찬스 : 0회
     // up, Down을 표시하다가 맞추면 "성공" , "실패"
     //chance
     //3   초기값
     //2   성공 or 실패
     //1   성공 or 실패
     //0   실패???

     "use strict";

     let chance, randomNum, isSuccess;

     //다시하기 누를때
     function init() {
       chance = 3;
       randomNum = Math.floor(Math.random() * 10) + 1; //0~9를 나오게 한후 1을 더해서 10이 나오게 함
       isSuccess = false;
       console.log(randomNum);
     }
     //GO 눌렀을때
     function play() {
       chance--;
       console.log(`chance: ${chance}`);
       let user = parseInt($("#user").val());

       if (user > randomNum) $("#result").text("DOWN!!");
       else if (user < randomNum) $("#result").text("UP!!");
       else {
         $("#result").text("정답입니다.");
         isSuccess = true;
       }

       //맞추기에 실패했다면

       //chance가 남았다면 찬스 출력
       if (chance <= 0 && isSuccess === false) {
         //실패
         $("#result").text(
           `숫자 맞추기에 실패했습니다. 정답은 ${randomNum}입니다`
         );
       }
       if (chance >= 0) {
         // 기회가 chance번 남았습니다
         $("#chance").text(`남은 찬스 : ${chance}`);
       }
     }

     $(document).ready(function () {
       init();
       $("#play").on("click", play);
       $("#init").on("init", init);
     });
   </script>
 </head>
 <body>
   <div id="app">
     <h1>1~10 숫자맞추기 게임</h1>
     <div id="result">결과가 나온다</div>
     <div id="chance">남은 찬스 : 3회</div>
     <input type="text" id="user" maxlength="2" />
     <button id="play">GO!!!</button>
     <button id="init">다시하기</button>
   </div>
 </body>
</html>
profile
안녕하세요

0개의 댓글