블랙커피스터디 클래스로 정의 및 적당한 모듈 분리 ( lotte )

KHW·2021년 4월 28일
0

블랙커피스터디

목록 보기
6/9
post-custom-banner

기본 형태 틀


└── start
   ├── clickBuyBtn
   │   └──  displayNum
   └── clickResult
      ├────  checkBeforeNum
      │		└──  checkWinningNum
      │		└──  checkBonusNum  
      └────  displayResult
      		└──  fillResultLotte

index.js

import  {$,$All,app,lotteImage,appBuySection,inputLastWeekNumber,alertMessage,winStatics} from './utils/constant.js'
import {calculateEarning} from "./utils/function.js";

let winNumber = {
  threeSameNum : 0,
  fourSameNum : 0,
  fiveSameNum : 0,
  fiveBonusSameNum : 0,
  sixSameNum : 0
}

class Lotte{
  constructor(){
    this.start();
    this.isNumberOpen = true;
    this.winningNumberArr = [];

    this.myLotteNumberArr = [];
    this.bonusNumber = -Infinity;
    this.beforeNumberArr = [];
    this.beforeBonusNum = -Infinity;

    this.myLotteNumsFromDom  = [];
    this.correctNum = 0;
    this.compareBonus= false;
    this.randomValue = 0;
    this.earning = 0;
  }
  start(){
    document.body.innerHTML = app;
    $('#payBtn').addEventListener('click',()=>{
      const payment =  Number($('.pl-2').value);
      if(payment % 1000 !== 0){
        alert(alertMessage.numInTheThousands);
      }
      else{
        this.clickBuyBtn(payment);
      }
    })
  }

  clickBuyBtn(payment){
    $('.mt-5').insertAdjacentHTML('afterend',appBuySection(payment/1000));
    for(let i=0;i<payment/1000;i++) {
      for(let j=0;j<6;j++){
        this.randomValue = Math.floor(Math.random()*45);
        if(this.myLotteNumberArr.indexOf(this.randomValue) > -1)
          j--;
        else
          this.myLotteNumberArr.push(this.randomValue);
      }
      $('#lotteImageTitle').insertAdjacentHTML('afterend', lotteImage(...this.myLotteNumberArr));
      this.myLotteNumberArr = [];

    }
    $('#app').insertAdjacentHTML('beforeend',inputLastWeekNumber)
    $('#seeNum').addEventListener('click',()=>{this.displayNum(this.isNumberOpen)});
    $('.open-result-modal-button').addEventListener('click',()=>{this.clickResult()});

  }

  displayNum(isOpen){
    if(isOpen) {
      $All('#lotteImage').forEach((dom) => {
        dom.style.display = 'block';
      })
      $All('#lotteNumber').forEach((dom) => {
        dom.style.display = 'inline'
      })
      this.isNumberOpen=false;
    }
    else{
      $All('#lotteImage').forEach((dom) => {
        dom.style.display = 'inline';
      })
      $All('#lotteNumber').forEach((dom) => {
        dom.style.display = 'none'
      })
      this.isNumberOpen=true;
    }
  }

  clickResult(){
    this.checkBeforeNum();
    this.displayResult();
  }

  checkBeforeNum(){
    this.checkWinningNum();
    this.checkBonusNum();
  }

  checkWinningNum(){
    for(let i=0;i<$All('.winning-number').length;i++){
      if($All('.winning-number')[i].value < 1 || $All('.winning-number')[i].value > 45) {
        alert(alertMessage.winningOverNum);
        this.winningNumberArr = [];
        break;
      }
      else if(this.winningNumberArr.indexOf($All('.winning-number')[i].value) > -1){
        alert(alertMessage.duplicationNum);
        this.winningNumberArr = [];
        break;
      }
      else{
        this.winningNumberArr.push($All('.winning-number')[i].value)
      }
    }
  }

