跳到正文

休闲·娱乐

塔防

Zhao_Yinghe约 112 分钟
原文
文章信息与版本

文章信息

发布
2025年12月14日
收录
2025年12月14日
更新
2026年11月21日
篇幅
约 112 分钟

版本

  1. v2当前
  2. v1
HTML
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>塔防游戏 - 网页版</title>
    <!-- Tailwind CSS v3 -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#4CAF50',
                        secondary: '#FFC107',
                        danger: '#F44336',
                        info: '#2196F3',
                        dark: '#2C3E50',
                        light: '#ECF0F1'
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    animation: {
                        'pulse-slow': 'pulse 3s cubic-bezier(0.4, 0, 0.6, 1) infinite',
                    }
                }
            }
        }
    </script>
    <style type="text/tailwindcss">
        @layer utilities {
            .text-shadow {
                text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
            }
            .tower-shadow {
                filter: drop-shadow(0px 4px 6px rgba(0, 0, 0, 0.3));
            }
            .enemy-shadow {
                filter: drop-shadow(0px 2px 4px rgba(0, 0, 0, 0.2));
            }
            .rain-effect {
                background-image: linear-gradient(to bottom, rgba(255,255,255,0) 0%, rgba(255,255,255,0.7) 100%);
                animation: rain 0.8s linear infinite;
            }
            @keyframes rain {
                0% { transform: translateY(-100%); opacity: 0; }
                50% { opacity: 0.5; }
                100% { transform: translateY(100%); opacity: 0; }
            }
        }
    </style>
    <style>
        body {
            overflow: hidden;
            background-color: #1a1a2e;
        }
        #gameCanvas {
            background-color: #2c3e50;
            background-image: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><rect width="100" height="100" fill="%232c3e50"/><path d="M0,50 L100,50 M50,0 L50,100" stroke="%2334495e" stroke-width="0.5"/></svg>');
            background-size: 50px 50px;
        }
        .tower {
            cursor: pointer;
            transition: all 0.2s ease;
        }
        .tower:hover {
            transform: translateY(-5px);
        }
        .enemy {
            position: absolute;
            transition: transform 0.1s linear;
        }
        .projectile {
            position: absolute;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            background-color: #FFC107;
            z-index: 10;
        }
        .explosion {
            position: absolute;
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: #F44336;
            opacity: 0.7;
            animation: explode 0.5s ease-out forwards;
            z-index: 20;
        }
        @keyframes explode {
            0% { transform: scale(0); opacity: 1; }
            100% { transform: scale(2); opacity: 0; }
        }
        .range-indicator {
            position: absolute;
            border: 2px dashed rgba(255, 255, 255, 0.5);
            border-radius: 50%;
            pointer-events: none;
            z-index: 5;
        }
        .health-bar {
            position: absolute;
            width: 100%;
            height: 4px;
            background-color: #e74c3c;
            top: -8px;
            left: 0;
            border-radius: 2px;
        }
        .health-bar-fill {
            height: 100%;
            background-color: #2ecc71;
            border-radius: 2px;
            transition: width 0.2s ease;
        }
        .weather-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            pointer-events: none;
            z-index: 15;
        }
        .tower-info {
            position: absolute;
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 8px;
            border-radius: 4px;
            font-size: 12px;
            z-index: 25;
            pointer-events: none;
            opacity: 0;
            transition: opacity 0.2s ease;
        }
        .tower:hover + .tower-info {
            opacity: 1;
        }
        .wave-notification {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 20px 40px;
            border-radius: 8px;
            font-size: 24px;
            font-weight: bold;
            z-index: 100;
            animation: wave-notification 2s ease-out forwards;
        }
        @keyframes wave-notification {
            0% { opacity: 0; transform: translate(-50%, -50%) scale(0.5); }
            20% { opacity: 1; transform: translate(-50%, -50%) scale(1.1); }
            30% { transform: translate(-50%, -50%) scale(1); }
            80% { opacity: 1; }
            100% { opacity: 0; }
        }
    </style>
