<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>퀴즈 게임</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            background-color: #f4f4f4;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            text-align: center;
            width: 100%;
            max-width: 400px;
        }
        .hidden {
            display: none;
        }
        button {
            padding: 10px 20px;
            margin-top: 10px;
            border: none;
            border-radius: 5px;
            background-color: #007BFF;
            color: white;
            cursor: pointer;
        }
        button:disabled {
            background-color: #aaa;
        }
        input, select {
            padding: 10px;
            margin: 10px 0;
            width: 100%;
            box-sizing: border-box;
        }
        .popup {
            display: none;
            position: fixed;
            left: 50%;
            top: 50%;
            transform: translate(-50%, -50%);
            padding: 20px;
            background: white;
            border: 1px solid #ccc;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
            z-index: 1000;
        }
        .popup button {
            margin-top: 10px;
        }
        .popup-background {
            display: none;
            position: fixed;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            z-index: 500;
        }
    </style>
</head>
<body>
    <div class="popup-background" id="popup-background"></div>
        <div class="container">
        <h1> 퀴즈 게임</h1>
        <div id="settings-container">
            <label for="difficulty">난이도 선택:</label>
            <select id="difficulty">
                <option value="easy">쉬움</option>
                <option value="medium">보통</option>
                <option value="hard">어려움</option>
            </select>
            <button id="start-game">게임 시작</button>
            <button onclick="showRankings()">랭킹 보기</button>
        </div>
        <div id="quiz-container" class="hidden">
            <p id="question"></p>
            <input type="text" id="answer" placeholder="여기에 답을 입력하세요">
            <button id="submit-answer">제출</button>
            <p>총 문제 수: 15</p>
            <p>틀린 갯수: <span id="wrong-count">0</span></p>
            <p>남은 문제 수: <span id="remaining-count">15</span></p>
        </div>
        <div id="score-container" class="hidden">
            <p>당신의 점수: <span id="score"></span></p>
            <input type="text" id="username" class="hidden" placeholder="이름을 입력하세요">
            <button id="submit-score">점수 제출</button>
            <button onclick="showRankings()">랭킹 보기</button>
        </div>
        <div id="ranking-container" class="hidden">
            <h2>최고 점수</h2>
            <ol id="rankings"></ol>
            <button onclick="restartGame()">게임 재시작</button>
        </div>
    </div>

    <script>
        const questionElement = document.getElementById('question');
        const answerElement = document.getElementById('answer');
        const submitAnswerButton = document.getElementById('submit-answer');
        const quizContainer = document.getElementById('quiz-container');
        const scoreContainer = document.getElementById('score-container');
        const rankingContainer = document.getElementById('ranking-container');
        const scoreElement = document.getElementById('score');
        const usernameElement = document.getElementById('username');
        const submitScoreButton = document.getElementById('submit-score');
        const wrongCountElement = document.getElementById('wrong-count');
        const remainingCountElement = document.getElementById('remaining-count');
        const startGameButton = document.getElementById('start-game');
        const settingsContainer = document.getElementById('settings-container');
        const difficultySelect = document.getElementById('difficulty');
        const popup = document.getElementById('popup');
        const popupBackground = document.getElementById('popup-background');
        const rankingsElement = document.getElementById('rankings');

        let currentQuestionIndex = 0;
        let score = 0;
        let wrongCount = 0;
        let questions = [];

        function translatePage(language) {
            const url = `https://translate.google.com/translate?hl=&sl=auto&tl=${language}&u=${encodeURIComponent(window.location.href)}`;
            window.location.href = url;
        }

        function showPopup() {
            popup.style.display = 'block';
            popupBackground.style.display = 'block';
        }

        function closePopup() {
            popup.style.display = 'none';
            popupBackground.style.display = 'none';
        }

        async function fetchQuestions(difficulty) {
            const response = await fetch(`https://opentdb.com/api.php?amount=15&difficulty=${difficulty}&type=multiple&encode=url3986`);
            const data = await response.json();
            questions = data.results.map(q => ({
                word: decodeURIComponent(q.correct_answer),
                hint: decodeURIComponent(q.question)
            }));
            showQuestion();
        }

        function showQuestion() {
            if (currentQuestionIndex < questions.length) {
                questionElement.innerHTML = questions[currentQuestionIndex].hint;
                remainingCountElement.textContent = questions.length - currentQuestionIndex;
            } else {
                endQuiz();
            }
        }

        function checkAnswer() {
            const userAnswer = answerElement.value.trim().toLowerCase();
            const correctAnswer = questions[currentQuestionIndex].word.toLowerCase();
            
            if (userAnswer === correctAnswer) {
                score++;
            } else {
                wrongCount++;
                wrongCountElement.textContent = wrongCount;
            }
            
            currentQuestionIndex++;
            answerElement.value = '';
            showQuestion();
        }

        function endQuiz() {
            quizContainer.classList.add('hidden');
            scoreContainer.classList.remove('hidden');
            scoreElement.textContent = score;
        }

        function getMaskedIP(ip) {
            const parts = ip.split('.');
            return `${parts[0]}.${parts[1]}.***.***`;
        }

        async function getUserIP() {
            try {
                const response = await fetch('https://api.ipify.org?format=json');
                const data = await response.json();
                return data.ip;
            } catch (error) {
                console.error('IP 주소를 가져오지 못했습니다:', error);
                return 'unknown';
            }
        }

        async function submitScore() {
            const ip = await getUserIP();
            const maskedIP = getMaskedIP(ip);
            
            const rankings = JSON.parse(localStorage.getItem('rankings')) || [];
            rankings.push({ name: maskedIP, score: score });
            rankings.sort((a, b) => b.score - a.score);
            localStorage.setItem('rankings', JSON.stringify(rankings.slice(0, 10))); // 상위 10명만 저장
                
            showRankings();
        }

        function showRankings() {
            scoreContainer.classList.add('hidden');
            rankingContainer.classList.remove('hidden');
            
            const rankings = JSON.parse(localStorage.getItem('rankings')) || [];
            rankingsElement.innerHTML = rankings.map(rank => `<li>${rank.name}: ${rank.score}</li>`).join('');
        }

        function restartGame() {
            settingsContainer.classList.remove('hidden');
            quizContainer.classList.add('hidden');
            rankingContainer.classList.add('hidden');
            scoreContainer.classList.add('hidden');
            currentQuestionIndex = 0;
            score = 0;
            wrongCount = 0;
            wrongCountElement.textContent = wrongCount;
            remainingCountElement.textContent = 15;
        }

        startGameButton.addEventListener('click', () => {
                       const difficulty = difficultySelect.value;
            fetchQuestions(difficulty);
            settingsContainer.classList.add('hidden');
            quizContainer.classList.remove('hidden');
        });

        submitAnswerButton.addEventListener('click', checkAnswer);
        submitScoreButton.addEventListener('click', submitScore);

        // 페이지 로드 시 팝업을 보여줍니다.
        window.onload = showPopup;

        // 게임 시작 시 기본 상태로 설정합니다.
        restartGame();
    </script>
</body>
</html>

Categorized in:

간단 게임,