  checkBonusNum(){
    if($('.bonus-number').value < 1 || $('.bonus-number').value>45) {
      alert(alertMessage.bonusOverNum);
      this.winningNumberArr = [];
    }
    else if(this.winningNumberArr.indexOf($('.bonus-number').value) > -1){
      alert(alertMessage.duplicationNum);
      this.winningNumberArr = [];
    }
    else {
      this.bonusNumber = ($('.bonus-number').value);
    }
  }

  displayResult(){
    if(this.winningNumberArr.length === 6 && this.bonusNumber !== -Infinity) {
      this.fillResultLotte();
      $('.modal').classList.add('open');
      $('.modal-close').addEventListener('click', () => {
        $('.modal').classList.remove('open');
        this.winningNumberArr = [];
        this.beforeNumberArr = [];
        for(let val in winNumber) {
          winNumber[val] = 0;
        }

        $('.modal').remove();
      })
    }
  }

  fillResultLotte(){
    $All('.winning-number').forEach(dom=>this.beforeNumberArr.push(dom.value));

    this.beforeBonusNum = $('.bonus-number').value;

    $All('#lotteNumber').forEach((Dom)=>{
      this.myLotteNumsFromDom = Dom.innerHTML.split(',');
      this.myLotteNumsFromDom.forEach((val)=>{
        if(this.beforeNumberArr.indexOf(val) > -1){
          this.correctNum++;
        }
      })
      if(this.myLotteNumsFromDom.indexOf(this.beforeBonusNum) > -1){
        this.compareBonus = true;
      }
      switch(this.correctNum){
        case 3 : winNumber.threeSameNum++;
                break;
        case 4 : winNumber.fourSameNum++;
          break;
        case 5 : winNumber.fiveSameNum++;
          break;
        case 6 : winNumber.sixSameNum++;
          break;
      }
      if(this.correctNum ===5 && this.compareBonus === true){
        winNumber.fiveSameNum--;
        winNumber.fiveBonusSameNum++;
      }
      this.compareBonus = false;
      this.correctNum = 0;
    });

    this.earning = calculateEarning(winNumber);
    $('#app').insertAdjacentHTML('beforeend',winStatics(winNumber,this.earning))
  }
}

new Lotte();

constant.js

const $ = (selector) => document.querySelector(selector)
const $All = (selector) => document.querySelectorAll(selector)

const app = `<div id="app" class="p-3">
      <div class="d-flex justify-center mt-5">
        <div class="w-100">
          <h1 class="text-center">🎱 행운의 로또</h1>
           <form class="mt-5">
            <label class="mb-2 d-inline-block"
              >구입할 금액을 입력해주세요.
            </label>
            <div class="d-flex">
              <input
                type="number"
                class="w-100 mr-2 pl-2"
                placeholder="구입 금액"
              />
              <button type="button" id="payBtn" class="btn btn-cyan">확인</button>
            </div>
          </form>
        </div>
      </div>
</div>`


const appBuySection = (num)=>`
          <section class="mt-9">
            <div class="d-flex">
              <label class="flex-auto my-0">총 ${num}개를 구매하였습니다.</label>
              <div class="flex-auto d-flex justify-end pr-1">
                <label class="switch">
                  <input type="checkbox" class="lotto-numbers-toggle-button" />
                  <span class="text-base font-normal" id="seeNum">번호보기</span>
                </label>
              </div>
            </div>
            <div class="d-flex flex-wrap" id="lotteImageTitle">
            </div>
          </section>`

const lotteImage = (n1,n2,n3,n4,n5,n6)=> `<span class="mx-1 text-4xl" id="lotteImage">🎟️ <span id="lotteNumber" style="display:none">${n1},${n2},${n3},${n4},${n5},${n6}</span> </span>`

