• 분류 전체보기 (512)
    • 개발남노씨(Coding Test) (6)
    • 고농축 백엔드 (17)
    • 재귀함수 DFS 총정리 (1)
    • 프론트엔드 날개달기:Vuejs.React (1)
    • 훈훈한 javascript (5)
    • 렛츠기릿 자바스크립트 (18)
    • 나도코딩 (1)
      • 웹 스크래핑 (1)
    • 프로그래머스(자바스크립트) (41)
      • LV.0(자바스크립트) (41)
    • 프로그래머스(자바) (121)
      • LV.0(자바) (56)
      • LV.1(자바) (41)
      • LV.2(자바) (23)
    • 프로그래머스(파이썬) (127)
      • LV.0(파이썬) (46)
      • LV.1(파이썬) (51)
      • LV.2(파이썬) (30)
    • 임시저장소 (31)
    • 프로젝트 (0)
    • 자바 알고리즘 (13)
      • 알고리즘 직빵 자바 문법 (10)
      • String(문자열) (3)
    • 파이썬 알고리즘 (93)
      • 알고리즘 직빵 파이썬 문법 (20)
      • 알고리즘 백준 (2)
      • 파이썬 알고리즘(사고력기르기) (6)
      • 파이썬 탐색 & 시물레이션 (8)
      • 이분탐색 & 그리디 알고리즘 (10)
      • 스택, 큐, 해쉬, 힙 (10)
      • 완전탐색과 DFS기초 (12)
      • DFS, BFS 활용 (19)
      • 동적계획법 (6)
    • 자바 (27)
      • Java TPC(생각하고, 표현하고, 코딩하고) (17)
      • Java (중요하고, 이해 안 되고, 어려운) (10)
    • 스프링 (5)
      • 스프링 MVC 패턴 2편 (5)
hELLO · Designed By 정상우.
@@#@@

기록용 블로그

렛츠기릿 자바스크립트

로또 등수 매기기 (self)

2023. 1. 16. 20:57

 

HTML파일

<!DOCTYPE html>
<html lang="ko">
  <head>
    <meta charset="utf-8" />
    <title>로또추첨기</title>
    <link rel="stylesheet" href="./style.css" />
  </head>
  <body>
    <script type="text/javascript" src="script.js" defer></script>
    <div id="result">추첨 결과는?</div>
    <br />
    <div id="bonus">보너스:</div>
    <br />

    <h2>띄어쓰기단위로 숫자 7개를 입력해주세요</h2>

    <input type="text" id="input" />
    <button id="startBtn">입력</button>
    <div id="logs"></div>
  </body>
</html>

 

style.css파일

.ball {
  display: inline-block;
  border: 1px solid black;
  border-radius: 20px;
  width: 40px;
  height: 40px;
  line-height: 40px;
  font-size: 20px;
  text-align: center;
  margin-right: 20px;
}

 

 

script파일

const $startBtn = document.querySelector("#startBtn");
$startBtn.addEventListener("click", () => {
  start();
});

const start = function () {
  const $logs = document.querySelector("#logs");
  let inputDigit = document.querySelector("#input").value;
  const inputArr = inputDigit.split(" ");
  console.log(inputArr);

  const Arr1 = [1, 2, 3, 4];
  const Arr2 = [5, 6, 7, 8];

  console.log(Arr1.includes(Arr2), "설렁탕");

  //1단계 입력값의 유효성체크
  const checkInput = function (Arr) {
    if (inputArr.length !== 7) {
      alert("7자리의 숫자를 입력해야 합니다.");
      return false;
    }
    if (inputArr.includes("0")) {
      alert("숫자 0은 포함될 수 없습니다.");
      return false;
    }
    if (new Set(inputArr).size !== 7) {
      alert("중복된 숫자는 입력할 수 없습니다.");
      return false;
    }
    return true;
  };

  if (!checkInput(inputArr)) {
    //if문 부정
    return; //return문 추가
  }

  //2단계 입력값이 문제가 없는 경우 로또 실행

  const candidate = Array(45)
    .fill()
    .map((v, i) => i + 1);
  const shuffle = [];
  while (candidate.length > 0) {
    console.log(candidate.length);
    const random = Math.floor(Math.random() * candidate.length); // 무작위 인덱스(0~44) 뽑기
    const spliceArray = candidate.splice(random, 1); // splice()의 리턴타입은 배열이다.
    const value = spliceArray[0]; // 배열에 들어 있는 값을 꺼내어
    shuffle.push(value); // shuffle 배열에 넣기
  }

  const winBalls = shuffle.slice(0, 6).sort((a, b) => a - b);
  const bonus = shuffle[6];

  const $result = document.querySelector("#result");

  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";
    }
  }

  const drawBall = (number, $parent) => {
    const $ball = document.createElement("div");
    $ball.className = "ball";
    colorize(number, $ball);
    $ball.textContent = number;
    $parent.appendChild($ball);
  };

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

  const $bonus = document.querySelector("#bonus");
  setTimeout(() => {
    drawBall(bonus, $bonus);
  }, 7000);

  //3단계 몇 개를 맞추었는지 출력
  let hit = 0;
  let extra_hit = false;
  for (let i = 0; i < winBalls.length - 1; i++) {
    const index = inputArr.includes(winBalls[i]);
    if (index > -1) {
      hit += 1;
    }
  }
  if (inputArr.includes(winBalls[winBalls.length - 1])) {
    extra_hit = true;
  }

  const rank = function (hit) {
    if (hit === 6) {
      rank = 1;
      $logs.append(`${hit}개 맞추셨으므로 ${rank}입니다.`);
    }
    if (hit === 5 && extra_hit) {
      rank = 2;
      $logs.append(
        `${hit}개 맞추셨고 보너스 숫자도 맞추셨으므로 ${rank}입니다.`
      );
    }

    if (hit === 5) {
      rank = 3;
      $logs.append(`${hit}개 맞추셨으므로 ${rank}입니다.`);
    }

    if (hit === 4) {
      rank = 4;
      $logs.append(`${hit}개 맞추셨으므로 ${rank}입니다.`);
    }

    if (hit === 3) {
      rank = 5;
      $logs.append(`${hit}개 맞추셨으므로 ${rank}입니다.`);
    } else {
      $logs.append(`${hit}개 이하로 맞추셨므로 꽝 입니다.`);
    }
    console.log($logs.textContent);
    rank(hit);
  };
};

 

 

 

 

 

 

 

 

 

 

저작자표시 비영리 변경금지 (새창열림)

'렛츠기릿 자바스크립트' 카테고리의 다른 글

반응 속도 체크  (0) 2023.01.17
가위 바위 보 (3선승제)  (0) 2023.01.16
로또 만들기 self (공에 색깔 넣기)  (0) 2023.01.15
로또 만들기 - splice( )★★+태그요소만들기+className추가 +sort()  (0) 2023.01.15
forEach, map, fill 알아보기  (0) 2023.01.14
    '렛츠기릿 자바스크립트' 카테고리의 다른 글
    • 반응 속도 체크
    • 가위 바위 보 (3선승제)
    • 로또 만들기 self (공에 색깔 넣기)
    • 로또 만들기 - splice( )★★+태그요소만들기+className추가 +sort()
    @@#@@
    @@#@@
    자바, 스프링, 알고리즘, 깃허브, 파이썬

    티스토리툴바