/* * 파일명: main.js * 위치: /js/main.js * 기능: 로또 번호 생성기 프론트엔드 로직 * 작성자: 웹 개발자 * 작성일: 2024-02-08 */ // 디버깅을 위한 로깅 함수 const logger = { log: (message, data) => { console.log(`[Lotto] ${message}`, data || ''); }, error: (message, error) => { console.error(`[Lotto Error] ${message}`, error); } }; // 생성된 번호 히스토리 (최대 10개) let numberHistory = []; // 이전 당첨 번호 정보를 저장할 변수 let previousWinningNumbers = []; // API 요청 함수들 const api = { // 번호 생성 API 호출 async generateNumbers() { const formData = new FormData(); formData.append('action', 'generate'); formData.append('count', 1); try { logger.log('번호 생성 중...'); const response = await fetch('api/lotto.php', { method: 'POST', body: formData }); const data = await response.json(); logger.log('API 응답:', data); if (data.success) { return data.numbers[0]; // 단일 게임만 반환 } else { throw new Error(data.message || '번호 생성 실패'); } } catch (error) { logger.error('번호 생성 실패', error); alert('번호 생성 중 오류가 발생했습니다.'); return null; } }, // api 객체 내에 히스토리 로드 함수 추가 async loadLottoHistory() { try { logger.log('로또 히스토리 로드 중...'); const response = await fetch('data/lotto_history.json'); const data = await response.json(); // rounds 배열만 반환 return data.rounds; } catch (error) { logger.error('로또 히스토리 로드 실패', error); return []; } }, // 현재 회차 정보 조회 API 호출 async getCurrentLottoInfo() { const formData = new FormData(); formData.append('action', 'current_info'); try { logger.log('현재 회차 정보 조회 중...'); const response = await fetch('api/lotto.php', { method: 'POST', body: formData }); const data = await response.json(); logger.log('현재 회차 정보:', data); if (data.success) { return data.info; } else { throw new Error(data.message || '정보 조회 실패'); } } catch (error) { logger.error('현재 회차 정보 조회 실패', error); alert('당첨 정보 조회 중 오류가 발생했습니다.'); return null; } }, // 특정 회차 정보 조회 API 호출 async getRoundInfo(round) { const formData = new FormData(); formData.append('action', 'round_info'); formData.append('round', round); try { logger.log(`${round}회차 정보 조회 중...`); const response = await fetch('api/lotto.php', { method: 'POST', body: formData }); const data = await response.json(); logger.log('회차 정보:', data); if (data.success) { return data.info; } else { throw new Error(data.message || '회차 정보 조회 실패'); } } catch (error) { logger.error('회차 정보 조회 실패', error); alert('회차 정보 조회 중 오류가 발생했습니다.'); return null; } } }; // UI 업데이트 함수들 const ui = { // 생성된 번호 표시 displayNumbers(numbers, containerId) { const container = document.getElementById(containerId); if (!container) return; // 매칭 라운드 찾기 const matchingRound = this.findMatchingRound(numbers); logger.log('현재 번호:', numbers); logger.log('매칭 라운드:', matchingRound); let html = '
'; // 생성된 번호 표시 html += '
'; html += numbers.map(num => `
${num}
`).join(''); html += '
'; // 매칭된 번호가 있는 경우 if (matchingRound) { html += '
'; html += '
'; html += matchingRound.matchingNumbers.map(num => { const rangeStart = Math.floor((num-1)/10)*10 + 1; const rangeEnd = Math.min(rangeStart + 9, 45); return `
${num}
`; }).join(''); html += '
'; html += `
제 ${matchingRound.round}회와
${matchingRound.matchCount}개 일치
자세히 보기 ▶
`; } html += '
'; container.innerHTML = html; // 히스토리에 추가 this.addToHistory(numbers, matchingRound); }, // 이전 당첨 번호와 비교 findMatchingRound(numbers) { // 로또 히스토리가 없으면 null 반환 if (!lottoHistory || lottoHistory.length === 0) { logger.log('로또 히스토리 데이터가 없음'); return null; } let bestMatch = null; let maxMatches = 3; // 최소 3개 이상 일치할 때만 표시 // 모든 히스토리와 비교 for (let round of lottoHistory) { // numbers 배열의 각 숫자가 round.numbers 배열에 있는지 확인 const matchingNums = numbers.filter(num => round.numbers.includes(Number(num)) // 숫자로 변환하여 비교 ); if (matchingNums.length >= maxMatches) { if (!bestMatch || matchingNums.length > bestMatch.matchCount) { bestMatch = { round: round.round, matchCount: matchingNums.length, winningNumbers: round.numbers, matchingNumbers: matchingNums // 일치하는 번호들 저장 }; } } } logger.log('매칭 결과:', bestMatch); return bestMatch; }, // 히스토리에 번호 추가 addToHistory(numbers, matchingRound) { numberHistory.unshift({ numbers, matchingRound }); if (numberHistory.length > 10) { numberHistory.pop(); } // 히스토리 표시 업데이트 const historyContainer = document.getElementById('numberHistory'); if (historyContainer) { historyContainer.innerHTML = numberHistory.map((item, index) => `
${index + 1}번째 생성 ${item.matchingRound ? ` ` : ''}
${item.numbers.map(num => `
${num}
`).join('')}
`).join(''); } }, // 현재 회차 정보 표시 displayCurrentInfo(info) { const container = document.getElementById('currentLottoInfo'); if (!container) { logger.error('현재 회차 정보 컨테이너를 찾을 수 없음'); return; } try { container.innerHTML = `