const inputLastWeekNumber = `<form class="mt-9">
            <label class="flex-auto d-inline-block mb-3"
              >지난 주 당첨번호 6개와 보너스 넘버 1개를 입력해주세요.</label
            >
            <div class="d-flex">
              <div>
                <h4 class="mt-0 mb-3 text-center">당첨 번호</h4>
                <div>
                  <input
                    type="number"
                    class="winning-number mx-1 text-center"
                    value="1"
                  />
                  <input
                    type="number"
                    class="winning-number mx-1 text-center"
                    value="2"
                  />
                  <input
                    type="number"
                    class="winning-number mx-1 text-center"
                    value="3"
                  />
                  <input
                    type="number"
                    class="winning-number mx-1 text-center"
                    value="4"
                  />
                  <input
                    type="number"
                    class="winning-number mx-1 text-center"
                    value="5"
                  />
                  <input
                    type="number"
                    class="winning-number mx-1 text-center"
                    value="6"
                  />
                </div>
              </div>
              <div class="bonus-number-container flex-grow">
                <h4 class="mt-0 mb-3 text-center">보너스 번호</h4>
                <div class="d-flex justify-center">
                  <input type="number" class="bonus-number text-center"                   value="7"/>
                </div>
              </div>
            </div>
            <button
              type="button"
              class="open-result-modal-button mt-5 btn btn-cyan w-100"
            >
              결과 확인하기
            </button>
          </form>`

const winStatics =(winNumber,earning)=> ` <div class="modal">
        <div class="modal-inner p-10">
          <div class="modal-close">
            <svg viewbox="0 0 40 40">
              <path class="close-x" d="M 10,10 L 30,30 M 30,10 L 10,30" />
            </svg>
          </div>

          <h2 class="text-center">🏆 당첨 통계 🏆</h2>
          <div class="d-flex justify-center">
            <table class="result-table border-collapse border border-black">
              <thead>
                <tr class="text-center">
                  <th class="p-3">일치 갯수</th>
                  <th class="p-3">당첨금</th>
                  <th class="p-3">당첨 갯수</th>
                </tr>
              </thead>
              <tbody>
                <tr class="text-center">
                  <td class="p-3">3개</td>
                  <td class="p-3">5,000</td>
                  <td class="p-3">${winNumber.threeSameNum}개</td>
                </tr>
                <tr class="text-center">
                  <td class="p-3">4개</td>
                  <td class="p-3">50,000</td>
                  <td class="p-3">${winNumber.fourSameNum}개</td>
                </tr>
                <tr class="text-center">
                  <td class="p-3">5개</td>
                  <td class="p-3">1,500,000</td>
                  <td class="p-3">${winNumber.fiveSameNum}개</td>
                </tr>
                <tr class="text-center">
                  <td class="p-3">5개 + 보너스볼</td>
                  <td class="p-3">30,000,000</td>
                  <td class="p-3">${winNumber.fiveBonusSameNum}개</td>
                </tr>
                <tr class="text-center">
                  <td class="p-3">6개</td>
                  <td class="p-3">2,000,000,000</td>
                  <td class="p-3">${winNumber.sixSameNum}개</td>
                </tr>
              </tbody>
            </table>
          </div>
          <p class="text-center font-bold">당신의 총 수익률은 ${earning}%입니다.</p>
          <div class="d-flex justify-center mt-5">
            <button type="button" class="btn btn-cyan">다시 시작하기</button>
          </div>
        </div>
      </div>`

const alertMessage ={
  winningOverNum : '당첨번호 값은 1이상 45이하이어야한다.',
  bonusOverNum : '보너스번호 값은 1이상 45이하이어야한다.',
  duplicationNum : '중복된 숫자는 불가능하다.',
  numInTheThousands : '천의자리만 가능하다'
}


export {$,$All,app,lotteImage,appBuySection,inputLastWeekNumber,alertMessage,winStatics}

function.js

import {$} from './constant.js'


const calculateEarning = (winNumber)=>
  Math.round((winNumber.threeSameNum * 5000 + winNumber.fourSameNum * 50000 + winNumber.fiveSameNum * 1500000 + winNumber.fiveBonusSameNum * 30000000 + winNumber.sixSameNum * 2000000000 - Number($('.pl-2').value)) / Number($('.pl-2').value) *1000);

export {calculateEarning};
profile
나의 하루를 가능한 기억하고 즐기고 후회하지말자
post-custom-banner

0개의 댓글