로또 (html / js)

yun·2023년 3월 9일
0

로또 번호를 생성해 보겠습니다.

절차

프로그래밍 사고

시작
-> 45개의 번호를 생성한다
-> 6개의 번호를 랜덤하게 뽑아준다
-> 보너스 번호를 랜덤하게 뽑아준다
-> 뽑은 번호를 정렬한다(6개의 번호만)
-> 화면에 나타낸다.


코드

  • 45개의 번호를 생성한다
const lottoNum = Array(45).fill().map((el,i)=>i+1);
  • 6개의 번호를 랜덤하게 뽑아준다

#.번호뽑기

  const suffle = []
  let selectNum=Math.floor((Math.random()*lottoNum.length+1));
  const numSplice=lottoNum.splice(selectNum,1);
  suffle.push(numSplice[0]);

#.6개 뽑을 때 까지 반복 + 보너스

for (let i = 0; i <= 6; i++) {
  let selectNum = Math.floor((Math.random() * lottoNum.length + 1));
  const numSplice = lottoNum.splice(selectNum, 1);
  suffle.push(numSplice[0]);
}
  • 뽑은 번호를 정렬한다(6개의 번호만)
let bonus = suffle[6]
const selectLotto = suffle.slice(0,6).sort((a,b)=>a-b);
  • 화면에 나타낸다.
$result = document.querySelector('#result')
$bonus = document.querySelector('#bonus')
const $lottoBall = document.createElement('div')
$lottoBall.className = 'ball';
$lottoBall.textContent = selectLotto[0];
$result.appendChild($lottoBall);

더 나아가기

#1. 반복되는 코드 줄이기

const drawBall = (num, targetTag) => {
  const $lottoBall = document.createElement('div')
  $lottoBall.className = 'ball';
  $lottoBall.textContent = num;
  targetTag.appendChild($lottoBall);
}

#2. setTimeout을 사용해 간격을 둬서 띄우기

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

#3. 로또 번호에 색깔 입히기

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

화면

소스코드(github)
링크텍스트

출처 "ZeroCho TV"
링크텍스트

profile
날아오르고 싶은 애벌레입니다.

0개의 댓글

관련 채용 정보