Deespeek制作单词小游戏,附上代码

大家中午好啊,小师弟吃完午饭,就赶紧给小伙伴们解决问题啦!

昨天说到Deespeek快速制作英语单词,有些小伙伴还是不知道怎么增加背景音乐,

附代码,可自定义更改音乐效果!

也可以从代码中批量添加小孩需要听写的单词哦!

附单词小游戏代码

<!DOCTYPE html>
<html lang="en">
<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;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            text-align: center;
            background-color: #f5f5f5;
        }
        .game-container {
            background-color: white;
            border-radius: 10px;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }
        .header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }
        .score, .timer {
            font-size: 18px;
            font-weight: bold;
        }
        .question {
            font-size: 24px;
            margin: 20px 0;
            color: #333;
        }
        .letters-container {
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 10px;
            margin: 20px 0;
        }
        .letter {
            width: 50px;
            height: 50px;
            background-color: #4CAF50;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
        }
        .letter:hover {
            background-color: #45a049;
            transform: scale(1.1);
        }
        .letter.selected {
            background-color: #ff9800;
        }
        .answer-container {
            min-height: 60px;
            border: 2px dashed #ccc;
            border-radius: 5px;
            margin: 20px 0;
            padding: 10px;
            display: flex;
            flex-wrap: wrap;
            justify-content: center;
            gap: 10px;
        }
        .answer-letter {
            width: 40px;
            height: 40px;
            background-color: #2196F3;
            color: white;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            border-radius: 5px;
        }
        .buttons {
            margin-top: 20px;
        }
        button {
            padding: 10px 20px;
            font-size: 16px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin: 0 10px;
            transition: all 0.3s;
        }
        .submit {
            background-color: #4CAF50;
            color: white;
        }
        .submit:hover {
            background-color: #45a049;
        }
        .clear {
            background-color: #f44336;
            color: white;
        }
        .clear:hover {
            background-color: #d32f2f;
        }
        .result {
            font-size: 18px;
            margin: 20px 0;
            min-height: 27px;
        }
        .correct {
            color: #4CAF50;
        }
        .incorrect {
            color: #f44336;
        }
        .game-over {
            font-size: 24px;
            font-weight: bold;
            color: #2196F3;
            margin: 20px 0;
        }
        .progress {
            width: 100%;
            background-color: #ddd;
            border-radius: 5px;
            margin: 20px 0;
        }
        .progress-bar {
            height: 20px;
            background-color: #4CAF50;
            border-radius: 5px;
            width: 1%;
            transition: width 0.3s;
        }
        .visual-progress {
            position: relative;
            height: 200px;
            margin: 20px 0;
            overflow: hidden;
            border-radius: 10px;
            background: linear-gradient(to bottom, #87CEEB, #E0F7FA);
        }
        .road {
            position: absolute;
            bottom: 0;
            width: 100%;
            height: 30px;
            background-color: #795548;
        }
        .character {
            position: absolute;
            bottom: 30px;
            left: 20px;
            width: 60px;
            height: 80px;
            transition: left 1s ease-in-out, transform 0.5s;
            z-index: 10;
            background-size: contain;
            background-repeat: no-repeat;
            background-position: center bottom;
        }
        .final-scene {
            position: absolute;
            right: 20px;
            bottom: 30px;
            width: 150px;
            height: 180px;
            display: none;
        }
        .tree {
            position: absolute;
            bottom: 0;
            width: 40px;
            height: 120px;
            background-color: #5D4037;
            left: 55px;
        }
        .tree-top {
            position: absolute;
            bottom: 100px;
            left: 0;
            width: 150px;
            height: 100px;
            background-color: #4CAF50;
            border-radius: 50%;
        }
        .apple {
            position: absolute;
            width: 15px;
            height: 15px;
            background-color: #F44336;
            border-radius: 50%;
            display: none;
        }
        .confetti {
            position: absolute;
            width: 10px;
            height: 10px;
            opacity: 0;
        }
        .word-management {
            margin-top: 30px;
            text-align: left;
            border-top: 1px solid #eee;
            padding-top: 20px;
        }
        .word-list {
            max-height: 200px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 10px;
            margin: 10px 0;
        }
        .word-item {
            display: flex;
            justify-content: space-between;
            padding: 8px;
            border-bottom: 1px solid #eee;
        }
        .word-item:last-child {
            border-bottom: none;
        }
        .delete-word {
            color: #f44336;
            cursor: pointer;
        }
        .add-word-form {
            display: flex;
            gap: 10px;
            margin-top: 15px;
        }
        .add-word-form input {
            flex-grow: 1;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .add-word-form button {
            margin: 0;
        }
        .tab-container {
            display: flex;
            margin-bottom: 20px;
        }
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            background-color: #eee;
            border-radius: 5px 5px 0 0;
            margin-right: 5px;
        }
        .tab.active {
            background-color: #4CAF50;
            color: white;
        }
        .content-container {
            display: none;
        }
        .content-container.active {
            display: block;
        }
        .music-control {
            position: fixed;
            bottom: 20px;
            right: 20px;
            width: 40px;
            height: 40px;
            background-color: #4CAF50;
            color: white;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
        }
        @keyframes bounce {
            0%, 100% { transform: translateY(0); }
            50% { transform: translateY(-20px); }
        }
        .bounce {
            animation: bounce 0.5s;
        }
        @keyframes heroPulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.1); }
        }
        .hero-pulse {
            animation: heroPulse 1s infinite;
        }
    </style>