제 ${info.round}회 (${info.drawDate} 추첨)

${info.winningNumbers.map(num => `
${num}
`).join('')} +
${info.bonusNumber}

총 판매금액: ${info.totalPrize}

1등 당첨자 수: ${info.firstPrizeCount}명

1등 당첨금액: ${info.firstPrizeAmount}

`; } catch (error) { logger.error('현재 회차 정보 표시 실패', error); container.innerHTML = '
당첨 정보를 표시하는 중 오류가 발생했습니다.
'; } }, // 로딩 표시 displayLoading(containerId) { const container = document.getElementById(containerId); if (container) { container.innerHTML = `
Loading...
`; } }, // 에러 메시지 표시 displayError(containerId, message) { const container = document.getElementById(containerId); if (container) { container.innerHTML = ` `; } } }; // 회차 정보 모달 표시 async function showRoundInfo(round) { // 해당 회차 정보 찾기 const roundInfo = lottoHistory.find(info => info.round === round); if (!roundInfo) { logger.error('회차 정보를 찾을 수 없음:', round); alert('회차 정보를 찾을 수 없습니다.'); return; } logger.log('회차 정보 표시:', roundInfo); const modalHtml = ` `; // 기존 모달 제거 const existingModal = document.getElementById('roundInfoModal'); if (existingModal) { existingModal.remove(); } // 새 모달 추가 및 표시 document.body.insertAdjacentHTML('beforeend', modalHtml); const modal = new bootstrap.Modal(document.getElementById('roundInfoModal')); modal.show(); } // 번호 생성 이벤트 핸들러 async function generateNumbers() { ui.displayLoading('lottoNumbers'); const numbers = await api.generateNumbers(); if (numbers) { ui.displayNumbers(numbers, 'lottoNumbers'); } else { ui.displayError('lottoNumbers', '번호 생성에 실패했습니다.'); } } // 페이지 초기화 async function initializePage() { ui.displayLoading('currentLottoInfo'); // 로또 히스토리 로드 lottoHistory = await api.loadLottoHistory(); logger.log('로또 히스토리 로드됨', lottoHistory); const currentInfo = await api.getCurrentLottoInfo(); if (currentInfo) { ui.displayCurrentInfo(currentInfo); // 이전 당첨 번호 저장 previousWinningNumbers.push({ round: currentInfo.round, winningNumbers: currentInfo.winningNumbers }); } else { ui.displayError('currentLottoInfo', '당첨 정보를 불러오는데 실패했습니다.'); } } // 페이지 로드 시 초기화 document.addEventListener('DOMContentLoaded', initializePage);