</head>
<body class="bg-gray-900 text-white">
    <div class="flex flex-col h-screen">
        <!-- 顶部信息栏 -->
        <div class="bg-dark p-4 flex justify-between items-center shadow-lg">
            <div class="flex items-center space-x-6">
                <div class="flex items-center">
                    <i class="fa fa-coins text-secondary text-2xl mr-2"></i>
                    <span id="gold" class="text-xl font-bold">500</span>
                </div>
                <div class="flex items-center">
                    <i class="fa fa-heart text-danger text-2xl mr-2"></i>
                    <span id="lives" class="text-xl font-bold">20</span>
                </div>
                <div class="flex items-center">
                    <i class="fa fa-refresh text-info text-2xl mr-2"></i>
                    <span id="wave" class="text-xl font-bold">1</span>
                </div>
            </div>
            <div class="flex items-center space-x-4">
                <div class="flex items-center">
                    <label for="gameSpeed" class="mr-2">速度:</label>
                    <input type="range" id="gameSpeed" min="0.5" max="2" step="0.5" value="1" class="w-24">
                    <span id="speedValue" class="ml-2">1x</span>
                </div>
                <button id="startWave" class="bg-primary hover:bg-green-600 text-white font-bold py-2 px-4 rounded-lg transition-all flex items-center">
                    <i class="fa fa-play mr-2"></i> 开始波次
                </button>
                <button id="pauseGame" class="bg-info hover:bg-blue-600 text-white font-bold py-2 px-4 rounded-lg transition-all flex items-center">
                    <i class="fa fa-pause mr-2"></i> 暂停
                </button>
                <button id="restartGame" class="bg-danger hover:bg-red-600 text-white font-bold py-2 px-4 rounded-lg transition-all flex items-center">
                    <i class="fa fa-refresh mr-2"></i> 重新开始
                </button>
            </div>
        </div>

        <!-- 主要游戏区域 -->
        <div class="flex flex-1 overflow-hidden">
            <!-- 左侧防御塔选择面板 -->
            <div class="w-64 bg-dark p-4 shadow-lg overflow-y-auto">
                <h2 class="text-xl font-bold mb-4 text-center border-b border-gray-700 pb-2">防御塔</h2>
                <div class="space-y-4">
                    <!-- 防御塔类型1 -->
                    <div class="tower bg-gray-800 rounded-lg p-3 flex flex-col items-center hover:bg-gray-700 transition-all">
                        <div class="tower-icon w-16 h-16 bg-primary rounded-full flex items-center justify-center mb-2 tower-shadow">
                            <i class="fa fa-crosshairs text-2xl"></i>
                        </div>
                        <h3 class="font-bold">基础塔</h3>
                        <div class="flex justify-between w-full mt-2 text-sm">
                            <span>伤害: 10</span>
                            <span>范围: 100</span>
                        </div>
                        <div class="flex justify-between w-full mt-1 text-sm">
                            <span>攻速: 快</span>
                            <span class="text-secondary"><i class="fa fa-coins mr-1"></i>50</span>
                        </div>
                        <button class="tower-btn mt-2 w-full bg-primary hover:bg-green-600 text-white py-1 px-2 rounded transition-all" data-tower-type="basic">
                            选择
                        </button>
                    </div>

                    <!-- 防御塔类型2 -->
                    <div class="tower bg-gray-800 rounded-lg p-3 flex flex-col items-center hover:bg-gray-700 transition-all">
                        <div class="tower-icon w-16 h-16 bg-secondary rounded-full flex items-center justify-center mb-2 tower-shadow">
                            <i class="fa fa-bomb text-2xl"></i>
                        </div>
                        <h3 class="font-bold">爆破塔</h3>
                        <div class="flex justify-between w-full mt-2 text-sm">
                            <span>伤害: 30</span>
                            <span>范围: 80</span>
                        </div>
                        <div class="flex justify-between w-full mt-1 text-sm">
                            <span>攻速: 慢</span>
                            <span class="text-secondary"><i class="fa fa-coins mr-1"></i>100</span>
                        </div>
                        <button class="tower-btn mt-2 w-full bg-secondary hover:bg-yellow-600 text-white py-1 px-2 rounded transition-all" data-tower-type="explosive">
                            选择
                        </button>
                    </div>

                    <!-- 防御塔类型3 -->
                    <div class="tower bg-gray-800 rounded-lg p-3 flex flex-col items-center hover:bg-gray-700 transition-all">
                        <div class="tower-icon w-16 h-16 bg-info rounded-full flex items-center justify-center mb-2 tower-shadow">
                            <i class="fa fa-bolt text-2xl"></i>
                        </div>
                        <h3 class="font-bold">电塔</h3>
                        <div class="flex justify-between w-full mt-2 text-sm">
                            <span>伤害: 15</span>
                            <span>范围: 120</span>
                        </div>
                        <div class="flex justify-between w-full mt-1 text-sm">
                            <span>攻速: 中</span>
                            <span class="text-secondary"><i class="fa fa-coins mr-1"></i>150</span>
                        </div>
                        <button class="tower-btn mt-2 w-full bg-info hover:bg-blue-600 text-white py-1 px-2 rounded transition-all" data-tower-type="electric">
                            选择
                        </button>
                    </div>
                </div>

                <h2 class="text-xl font-bold my-4 text-center border-b border-gray-700 pb-2">天气效果</h2>
                <div class="space-y-2">
                    <div class="flex items-center justify-between">
                        <span>天气状态:</span>
                        <span id="weatherStatus" class="font-bold">晴天</span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span>效果:</span>
                        <span id="weatherEffect" class="text-sm">无特殊效果</span>
                    </div>
                </div>

                <h2 class="text-xl font-bold my-4 text-center border-b border-gray-700 pb-2">游戏统计</h2>
                <div class="space-y-2">
                    <div class="flex items-center justify-between">
                        <span>消灭敌人:</span>
                        <span id="enemiesKilled">0</span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span>建造塔数:</span>
                        <span id="towersBuilt">0</span>
                    </div>
                    <div class="flex items-center justify-between">
                        <span>游戏时间:</span>
                        <span id="gameTime">00:00</span>
                    </div>
                </div>
            </div>

            <!-- 游戏画布区域 -->
            <div class="flex-1 relative">
                <canvas id="gameCanvas" class="absolute top-0 left-0 w-full h-full"></canvas>
                <div id="weatherOverlay" class="weather-overlay"></div>
                <div id="towerInfo" class="tower-info"></div>
                
                <!-- 游戏结束/胜利界面 -->
                <div id="gameOver" class="absolute inset-0 bg-black bg-opacity-80 flex items-center justify-center z-50 hidden">
                    <div class="bg-dark p-8 rounded-lg shadow-2xl text-center max-w-md">
                        <h2 id="gameOverTitle" class="text-3xl font-bold mb-4">游戏结束</h2>
                        <p id="gameOverMessage" class="text-xl mb-6">你未能阻止敌人的进攻!</p>
                        <div class="space-y-4">
                            <div class="flex justify-between">
                                <span>波次:</span>
                                <span id="finalWave">1</span>
                            </div>
                            <div class="flex justify-between">
                                <span>消灭敌人:</span>
                                <span id="finalEnemiesKilled">0</span>
                            </div>
                            <div class="flex justify-between">
                                <span>建造塔数:</span>
                                <span id="finalTowersBuilt">0</span>
                            </div>
                        </div>
                        <button id="playAgain" class="mt-6 bg-primary hover:bg-green-600 text-white font-bold py-3 px-6 rounded-lg transition-all text-lg">
                            再玩一次
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        // 游戏常量
        const CANVAS_WIDTH = 1200;
        const CANVAS_HEIGHT = 600;
        const GRID_SIZE = 50;
        const PATH_COLOR = '#34495e';
        const GRASS_COLOR = '#27ae60';
        const TOWER_PLACE_COLOR = 'rgba(39, 174, 96, 0.5)';
        const TOWER_INVALID_COLOR = 'rgba(231, 76, 60, 0.5)';
        
        // 游戏状态
        let gameState = {
            gold: 500,
            lives: 20,
            wave: 1,
            gameSpeed: 1,
            isPaused: false,
            isWaveActive: false,
            selectedTowerType: null,
            towers: [],
            enemies: [],
            projectiles: [],
            explosions: [],
            weather: 'sunny', // sunny, rainy, snowy
            enemiesKilled: 0,
            towersBuilt: 0,
            gameTime: 0,
            gameTimeInterval: null,
            lastUpdateTime: 0,
            waveEnemies: 0,
            waveEnemiesSpawned: 0,
            waveEnemyLimit: 10,
            waveSpawnTimer: 0,
            waveSpawnInterval: 1000, // 毫秒
            gameOver: false
        };
        
        // 防御塔配置
        const towerTypes = {
            basic: {
                name: '基础塔',
                cost: 50,
                damage: 10,
                range: 100,
                fireRate: 1000, // 毫秒
                color: '#4CAF50',
                projectileColor: '#FFC107',
                projectileSpeed: 5,
                description: '基础防御塔,攻速快,伤害一般'
            },
            explosive: {
                name: '爆破塔',
                cost: 100,
                damage: 30,
                range: 80,
                fireRate: 2000, // 毫秒
                color: '#FFC107',
                projectileColor: '#F44336',
                projectileSpeed: 3,
                splashRadius: 40,
                description: '爆破塔,伤害高,范围攻击,攻速慢'
            },
            electric: {
                name: '电塔',
                cost: 150,
                damage: 15,
                range: 120,
                fireRate: 1500, // 毫秒
                color: '#2196F3',
                projectileColor: '#FFEB3B',
                projectileSpeed: 4,
                chainTargets: 2,
                description: '电塔,攻击范围大,可攻击多个目标'
            }
        };
        
        // 敌人配置
        const enemyTypes = {
            basic: {
                name: '普通敌人',
                health: 100,
                speed: 1,
                reward: 10,
                color: '#e74c3c',
                size: 20
            },
            fast: {
                name: '快速敌人',
                health: 50,
                speed: 2,
                reward: 15,
                color: '#9b59b6',
                size: 15
            },
            tank: {
                name: '坦克敌人',
                health: 300,
                speed: 0.5,
                reward: 30,
                color: '#8e44ad',
                size: 30
            }
        };
        
        // 天气效果配置
        const weatherEffects = {
            sunny: {
                name: '晴天',
                effect: '无特殊效果',
                towerModifier: { range: 1, damage: 1, fireRate: 1 },
                enemyModifier: { speed: 1, health: 1 }
            },
            rainy: {
                name: '雨天',
                effect: '减慢敌人速度,降低塔攻击范围',
                towerModifier: { range: 0.8, damage: 1, fireRate: 1 },
                enemyModifier: { speed: 0.8, health: 1 }
            },
            snowy: {
                name: '雪天',
                effect: '减慢敌人速度,降低塔攻击速度',
                towerModifier: { range: 1, damage: 1, fireRate: 0.8 },
                enemyModifier: { speed: 0.7, health: 1.1 }
            }
        };
        
        // 游戏路径点
        const pathPoints = [
            { x: 0, y: 300 },
            { x: 200, y: 300 },
            { x: 200, y: 150 },
            { x: 400, y: 150 },
            { x: 400, y: 450 },
            { x: 600, y: 450 },
            { x: 600, y: 150 },
            { x: 800, y: 150 },
            { x: 800, y: 300 },
            { x: 1000, y: 300 },
            { x: 1000, y: 450 },
            { x: 1200, y: 450 }
        ];
        
        // 获取DOM元素
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const goldDisplay = document.getElementById('gold');
        const livesDisplay = document.getElementById('lives');
        const waveDisplay = document.getElementById('wave');
        const startWaveBtn = document.getElementById('startWave');
        const pauseGameBtn = document.getElementById('pauseGame');
        const restartGameBtn = document.getElementById('restartGame');
        const gameSpeedSlider = document.getElementById('gameSpeed');
        const speedValueDisplay = document.getElementById('speedValue');
        const weatherStatusDisplay = document.getElementById('weatherStatus');
        const weatherEffectDisplay = document.getElementById('weatherEffect');
        const enemiesKilledDisplay = document.getElementById('enemiesKilled');
        const towersBuiltDisplay = document.getElementById('towersBuilt');
        const gameTimeDisplay = document.getElementById('gameTime');
        const gameOverScreen = document.getElementById('gameOver');
        const gameOverTitle = document.getElementById('gameOverTitle');
        const gameOverMessage = document.getElementById('gameOverMessage');
        const finalWaveDisplay = document.getElementById('finalWave');
        const finalEnemiesKilledDisplay = document.getElementById('finalEnemiesKilled');
        const finalTowersBuiltDisplay = document.getElementById('finalTowersBuilt');
        const playAgainBtn = document.getElementById('playAgain');
        const towerButtons = document.querySelectorAll('.tower-btn');
        
        // 初始化画布
        function initCanvas() {
            canvas.width = CANVAS_WIDTH;
            canvas.height = CANVAS_HEIGHT;
            
            // 设置画布大小以匹配容器
            function resizeCanvas() {
                const container = canvas.parentElement;
                canvas.style.width = container.clientWidth + 'px';
                canvas.style.height = container.clientHeight + 'px';
            }
            
            resizeCanvas();
            window.addEventListener('resize', resizeCanvas);
        }
        
        // 初始化游戏
        function initGame() {
            initCanvas();
            setupEventListeners();
            startGameTimer();
            updateWeatherDisplay();
            gameLoop();
        }
        
        // 设置事件监听器
        function setupEventListeners() {
            // 塔选择按钮
            towerButtons.forEach(button => {
                button.addEventListener('click', () => {
                    const towerType = button.getAttribute('data-tower-type');
                    selectTowerType(towerType);
                });
            });
            
            // 画布点击事件 - 放置塔
            canvas.addEventListener('click', handleCanvasClick);
            
            // 开始波次按钮
            startWaveBtn.addEventListener('click', startWave);
            
            // 暂停/继续游戏按钮
            pauseGameBtn.addEventListener('click', togglePause);
            
            // 重新开始按钮
            restartGameBtn.addEventListener('click', restartGame);
            
            // 游戏速度滑块
            gameSpeedSlider.addEventListener('input', updateGameSpeed);
            
            // 再玩一次按钮
            playAgainBtn.addEventListener('click', restartGame);
        }
        
        // 选择塔类型
        function selectTowerType(type) {
            gameState.selectedTowerType = type;
            
            // 更新UI显示选中状态
            towerButtons.forEach(btn => {
                if (btn.getAttribute('data-tower-type') === type) {
                    btn.classList.add('ring-2', 'ring-white');
                } else {
                    btn.classList.remove('ring-2', 'ring-white');
                }
            });
        }
        
        // 处理画布点击事件
        function handleCanvasClick(event) {
            if (gameState.isPaused || gameState.gameOver) return;
            
            const rect = canvas.getBoundingClientRect();
            const x = (event.clientX - rect.left) * (canvas.width / rect.width);
            const y = (event.clientY - rect.top) * (canvas.height / rect.height);
            
            // 如果选择了塔类型,尝试放置塔
            if (gameState.selectedTowerType) {
                placeTower(x, y);
            }
        }
        
        // 放置塔
        function placeTower(x, y) {
            const towerType = gameState.selectedTowerType;
            const towerConfig = towerTypes[towerType];
            
            // 检查是否有足够的金币
            if (gameState.gold < towerConfig.cost) {
                showNotification('金币不足!', 'error');
                return;
            }
            
            // 检查位置是否有效(不在路径上,不与其他塔重叠)
            if (!isValidTowerPosition(x, y)) {
                showNotification('无法在此位置建造塔!', 'error');
                return;
            }
            
            // 创建新塔
            const newTower = {
                type: towerType,
                x: x,
                y: y,
                lastFired: 0,
                target: null,
                ...towerConfig
            };
            
            // 应用天气效果
            applyWeatherEffectsToTower(newTower);
            
            // 添加到塔列表
            gameState.towers.push(newTower);
            
            // 扣除金币
            gameState.gold -= towerConfig.cost;
            
            // 更新统计
            gameState.towersBuilt++;
            
            // 更新UI
            updateUI();
            
            showNotification(`建造了 ${towerConfig.name}!`, 'success');
        }
        
        // 检查塔位置是否有效
        function isValidTowerPosition(x, y) {
            // 检查是否在路径上
            if (isPointOnPath(x, y)) {
                return false;
            }
            
            // 检查是否与其他塔重叠
            for (const tower of gameState.towers) {
                const distance = Math.sqrt(Math.pow(x - tower.x, 2) + Math.pow(y - tower.y, 2));
                if (distance < 40) { // 塔的半径
                    return false;
                }
            }
            
            return true;
        }
        
        // 检查点是否在路径上
        function isPointOnPath(x, y) {
            // 简化版:检查点是否靠近路径点之间的线段
            for (let i = 0; i < pathPoints.length - 1; i++) {
                const p1 = pathPoints[i];
                const p2 = pathPoints[i + 1];
                
                // 检查点到线段的距离
                const distance = distancePointToLine(x, y, p1.x, p1.y, p2.x, p2.y);
                if (distance < 30) { // 路径宽度
                    return true;
                }
            }
            
            return false;
        }
        
        // 计算点到线段的距离
        function distancePointToLine(x, y, x1, y1, x2, y2) {
            const A = x - x1;
            const B = y - y1;
            const C = x2 - x1;
            const D = y2 - y1;
            
            const dot = A * C + B * D;
            const lenSq = C * C + D * D;
            let param = -1;
            
            if (lenSq !== 0) {
                param = dot / lenSq;
            }
            
            let xx, yy;
            
            if (param < 0) {
                xx = x1;
                yy = y1;
            } else if (param > 1) {
                xx = x2;
                yy = y2;
            } else {
                xx = x1 + param * C;
                yy = y1 + param * D;
            }
            
            const dx = x - xx;
            const dy = y - yy;
            
            return Math.sqrt(dx * dx + dy * dy);
        }
        
        // 开始新波次
        function startWave() {
            if (gameState.isWaveActive || gameState.isPaused || gameState.gameOver) return;
            
            gameState.isWaveActive = true;
            gameState.waveEnemies = 0;
            gameState.waveEnemiesSpawned = 0;
            gameState.waveEnemyLimit = 10 + (gameState.wave * 2); // 每波增加2个敌人
            gameState.waveSpawnTimer = 0;
            
            // 显示波次通知
            showWaveNotification(`第 ${gameState.wave} 波`);
            
            // 更新按钮状态
            startWaveBtn.disabled = true;
            startWaveBtn.classList.add('opacity-50', 'cursor-not-allowed');
            
            // 随机改变天气
            if (Math.random() < 0.3) { // 30% 几率改变天气
                const weathers = ['sunny', 'rainy', 'snowy'];
                gameState.weather = weathers[Math.floor(Math.random() * weathers.length)];
                updateWeatherDisplay();
            }
        }
        
        // 生成敌人
        function spawnEnemy() {
            if (gameState.waveEnemiesSpawned >= gameState.waveEnemyLimit) return;
            
            // 根据波次决定敌人类型
            let enemyType = 'basic';
            const rand = Math.random();
            
            if (gameState.wave >= 3 && rand < 0.3) {
                enemyType = 'fast';
            } else if (gameState.wave >= 5 && rand < 0.2) {
                enemyType = 'tank';
            }
            
            const enemyConfig = enemyTypes[enemyType];
            
            // 创建新敌人
            const newEnemy = {
                type: enemyType,
                x: pathPoints[0].x,
                y: pathPoints[0].y,
                health: enemyConfig.health,
                maxHealth: enemyConfig.health,
                speed: enemyConfig.speed,
                reward: enemyConfig.reward,
                pathIndex: 0,
                ...enemyConfig
            };
            
            // 应用天气效果
            applyWeatherEffectsToEnemy(newEnemy);
            
            // 添加到敌人列表
            gameState.enemies.push(newEnemy);
            
            gameState.waveEnemiesSpawned++;
        }
        
        // 应用天气效果到塔
        function applyWeatherEffectsToTower(tower) {
            const weatherEffect = weatherEffects[gameState.weather];
            
            // 应用修改器
            tower.range *= weatherEffect.towerModifier.range;
            tower.damage *= weatherEffect.towerModifier.damage;
            tower.fireRate *= weatherEffect.towerModifier.fireRate;
        }
        
        // 应用天气效果到敌人
        function applyWeatherEffectsToEnemy(enemy) {
            const weatherEffect = weatherEffects[gameState.weather];
            
            // 应用修改器
            enemy.speed *= weatherEffect.enemyModifier.speed;
            enemy.health *= weatherEffect.enemyModifier.health;
            enemy.maxHealth = enemy.health; // 更新最大生命值
        }
        
        // 更新天气显示
        function updateWeatherDisplay() {
            const weatherEffect = weatherEffects[gameState.weather];
            weatherStatusDisplay.textContent = weatherEffect.name;
            weatherEffectDisplay.textContent = weatherEffect.effect;
            
            // 更新天气覆盖层
            const weatherOverlay = document.getElementById('weatherOverlay');
            weatherOverlay.className = 'weather-overlay';
            
            if (gameState.weather === 'rainy') {
                weatherOverlay.classList.add('rain-effect');
            } else if (gameState.weather === 'snowy') {
                weatherOverlay.classList.add('snow-effect');
            }
        }
        
        // 塔攻击逻辑
        function towerAttack(tower, currentTime) {
            // 检查是否可以开火
            if (currentTime - tower.lastFired < tower.fireRate) return;
            
            // 寻找目标
            const target = findTarget(tower);
            if (!target) return;
            
            // 创建投射物
            createProjectile(tower, target);
            
            // 更新最后开火时间
            tower.lastFired = currentTime;
        }
        
        // 寻找目标
        function findTarget(tower) {
            let closestEnemy = null;
            let minDistance = Infinity;
            
            for (const enemy of gameState.enemies) {
                const distance = Math.sqrt(Math.pow(tower.x - enemy.x, 2) + Math.pow(tower.y - enemy.y, 2));
                
                if (distance <= tower.range && distance < minDistance) {
                    closestEnemy = enemy;
                    minDistance = distance;
                }
            }
            
            return closestEnemy;
        }
        
        // 创建投射物
        function createProjectile(tower, target) {
            const projectile = {
                x: tower.x,
                y: tower.y,
                targetX: target.x,
                targetY: target.y,
                target: target,
                damage: tower.damage,
                speed: tower.projectileSpeed,
                color: tower.projectileColor,
                type: tower.type,
                splashRadius: tower.splashRadius || 0,
                chainTargets: tower.chainTargets || 0
            };
            
            gameState.projectiles.push(projectile);
        }
        
        // 更新投射物
        function updateProjectiles(deltaTime) {
            for (let i = gameState.projectiles.length - 1; i >= 0; i--) {
                const projectile = gameState.projectiles[i];
                
                // 检查目标是否仍然存在
                if (!gameState.enemies.includes(projectile.target)) {
                    gameState.projectiles.splice(i, 1);
                    continue;
                }
                
                // 计算方向
                const dx = projectile.targetX - projectile.x;
                const dy = projectile.targetY - projectile.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                // 标准化方向向量
                const dirX = dx / distance;
                const dirY = dy / distance;
                
                // 移动投射物
                projectile.x += dirX * projectile.speed * gameState.gameSpeed;
                projectile.y += dirY * projectile.speed * gameState.gameSpeed;
                
                // 检查是否击中目标
                const newDistance = Math.sqrt(
                    Math.pow(projectile.targetX - projectile.x, 2) + 
                    Math.pow(projectile.targetY - projectile.y, 2)
                );
                
                if (newDistance < 10) {
                    // 处理击中
                    handleProjectileHit(projectile);
                    
                    // 移除投射物
                    gameState.projectiles.splice(i, 1);
                }
            }
        }
        
        // 处理投射物击中
        function handleProjectileHit(projectile) {
            // 创建爆炸效果
            createExplosion(projectile.targetX, projectile.targetY, projectile.color);
            
            // 根据投射物类型处理伤害
            if (projectile.type === 'explosive' && projectile.splashRadius > 0) {
                // 范围伤害
                for (const enemy of gameState.enemies) {
                    const distance = Math.sqrt(
                        Math.pow(enemy.x - projectile.targetX, 2) + 
                        Math.pow(enemy.y - projectile.targetY, 2)
                    );
                    
                    if (distance <= projectile.splashRadius) {
                        damageEnemy(enemy, projectile.damage);
                    }
                }
            } else if (projectile.type === 'electric' && projectile.chainTargets > 0) {
                // 链式伤害
                let currentTarget = projectile.target;
                let remainingChains = projectile.chainTargets;
                
                // 伤害初始目标
                damageEnemy(currentTarget, projectile.damage);
                
                // 寻找链式目标
                while (remainingChains > 0) {
                    let nextTarget = null;
                    let minDistance = Infinity;
                    
                    for (const enemy of gameState.enemies) {
                        if (enemy === currentTarget || enemy.health <= 0) continue;
                        
                        const distance = Math.sqrt(
                            Math.pow(enemy.x - currentTarget.x, 2) + 
                            Math.pow(enemy.y - currentTarget.y, 2)
                        );
                        
                        if (distance < 100 && distance < minDistance) { // 链击范围
                            nextTarget = enemy;
                            minDistance = distance;
                        }
                    }
                    
                    if (nextTarget) {
                        // 创建链式闪电效果
                        createLightning(currentTarget.x, currentTarget.y, nextTarget.x, nextTarget.y);
                        
                        // 伤害链式目标(伤害递减)
                        const chainDamage = projectile.damage * (0.7 * remainingChains / projectile.chainTargets);
                        damageEnemy(nextTarget, chainDamage);
                        
                        currentTarget = nextTarget;
                        remainingChains--;
                    } else {
                        break;
                    }
                }
            } else {
                // 普通伤害
                damageEnemy(projectile.target, projectile.damage);
            }
        }
        
        // 创建爆炸效果
        function createExplosion(x, y, color) {
            const explosion = {
                x: x,
                y: y,
                color: color || '#F44336',
                startTime: Date.now(),
                duration: 500 // 毫秒
            };
            
            gameState.explosions.push(explosion);
        }
        
        // 创建闪电效果
        function createLightning(x1, y1, x2, y2) {
            // 这个函数可以创建闪电效果的视觉元素
            // 为了简化,我们可以使用爆炸效果来模拟
            createExplosion((x1 + x2) / 2, (y1 + y2) / 2, '#FFEB3B');
        }
        
        // 伤害敌人
        function damageEnemy(enemy, damage) {
            enemy.health -= damage;
            
            // 检查敌人是否死亡
            if (enemy.health <= 0) {
                killEnemy(enemy);
            }
        }
        
        // 杀死敌人
        function killEnemy(enemy) {
            // 添加金币奖励
            gameState.gold += enemy.reward;
            
            // 更新统计
            gameState.enemiesKilled++;
            gameState.waveEnemies++;
            
            // 创建爆炸效果
            createExplosion(enemy.x, enemy.y);
            
            // 从敌人列表中移除
            const index = gameState.enemies.indexOf(enemy);
            if (index !== -1) {
                gameState.enemies.splice(index, 1);
            }
            
            // 更新UI
            updateUI();
            
            // 检查波次是否结束
            checkWaveEnd();
        }
        
        // 更新敌人位置
        function updateEnemies(deltaTime) {
            for (let i = gameState.enemies.length - 1; i >= 0; i--) {
                const enemy = gameState.enemies[i];
                
                // 检查是否到达路径终点
                if (enemy.pathIndex >= pathPoints.length - 1) {
                    // 敌人到达终点,减少生命值
                    gameState.lives--;
                    
                    // 从敌人列表中移除
                    gameState.enemies.splice(i, 1);
                    
                    // 更新UI
                    updateUI();
                    
                    // 检查游戏是否结束
                    checkGameOver();
                    
                    continue;
                }
                
                // 获取下一个路径点
                const nextPoint = pathPoints[enemy.pathIndex + 1];
                
                // 计算方向
                const dx = nextPoint.x - enemy.x;
                const dy = nextPoint.y - enemy.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                // 如果接近下一个点,更新路径索引
                if (distance < 10) {
                    enemy.pathIndex++;
                    continue;
                }
                
                // 标准化方向向量
                const dirX = dx / distance;
                const dirY = dy / distance;
                
                // 移动敌人
                enemy.x += dirX * enemy.speed * gameState.gameSpeed;
                enemy.y += dirY * enemy.speed * gameState.gameSpeed;
                
                // 更新目标位置(用于投射物追踪)
                if (enemy.pathIndex + 1 < pathPoints.length) {
                    const nextPathPoint = pathPoints[enemy.pathIndex + 1];
                    enemy.targetX = nextPathPoint.x;
                    enemy.targetY = nextPathPoint.y;
                }
            }
        }
        
        // 检查波次是否结束
        function checkWaveEnd() {
            if (gameState.waveEnemies >= gameState.waveEnemyLimit && gameState.enemies.length === 0) {
                // 波次结束
                gameState.isWaveActive = false;
                gameState.wave++;
                
                // 更新按钮状态
                startWaveBtn.disabled = false;
                startWaveBtn.classList.remove('opacity-50', 'cursor-not-allowed');
                
                // 显示通知
                showNotification(`第 ${gameState.wave - 1} 波完成! 准备第 ${gameState.wave} 波...`, 'success');
                
                // 更新UI
                updateUI();
            }
        }
        
        // 检查游戏是否结束
        function checkGameOver() {
            if (gameState.lives <= 0) {
                endGame(false); // 失败
            } else if (gameState.wave > 20) {
                endGame(true); // 胜利
            }
        }
        
        // 结束游戏
        function endGame(isVictory) {
            gameState.gameOver = true;
            gameState.isPaused = true;
            
            // 停止游戏计时器
            stopGameTimer();
            
            // 显示游戏结束界面
            gameOverScreen.classList.remove('hidden');
            
            if (isVictory) {
                gameOverTitle.textContent = '胜利!';
                gameOverMessage.textContent = '你成功阻止了所有敌人的进攻!';
            } else {
                gameOverTitle.textContent = '游戏结束';
                gameOverMessage.textContent = '敌人突破了你的防线!';
            }
            
            // 更新最终统计
            finalWaveDisplay.textContent = gameState.wave;
            finalEnemiesKilledDisplay.textContent = gameState.enemiesKilled;
            finalTowersBuiltDisplay.textContent = gameState.towersBuilt;
        }
        
        // 暂停/继续游戏
        function togglePause() {
            if (gameState.gameOver) return;
            
            gameState.isPaused = !gameState.isPaused;
            
            if (gameState.isPaused) {
                pauseGameBtn.innerHTML = '<i class="fa fa-play mr-2"></i> 继续';
                pauseGameBtn.classList.remove('bg-info', 'hover:bg-blue-600');
                pauseGameBtn.classList.add('bg-success', 'hover:bg-green-600');
                
                // 停止游戏计时器
                stopGameTimer();
            } else {
                pauseGameBtn.innerHTML = '<i class="fa fa-pause mr-2"></i> 暂停';
                pauseGameBtn.classList.remove('bg-success', 'hover:bg-green-600');
                pauseGameBtn.classList.add('bg-info', 'hover:bg-blue-600');
                
                // 重启游戏计时器
                startGameTimer();
            }
        }
        
        // 重新开始游戏
        function restartGame() {
            // 重置游戏状态
            gameState = {
                gold: 500,
                lives: 20,
                wave: 1,
                gameSpeed: 1,
                isPaused: false,
                isWaveActive: false,
                selectedTowerType: null,
                towers: [],
                enemies: [],
                projectiles: [],
                explosions: [],
                weather: 'sunny',
                enemiesKilled: 0,
                towersBuilt: 0,
                gameTime: 0,
                gameTimeInterval: null,
                lastUpdateTime: 0,
                waveEnemies: 0,
                waveEnemiesSpawned: 0,
                waveEnemyLimit: 10,
                waveSpawnTimer: 0,
                waveSpawnInterval: 1000,
                gameOver: false
            };
            
            // 重置UI
            gameSpeedSlider.value = 1;
            speedValueDisplay.textContent = '1x';
            pauseGameBtn.innerHTML = '<i class="fa fa-pause mr-2"></i> 暂停';
            pauseGameBtn.classList.remove('bg-success', 'hover:bg-green-600');
            pauseGameBtn.classList.add('bg-info', 'hover:bg-blue-600');
            startWaveBtn.disabled = false;
            startWaveBtn.classList.remove('opacity-50', 'cursor-not-allowed');
            gameOverScreen.classList.add('hidden');
            
            // 清除塔选择
            towerButtons.forEach(btn => {
                btn.classList.remove('ring-2', 'ring-white');
            });
            
            // 更新UI
            updateUI();
            
            // 重启游戏计时器
            startGameTimer();
            
            // 更新天气显示
            updateWeatherDisplay();
            
            showNotification('游戏已重置!', 'info');
        }
        
        // 更新游戏速度
        function updateGameSpeed() {
            gameState.gameSpeed = parseFloat(gameSpeedSlider.value);
            speedValueDisplay.textContent = gameState.gameSpeed + 'x';
        }
        
        // 开始游戏计时器
        function startGameTimer() {
            if (gameState.gameTimeInterval) return;
            
            gameState.gameTimeInterval = setInterval(() => {
                if (!gameState.isPaused && !gameState.gameOver) {
                    gameState.gameTime++;
                    updateGameTimeDisplay();
                }
            }, 1000);
        }
        
        // 停止游戏计时器
        function stopGameTimer() {
            if (gameState.gameTimeInterval) {
                clearInterval(gameState.gameTimeInterval);
                gameState.gameTimeInterval = null;
            }
        }
        
        // 更新游戏时间显示
        function updateGameTimeDisplay() {
            const minutes = Math.floor(gameState.gameTime / 60);
            const seconds = gameState.gameTime % 60;
            gameTimeDisplay.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
        }
        
        // 显示波次通知
        function showWaveNotification(message) {
            const notification = document.createElement('div');
            notification.className = 'wave-notification';
            notification.textContent = message;
            
            document.body.appendChild(notification);
            
            // 2秒后移除
            setTimeout(() => {
                notification.remove();
            }, 2000);
        }
        
        // 显示通知
        function showNotification(message, type = 'info') {
            const notification = document.createElement('div');
            notification.className = 'fixed top-4 right-4 p-4 rounded-lg shadow-lg z-50 transition-all transform translate-x-full opacity-0';
            
            // 设置颜色
            switch (type) {
                case 'success':
                    notification.classList.add('bg-green-500');
                    break;
                case 'error':
                    notification.classList.add('bg-red-500');
                    break;
                case 'warning':
                    notification.classList.add('bg-yellow-500');
                    break;
                default:
                    notification.classList.add('bg-blue-500');
            }
            
            notification.textContent = message;
            document.body.appendChild(notification);
            
            // 显示动画
            setTimeout(() => {
                notification.classList.remove('translate-x-full', 'opacity-0');
            }, 10);
            
            // 3秒后隐藏
            setTimeout(() => {
                notification.classList.add('translate-x-full', 'opacity-0');
                
                // 移除元素
                setTimeout(() => {
                    notification.remove();
                }, 300);
            }, 3000);
        }
        
        // 更新UI
        function updateUI() {
            goldDisplay.textContent = gameState.gold;
            livesDisplay.textContent = gameState.lives;
            waveDisplay.textContent = gameState.wave;
            enemiesKilledDisplay.textContent = gameState.enemiesKilled;
            towersBuiltDisplay.textContent = gameState.towersBuilt;
        }
        
        // 绘制游戏
        function drawGame() {
            // 清除画布
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            
            // 绘制网格
            drawGrid();
            
            // 绘制路径
            drawPath();
            
            // 绘制塔
            drawTowers();
            
            // 绘制敌人
            drawEnemies();
            
            // 绘制投射物
            drawProjectiles();
            
            // 绘制爆炸效果
            drawExplosions();
            
            // 绘制塔范围指示器(如果有选中的塔类型)
            if (gameState.selectedTowerType) {
                drawRangeIndicator();
            }
        }
        
        // 绘制网格
        function drawGrid() {
            ctx.strokeStyle = 'rgba(255, 255, 255, 0.1)';
            ctx.lineWidth = 1;
            
            // 绘制垂直线
            for (let x = 0; x <= canvas.width; x += GRID_SIZE) {
                ctx.beginPath();
                ctx.moveTo(x, 0);
                ctx.lineTo(x, canvas.height);
                ctx.stroke();
            }
            
            // 绘制水平线
            for (let y = 0; y <= canvas.height; y += GRID_SIZE) {
                ctx.beginPath();
                ctx.moveTo(0, y);
                ctx.lineTo(canvas.width, y);
                ctx.stroke();
            }
        }
        
        // 绘制路径
        function drawPath() {
            ctx.strokeStyle = PATH_COLOR;
            ctx.lineWidth = 40;
            ctx.lineCap = 'round';
            ctx.lineJoin = 'round';
            
            ctx.beginPath();
            ctx.moveTo(pathPoints[0].x, pathPoints[0].y);
            
            for (let i = 1; i < pathPoints.length; i++) {
                ctx.lineTo(pathPoints[i].x, pathPoints[i].y);
            }
            
            ctx.stroke();
            
            // 绘制路径点
            ctx.fillStyle = '#7f8c8d';
            for (const point of pathPoints) {
                ctx.beginPath();
                ctx.arc(point.x, point.y, 5, 0, Math.PI * 2);
                ctx.fill();
            }
        }
        
        // 绘制塔
        function drawTowers() {
            for (const tower of gameState.towers) {
                // 绘制塔基
                ctx.fillStyle = tower.color;
                ctx.beginPath();
                ctx.arc(tower.x, tower.y, 20, 0, Math.PI * 2);
                ctx.fill();
                
                // 绘制塔图标
                ctx.fillStyle = 'white';
                ctx.font = '16px Arial';
                ctx.textAlign = 'center';
                ctx.textBaseline = 'middle';
                
                let icon = '⚡';
                if (tower.type === 'basic') icon = '🔴';
                else if (tower.type === 'explosive') icon = '💣';
                
                ctx.fillText(icon, tower.x, tower.y);
                
                // 绘制攻击范围(可选)
                // ctx.strokeStyle = 'rgba(255, 255, 255, 0.2)';
                // ctx.beginPath();
                // ctx.arc(tower.x, tower.y, tower.range, 0, Math.PI * 2);
                // ctx.stroke();
            }
        }
        
        // 绘制敌人
        function drawEnemies() {
            for (const enemy of gameState.enemies) {
                // 绘制生命值条
                const healthPercent = enemy.health / enemy.maxHealth;
                const barWidth = enemy.size * 2;
                const barHeight = 4;
                
                ctx.fillStyle = '#e74c3c';
                ctx.fillRect(enemy.x - barWidth / 2, enemy.y - enemy.size - 10, barWidth, barHeight);
                
                ctx.fillStyle = '#2ecc71';
                ctx.fillRect(enemy.x - barWidth / 2, enemy.y - enemy.size - 10, barWidth * healthPercent, barHeight);
                
                // 绘制敌人
                ctx.fillStyle = enemy.color;
                ctx.beginPath();
                ctx.arc(enemy.x, enemy.y, enemy.size, 0, Math.PI * 2);
                ctx.fill();
                
                // 绘制敌人边框
                ctx.strokeStyle = 'rgba(0, 0, 0, 0.5)';
                ctx.lineWidth = 2;
                ctx.stroke();
            }
        }
        
        // 绘制投射物
        function drawProjectiles() {
            for (const projectile of gameState.projectiles) {
                ctx.fillStyle = projectile.color;
                ctx.beginPath();
                ctx.arc(projectile.x, projectile.y, 4, 0, Math.PI * 2);
                ctx.fill();
            }
        }
        
        // 绘制爆炸效果
        function drawExplosions() {
            const currentTime = Date.now();
            
            for (let i = gameState.explosions.length - 1; i >= 0; i--) {
                const explosion = gameState.explosions[i];
                const elapsed = currentTime - explosion.startTime;
                const progress = elapsed / explosion.duration;
                
                if (progress >= 1) {
                    // 爆炸效果结束,移除
                    gameState.explosions.splice(i, 1);
                    continue;
                }
                
                // 绘制爆炸
                const radius = 50 * progress;
                const alpha = 1 - progress;
                
                ctx.fillStyle = `rgba(255, 255, 255, ${alpha * 0.5})`;
                ctx.beginPath();
                ctx.arc(explosion.x, explosion.y, radius, 0, Math.PI * 2);
                ctx.fill();
                
                ctx.strokeStyle = `rgba(255, 193, 7, ${alpha})`;
                ctx.lineWidth = 3;
                ctx.beginPath();
                ctx.arc(explosion.x, explosion.y, radius * 0.7, 0, Math.PI * 2);
                ctx.stroke();
            }
        }
        
        // 绘制范围指示器
        function drawRangeIndicator() {
            // 获取鼠标位置
            const rect = canvas.getBoundingClientRect();
            const mouseX = (mousePos.x - rect.left) * (canvas.width / rect.width);
            const mouseY = (mousePos.y - rect.top) * (canvas.height / rect.height);
            
            const towerConfig = towerTypes[gameState.selectedTowerType];
            
            // 检查位置是否有效
            const isValid = isValidTowerPosition(mouseX, mouseY);
            
            // 绘制范围指示器
            ctx.strokeStyle = isValid ? 'rgba(46, 204, 113, 0.5)' : 'rgba(231, 76, 60, 0.5)';
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.arc(mouseX, mouseY, towerConfig.range, 0, Math.PI * 2);
            ctx.stroke();
            
            // 绘制塔预览
            ctx.fillStyle = isValid ? towerConfig.color : 'rgba(231, 76, 60, 0.7)';
            ctx.beginPath();
            ctx.arc(mouseX, mouseY, 20, 0, Math.PI * 2);
            ctx.fill();
            
            // 绘制塔图标
            ctx.fillStyle = 'white';
            ctx.font = '16px Arial';
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            
            let icon = '⚡';
            if (gameState.selectedTowerType === 'basic') icon = '🔴';
            else if (gameState.selectedTowerType === 'explosive') icon = '💣';
            
            ctx.fillText(icon, mouseX, mouseY);
        }
        
        // 跟踪鼠标位置
        const mousePos = { x: 0, y: 0 };
        canvas.addEventListener('mousemove', (event) => {
            mousePos.x = event.clientX;
            mousePos.y = event.clientY;
        });
        
        // 游戏主循环
        function gameLoop(timestamp) {
            if (!gameState.lastUpdateTime) {
                gameState.lastUpdateTime = timestamp;
            }
            
            const deltaTime = timestamp - gameState.lastUpdateTime;
            gameState.lastUpdateTime = timestamp;
            
            if (!gameState.isPaused && !gameState.gameOver) {
                // 更新游戏状态
                updateGame(deltaTime);
            }
            
            // 绘制游戏
            drawGame();
            
            // 继续游戏循环
            requestAnimationFrame(gameLoop);
        }
        
        // 更新游戏状态
        function updateGame(deltaTime) {
            // 更新波次生成
            if (gameState.isWaveActive) {
                gameState.waveSpawnTimer += deltaTime;
                
                if (gameState.waveSpawnTimer >= gameState.waveSpawnInterval) {
                    spawnEnemy();
                    gameState.waveSpawnTimer = 0;
                }
            }
            
            // 更新塔攻击
            const currentTime = Date.now();
            for (const tower of gameState.towers) {
                towerAttack(tower, currentTime);
            }
            
            // 更新投射物
            updateProjectiles(deltaTime);
            
            // 更新敌人
            updateEnemies(deltaTime);
        }
        
        // 初始化游戏
        window.onload = initGame;
    </script>
</body>
</html>
原文