</head>
<body>
    <div class="game-container">
        <h1>英语单词组合小游戏</h1>

        <div class="tab-container">
            <div class="tab active" data-tab="game">游戏</div>
            <div class="tab" data-tab="words">单词管理</div>
        </div>

        <div class="content-container active" id="game-content">
            <div class="header">
                <div class="score">得分: <span id="score">0</span></div>
                <div class="timer">时间: <span id="time">05:00</span></div>
            </div>
            <div class="progress">
                <div class="progress-bar" id="progress"></div>
            </div>

            <!-- 视觉进度展示 -->
            <div class="visual-progress">
                <div class="road"></div>
                <div class="character" id="character"></div>
                <div class="final-scene">
                    <div class="tree"></div>
                    <div class="tree-top"></div>
                    <!-- 苹果将在这里动态添加 -->
                </div>
                <!-- 彩色纸屑将在这里动态添加 -->
            </div>

            <div class="question" id="question">准备好开始了吗?</div>
            <div class="answer-container" id="answer-container"></div>
            <div class="letters-container" id="letters-container"></div>
            <div class="result" id="result"></div>
            <div class="buttons">
                <button class="submit" id="submit">提交</button>
                <button class="clear" id="clear">清除</button>
                <button class="start" id="start">开始游戏</button>
            </div>
        </div>

        <div class="content-container" id="words-content">
            <div class="word-management">
                <h2>单词管理</h2>
                <p>当前单词库 (<span id="word-count">0</span> 个单词):</p>
                <div class="word-list" id="word-list">
                    <!-- 单词列表将在这里动态生成 -->
                </div>
                <div class="add-word-form">
                    <input type="text" id="chinese-input" placeholder="中文 (如: 苹果)">
                    <input type="text" id="english-input" placeholder="英文 (如: apple)">
                    <input type="text" id="extra-letters" placeholder="额外字母 (如: b,c)">
                    <button id="add-word">添加单词</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 音乐控制按钮 -->
    <div class="music-control" id="music-control">♪</div>

    <!-- 音频元素 -->
    <audio id="background-music" loop>
        <source src="https://www.soundhelix.com/examples/mp3/SoundHelix-Song-17.mp3" type="audio/mpeg">
    </audio>
    <audio id="correct-sound">
        <source src="https://www.soundjay.com/buttons/sounds/button-09.mp3" type="audio/mpeg">
    </audio>
    <audio id="wrong-sound">
        <source src="https://www.soundjay.com/buttons/sounds/button-10.mp3" type="audio/mpeg">
    </audio>
    <audio id="level-up-sound">
        <source src="https://www.soundjay.com/buttons/sounds/button-21.mp3" type="audio/mpeg">
    </audio>

    <script>
        // 默认单词库 - 中文: [英文, 额外字母1, 额外字母2, ...]
        const defaultWordPairs = {
            "苹果": ["apple", "b", "c"],
            "香蕉": ["banana", "p", "o"],
            "猫": ["cat", "d", "e"],
            "狗": ["dog", "a", "t"],
            "鸡蛋": ["egg", "h", "i"],
            "鱼": ["fish", "g", "l"],
            "女孩": ["girl", "b", "y"],
            "房子": ["house", "r", "m"],
            "冰淇淋": ["icecream", "h", "n"],
            "果汁": ["juice", "m", "k"],
            "风筝": ["kite", "f", "l"],
            "狮子": ["lion", "e", "m"],
            "猴子": ["monkey", "a", "s"],
            "鼻子": ["nose", "e", "y"],
            "橙色": ["orange", "p", "l"],
            "猪": ["pig", "o", "e"],
            "女王": ["queen", "k", "i"],
            "兔子": ["rabbit", "e", "d"],
            "太阳": ["sun", "m", "o"],
            "树": ["tree", "a", "d"],
            "雨伞": ["umbrella", "o", "p"],
            "蔬菜": ["vegetable", "f", "h"],
            "水": ["water", "i", "l"],
            "狐狸": ["fox", "b", "e"],
            "黄色": ["yellow", "b", "w"],
            "动物园": ["zoo", "a", "p"]
        };

        // 从本地存储加载单词库,如果没有则使用默认单词库
        let wordPairs = JSON.parse(localStorage.getItem('wordPairs')) || defaultWordPairs;

        // 游戏变量
        let score = 0;
        let timeLeft = 300; // 5分钟 = 300秒
        let timer;
        let currentQuestion = 0;
        let totalQuestions = 20; // 总共20题 (可以根据需要调整)
        let selectedLetters = [];
        let currentWord = "";
        let currentAnswer = "";
        let gameStarted = false;
        let extraLetters = [];
        let correctAnswers = 0;
        let currentLevel = 0;
        let musicOn = true;

        // 角色等级配置
        const characterLevels = [
            { name: "小怪兽", score: 0, color: "#FF5722", emoji: "👾" },
            { name: "小勇士", score: 40, color: "#4CAF50", emoji: "🦸" },
            { name: "超级英雄", score: 80, color: "#2196F3", emoji: "🦸‍♂️" },
            { name: "奥特曼", score: 150, color: "#FFC107", emoji: "🦸‍♂️💥" }
        ];

        // DOM元素
        const scoreElement = document.getElementById('score');
        const timeElement = document.getElementById('time');
        const questionElement = document.getElementById('question');
        const lettersContainer = document.getElementById('letters-container');
        const answerContainer = document.getElementById('answer-container');
        const resultElement = document.getElementById('result');
        const submitButton = document.getElementById('submit');
        const clearButton = document.getElementById('clear');
        const startButton = document.getElementById('start');
        const progressBar = document.getElementById('progress');
        const wordListElement = document.getElementById('word-list');
        const wordCountElement = document.getElementById('word-count');
        const chineseInput = document.getElementById('chinese-input');
        const englishInput = document.getElementById('english-input');
        const extraLettersInput = document.getElementById('extra-letters');
        const addWordButton = document.getElementById('add-word');
        const tabs = document.querySelectorAll('.tab');
        const gameContent = document.getElementById('game-content');
        const wordsContent = document.getElementById('words-content');
        const visualProgress = document.querySelector('.visual-progress');
        const character = document.getElementById('character');
        const finalScene = document.querySelector('.final-scene');
        const treeTop = document.querySelector('.tree-top');
        const musicControl = document.getElementById('music-control');
        const bgMusic = document.getElementById('background-music');
        const correctSound = document.getElementById('correct-sound');
        const wrongSound = document.getElementById('wrong-sound');
        const levelUpSound = document.getElementById('level-up-sound');

        // 初始化游戏
        function initGame() {
            score = 0;
            timeLeft = 300;
            currentQuestion = 0;
            correctAnswers = 0;
            currentLevel = 0;
            gameStarted = true;

            scoreElement.textContent = score;
            updateTimerDisplay();

            startButton.style.display = 'none';
            submitButton.style.display = 'inline-block';
            clearButton.style.display = 'inline-block';

            // 重置视觉进度
            character.style.left = '20px';
            finalScene.style.display = 'none';
            document.querySelectorAll('.apple').forEach(apple => apple.remove());

            // 更新角色形象
            updateCharacter();

            // 播放背景音乐
            if (musicOn) {
                bgMusic.play().catch(e => console.log("自动播放被阻止,请点击页面后重试"));
            }

            timer = setInterval(updateTimer, 1000);

            loadNextQuestion();
        }

        // 加载下一个问题
        function loadNextQuestion() {
            if (currentQuestion >= totalQuestions) {
                endGame();
                return;
            }

            currentQuestion++;
            updateProgressBar();

            // 随机选择一个单词
            const chineseWords = Object.keys(wordPairs);

            if (chineseWords.length === 0) {
                questionElement.textContent = "单词库为空,请添加单词";
                lettersContainer.innerHTML = '';
                answerContainer.innerHTML = '';
                clearInterval(timer);
                return;
            }

            const randomIndex = Math.floor(Math.random() * chineseWords.length);
            const chineseWord = chineseWords[randomIndex];
            const wordData = wordPairs[chineseWord];

            currentAnswer = wordData[0];
            extraLetters = wordData.slice(1);

            // 创建字母池 (正确答案的字母 + 额外字母)
            const allLetters = [...currentAnswer.split(''), ...extraLetters];
            shuffleArray(allLetters);

            // 显示问题
            questionElement.textContent = `${currentQuestion}. ${chineseWord} (${currentAnswer.length}个字母)`;

            // 清空之前的字母和答案
            lettersContainer.innerHTML = '';
            answerContainer.innerHTML = '';
            selectedLetters = [];
            resultElement.textContent = '';
            resultElement.className = 'result';

            // 创建字母按钮
            allLetters.forEach((letter, index) => {
                const letterElement = document.createElement('div');
                letterElement.className = 'letter';
                letterElement.textContent = letter.toUpperCase();
                letterElement.dataset.index = index;
                letterElement.addEventListener('click', () => selectLetter(letter, index));
                lettersContainer.appendChild(letterElement);
            });
        }

        // 选择字母
        function selectLetter(letter, index) {
            if (selectedLetters.includes(index)) {
                // 如果字母已选中,则取消选择
                const selectedIndex = selectedLetters.indexOf(index);
                selectedLetters.splice(selectedIndex, 1);

                // 从答案区域移除
                const answerLetters = answerContainer.querySelectorAll('.answer-letter');
                answerLetters[selectedIndex].remove();

                // 更新字母按钮样式
                lettersContainer.children[index].classList.remove('selected');
            } else {
                // 选择字母
                selectedLetters.push(index);

                // 添加到答案区域
                const answerLetter = document.createElement('div');
                answerLetter.className = 'answer-letter';
                answerLetter.textContent = letter.toUpperCase();
                answerContainer.appendChild(answerLetter);

                // 更新字母按钮样式
                lettersContainer.children[index].classList.add('selected');
            }
        }

        // 提交答案
        function submitAnswer() {
            if (selectedLetters.length !== currentAnswer.length) {
                resultElement.textContent = `答案需要${currentAnswer.length}个字母!`;
                resultElement.className = 'result incorrect';
                playSound(wrongSound);
                return;
            }

            // 获取用户答案
            let userAnswer = '';
            selectedLetters.forEach(index => {
                userAnswer += lettersContainer.children[index].textContent.toLowerCase();
            });

            // 检查答案
            if (userAnswer === currentAnswer) {
                score += 10;
                correctAnswers++;
                scoreElement.textContent = score;
                resultElement.textContent = '正确!+10分';
                resultElement.className = 'result correct';
                playSound(correctSound);

                // 检查是否升级
                checkLevelUp();

                // 显示视觉效果
                showCorrectAnswerEffect();
            } else {
                resultElement.textContent = `错误!正确答案是: ${currentAnswer}`;
                resultElement.className = 'result incorrect';
                playSound(wrongSound);
            }

            // 延迟加载下一题
            setTimeout(loadNextQuestion, 1500);
        }

        // 检查角色是否升级
        function checkLevelUp() {
            const newLevel = characterLevels.findIndex(level => score < level.score) - 1;
            if (newLevel > currentLevel) {
                currentLevel = newLevel;
                playSound(levelUpSound);
                updateCharacter();

                // 显示升级消息
                const levelName = characterLevels[currentLevel].name;
                const levelEmoji = characterLevels[currentLevel].emoji;
                const levelUpMessage = document.createElement('div');
                levelUpMessage.textContent = `升级啦!${levelEmoji} ${levelName} ${levelEmoji}`;
                levelUpMessage.style.position = 'absolute';
                levelUpMessage.style.top = '50px';
                levelUpMessage.style.left = '50%';
                levelUpMessage.style.transform = 'translateX(-50%)';
                levelUpMessage.style.fontSize = '20px';
                levelUpMessage.style.fontWeight = 'bold';
                levelUpMessage.style.color = characterLevels[currentLevel].color;
                levelUpMessage.style.zIndex = '100';
                levelUpMessage.style.animation = 'fadeOut 2s forwards';

                visualProgress.appendChild(levelUpMessage);

                setTimeout(() => {
                    levelUpMessage.remove();
                }, 2000);
            }
        }

        // 更新角色形象
        function updateCharacter() {
            let levelConfig;

            // 找到当前等级配置
            for (let i = characterLevels.length - 1; i >= 0; i--) {
                if (score >= characterLevels[i].score) {
                    levelConfig = characterLevels[i];
                    break;
                }
            }

            // 如果没有匹配的等级,使用最低等级
            if (!levelConfig) {
                levelConfig = characterLevels[0];
            }

            // 更新角色样式
            character.style.backgroundColor = levelConfig.color;
            character.innerHTML = levelConfig.emoji;
            character.style.fontSize = '30px';
            character.style.display = 'flex';
            character.style.alignItems = 'center';
            character.style.justifyContent = 'center';

            // 如果是最高等级,添加特殊效果
            if (levelConfig.name === "奥特曼") {
                character.classList.add('hero-pulse');
            } else {
                character.classList.remove('hero-pulse');
            }
        }

        // 显示正确答案的视觉效果
        function showCorrectAnswerEffect() {
            // 显示最终场景(如果还没显示)
            if (finalScene.style.display === 'none') {
                finalScene.style.display = 'block';
            }

            // 计算角色应该移动到的位置
            const progress = correctAnswers / totalQuestions;
            const maxDistance = visualProgress.offsetWidth - 200; // 留出空间给最终场景
            const newPosition = 20 + (maxDistance * progress);

            // 移动角色
            character.style.left = `${newPosition}px`;

            // 在树上添加一个苹果
            if (correctAnswers <= 20) { // 最多20个苹果
                const apple = document.createElement('div');
                apple.className = 'apple';

                // 随机位置(在树冠范围内)
                const left = 10 + Math.random() * 130;
                const top = 50 + Math.random() * 70;

                apple.style.left = `${left}px`;
                apple.style.top = `${top}px`;
                apple.style.display = 'block';

                // 添加弹跳动画
                apple.classList.add('bounce');

                finalScene.appendChild(apple);

                // 动画结束后移除bounce类
                setTimeout(() => {
                    apple.classList.remove('bounce');
                }, 500);
            }

            // 创建彩色纸屑效果
            createConfetti();
        }

        // 创建彩色纸屑效果
        function createConfetti() {
            const colors = ['#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5', '#2196f3', '#03a9f4', '#00bcd4', '#009688', '#4CAF50', '#8BC34A', '#CDDC39', '#FFEB3B', '#FFC107', '#FF9800', '#FF5722'];

            for (let i = 0; i < 50; i++) {
                const confetti = document.createElement('div');
                confetti.className = 'confetti';
                confetti.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
                confetti.style.left = `${Math.random() * 100}%`;
                confetti.style.top = '-10px';
                confetti.style.transform = `rotate(${Math.random() * 360}deg)`;

                visualProgress.appendChild(confetti);

                // 动画
                const animationDuration = 1 + Math.random() * 2;
                const animationDelay = Math.random() * 0.5;

                confetti.style.transition = `all ${animationDuration}s ease-out ${animationDelay}s`;

                setTimeout(() => {
                    confetti.style.opacity = '1';
                    confetti.style.top = `${100 + Math.random() * 20}%`;
                    confetti.style.left = `${parseFloat(confetti.style.left) + (Math.random() * 20 - 10)}%`;
                }, 10);

                // 移除元素
                setTimeout(() => {
                    confetti.remove();
                }, (animationDuration + animationDelay) * 1000);
            }
        }

        // 播放音效
        function playSound(sound) {
            if (!musicOn) return;

            sound.currentTime = 0;
            sound.play().catch(e => console.log("音效播放失败"));
        }

        // 清除当前答案
        function clearAnswer() {
            selectedLetters.forEach(index => {
                lettersContainer.children[index].classList.remove('selected');
            });
            selectedLetters = [];
            answerContainer.innerHTML = '';
            resultElement.textContent = '';
            resultElement.className = 'result';
        }

        // 更新计时器
        function updateTimer() {
            timeLeft--;
            updateTimerDisplay();

            if (timeLeft <= 0) {
                endGame();
            }
        }

        // 更新计时器显示
        function updateTimerDisplay() {
            const minutes = Math.floor(timeLeft / 60);
            const seconds = timeLeft % 60;
            timeElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }

        // 更新进度条
        function updateProgressBar() {
            const progress = (currentQuestion / totalQuestions) * 100;
            progressBar.style.width = `${progress}%`;
        }

        // 结束游戏
        function endGame() {
            clearInterval(timer);
            gameStarted = false;

            questionElement.textContent = '游戏结束!';
            lettersContainer.innerHTML = '';
            answerContainer.innerHTML = '';
            resultElement.textContent = `你的最终得分是: ${score}分`;
            resultElement.className = 'result';

            submitButton.style.display = 'none';
            clearButton.style.display = 'none';
            startButton.style.display = 'inline-block';
            startButton.textContent = '再玩一次';

            // 角色移动到终点
            character.style.left = `calc(100% - 180px)`;

            // 停止背景音乐
            bgMusic.pause();
        }

        // 更新单词列表显示
        function updateWordList() {
            wordListElement.innerHTML = '';
            const chineseWords = Object.keys(wordPairs);
            wordCountElement.textContent = chineseWords.length;

            if (chineseWords.length === 0) {
                wordListElement.innerHTML = '<p>单词库为空,请添加单词</p>';
                return;
            }

            chineseWords.forEach(chineseWord => {
                const wordData = wordPairs[chineseWord];
                const englishWord = wordData[0];
                const extraLetters = wordData.slice(1).join(', ');

                const wordItem = document.createElement('div');
                wordItem.className = 'word-item';
                wordItem.innerHTML = `
                    <span>${chineseWord} → ${englishWord} (额外字母: ${extraLetters || '无'})</span>
                    <span class="delete-word" data-word="${chineseWord}">删除</span>
                `;
                wordListElement.appendChild(wordItem);
            });

            // 添加删除事件监听
            document.querySelectorAll('.delete-word').forEach(button => {
                button.addEventListener('click', function() {
                    const wordToDelete = this.getAttribute('data-word');
                    deleteWord(wordToDelete);
                });
            });
        }

        // 添加新单词
        function addNewWord() {
            const chinese = chineseInput.value.trim();
            const english = englishInput.value.trim().toLowerCase();
            const extras = extraLettersInput.value.trim().split(',').map(e => e.trim()).filter(e => e);

            if (!chinese || !english) {
                alert('请输入中文和英文单词!');
                return;
            }

            if (wordPairs[chinese]) {
                alert('该中文单词已存在!');
                return;
            }

            wordPairs[chinese] = [english, ...extras];
            saveWordPairs();

            chineseInput.value = '';
            englishInput.value = '';
            extraLettersInput.value = '';

            updateWordList();
        }

        // 删除单词
        function deleteWord(chineseWord) {
            if (confirm(`确定要删除 "${chineseWord}" 这个单词吗?`)) {
                delete wordPairs[chineseWord];
                saveWordPairs();
                updateWordList();
            }
        }

        // 保存单词库到本地存储
        function saveWordPairs() {
            localStorage.setItem('wordPairs', JSON.stringify(wordPairs));
        }

        // 辅助函数:打乱数组顺序
        function shuffleArray(array) {
            for (let i = array.length - 1; i > 0; i--) {
                const j = Math.floor(Math.random() * (i + 1));
                [array[i], array[j]] = [array[j], array[i]];
            }
            return array;
        }

        // 初始化页面
        function initPage() {
            updateWordList();

            // 标签切换
            tabs.forEach(tab => {
                tab.addEventListener('click', function() {
                    tabs.forEach(t => t.classList.remove('active'));
                    this.classList.add('active');

                    const tabName = this.getAttribute('data-tab');
                    gameContent.classList.remove('active');
                    wordsContent.classList.remove('active');

                    if (tabName === 'game') {
                        gameContent.classList.add('active');
                    } else {
                        wordsContent.classList.add('active');
                    }
                });
            });

            // 音乐控制
            musicControl.addEventListener('click', function() {
                musicOn = !musicOn;
                if (musicOn) {
                    bgMusic.play();
                    musicControl.textContent = '♪';
                    musicControl.style.backgroundColor = '#4CAF50';
                } else {
                    bgMusic.pause();
                    musicControl.textContent = '🔇';
                    musicControl.style.backgroundColor = '#f44336';
                }
            });

            // 点击页面后允许音频播放(解决浏览器自动播放限制)
            document.body.addEventListener('click', function() {
                if (musicOn && bgMusic.paused) {
                    bgMusic.play().catch(e => console.log("音频播放被阻止"));
                }
            }, { once: true });
        }

        // 事件监听
        startButton.addEventListener('click', initGame);
        submitButton.addEventListener('click', submitAnswer);
        clearButton.addEventListener('click', clearAnswer);
        addWordButton.addEventListener('click', addNewWord);

        // 初始化页面
        initPage();
    </script>
</body>
</html>

复制以上代码到记事本,把记事本格式改为html格式,点击就可以运行啦!

运行效果如下:

个人说明个人说明个人说明
上一篇

推荐 10 个很“哇塞”的Web“资源”给前端工友,收藏等于学会~

下一篇

一行代码不写,就能让DeepSeek生成学生成长档案管理器!

你也可能喜欢

发表评论

您的电子邮件地址不会被公开。 必填项已用 * 标注

提示:点击验证后方可评论!

插入图片

最新评论

热线 热线
13888888888
QQ QQ
QQ在线咨询
微信 微信
微信
关注 关注
关注
返回顶部

微信扫一扫

微信扫一扫