[js]로또 추첨기 만들기

babypig·2023년 1월 8일
1

javascript

목록 보기
4/12
post-thumbnail

<body>
  <div id="result">
    추첨 결과는 ?
  </div>
  <div id="bonus">
    보너스 번호는 ?
  </div>
  <script>
    //while 버전
    const candidate = Array(45).fill().map((item, i) => i + 1);
    const shuffle = [];
    while(candidate.length > 0) {
      const random = Math.floor(Math.random() * candidate.length);
      const spliceArray = candidate.splice(random, 1);
      const value = spliceArray[0];
      shuffle.push(value);
    }
    console.log(shuffle)

    //for문 버전
    const candidate2 = Array(45).fill().map((item, i) => i + 1);
    const shuffle2 = [];
    for(let i = candidate2.length; i > 0; i--) {
      const random = Math.floor(Math.random() * i);
      const spliceArray = candidate2.splice(random, 1);
      const value = spliceArray[0];
      shuffle2.push(value);
    }
    console.log(shuffle2);

    const winBalls = shuffle.slice(0, 6).sort((a,b) => a- b);
    const bonus = shuffle[6];
    console.log(winBalls, bonus);
    const $result = document.querySelector('#result');
    const $bonus = document.querySelector('#bonus');

    const colorize = (num, $tag) => {
      if(num < 10) {
        $tag.style.backgroundColor = 'red'
        $tag.style.color = 'white'
      } else if(num < 20) {
        $tag.style.backgroundColor = 'orange'
      } else if(num < 30) {
        $tag.style.backgroundColor = 'yellow'
      } else if(num < 40) {
        $tag.style.backgroundColor = 'blue'
        $tag.style.color = 'white'
      } else {
        $tag.style.backgroundColor = 'green'
        $tag.style.color = 'white'
      }
    }

    const showBall = (num, $target) => {
      const $ball = document.createElement('div');
      $ball.className = 'ball';
      colorize(num, $ball);
      $ball.textContent = num;
      $target.append($ball);
    }

    for(let i = 0; i < winBalls.length; i++) {
      setTimeout(() => {
        showBall(winBalls[i], $result)
      }, (i + 1) * 1000);
    }

    setTimeout(() => {
      showBall(bonus, $bonus)
    },7000 );


  </script>
</body>
profile
babypig

0개의 댓글