星际战斗, Trae 一句话生成的宇宙射击爽游

说到"星际战斗",脑子里立刻浮现的是经典的 ​太空射击街机 ​:玩家驾驶一架小飞船,在星空中来回穿梭,​一边射击来袭的敌机,一边收集武器升级道具 ​。 如果是过去,要写这样一个游戏,得搞定一堆东西:​飞船移动控制、子弹发射逻辑、敌机生成与 AI、碰撞检测、道具掉落​,每一步都挺烧时间。

但现在,用 ​Trae IDE​,一句话就能让一个完整的太空射击游戏出现在你面前。

💡 我想要的玩法

脑子里的构想其实很直白:

  • 飞船能飞:玩家用键盘方向键控制飞船上下左右移动;
  • 能发射激光:按空格射出子弹,干掉敌人;
  • 敌人随机来袭:小型敌机、BOSS 轮番登场,挑战不断;
  • 道具掉落:有时打掉敌机会掉下道具,可以升级子弹或补充护盾;
  • 背景是星空:黑色宇宙背景,点缀星星,让游戏更有氛围。

我直接在 Trae 输入了:

"生成一个太空飞行射击游戏,玩家控制飞船射击敌人并收集道具。"

✨ Trae 怎么"秒懂"

不到十秒钟,Trae 就生成了一个​**完整能玩的"星际战斗"**​:

✅ ​飞船控制流畅 ​:上下左右随意移动,操作顺滑,没有延迟感。 ✅ ​射击逻辑完善 ​:子弹发射、击中敌机后消失,打击感很足。 ✅ ​敌人生成系统 ​:小敌机随机刷新,还能设定 Boss 关卡。 ✅ ​道具与升级 ​:敌机偶尔掉落加速、三连发或护盾道具,玩法更丰富。 ✅ ​宇宙背景动画​:星空慢慢流动,让画面有种"正在飞行"的感觉。

🧩 试玩感受

我一上手就停不下来:

🚀 ​第一波敌机很简单 ​,轻松消灭拿了几个道具; ⚠ ​后面敌机越来越多 ​,子弹刷屏的那一刻,手指根本停不下来; 🎯 ​打到 Boss 的时候 ​,画面里子弹和激光乱飞,​一边闪避一边输出的紧张感让人上瘾​。

Trae 自动生成的版本,不只是能玩,还真有那味儿。

🛠 想扩展玩法?一句话

Trae 的魅力是------​随时能说点啥,游戏就能变更酷​:

  • "加个连击系统" → 连续击毁敌机会有 Combo 特效和额外得分。
  • "加入双人模式" → 两架飞船并肩作战,合作打 Boss。
  • "让敌机也能发射子弹" → 闪避难度提升,挑战更大。
  • "增加背景星云和陨石带" → 飞行感觉更真实。

只要一句自然语言,Trae 自动补逻辑,无需写一行额外代码。

🎮 开发小游戏的"新姿势"

以前写这种太空射击游戏,开发者得:

  • 飞船控制代码
  • 调整 子弹发射与碰撞检测
  • 设计 敌人 AI 和刷新机制
  • 手工实现 道具系统和背景动画

每个环节都得花心思调试。

现在用 Trae: 👉 ​一句话生成核心玩法 ​; 👉 ​再加几句,就能进化成完整街机级体验​。

开发变成了纯粹的创意输出,​写游戏就像开口聊天一样简单​。

✅ 结语

如果你也想做一款"打飞船爽游",打开 Trae,只要输入:

"生成一个太空飞行射击游戏,玩家控制飞船射击敌人并收集道具。"

几秒后,你就能玩到一个完整的太空战斗游戏:飞船顺滑、射击爽快、敌人够刺激,道具升级让玩法更丰富。

这就是 Trae 的魅力------​开发变得轻松,创意才能尽情释放​。

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>

    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        

        body {
            font-family: 'Arial', sans-serif;
            background-color: #000;
            display: flex;
            justify-content: center;
            align-items: center;

            height: 100vh;
            overflow: hidden;
            color: #fff;
        }
        

        .game-container {
            position: relative;
            width: 800px;
            height: 600px;

            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" width="800" height="600" viewBox="0 0 800 600"><rect width="800" height="600" fill="%23000"/><g fill="%23FFF"><circle cx="50" cy="50" r="1"/><circle cx="150" cy="150" r="1"/><circle cx="350" cy="250" r="1"/><circle cx="250" cy="350" r="1"/><circle cx="450" cy="450" r="1"/><circle cx="550" cy="50" r="1"/><circle cx="650" cy="150" r="1"/><circle cx="750" cy="250" r="1"/><circle cx="50" cy="450" r="1"/><circle cx="150" cy="550" r="1"/><circle cx="250" cy="50" r="1"/><circle cx="350" cy="150" r="1"/><circle cx="450" cy="250" r="1"/><circle cx="550" cy="350" r="1"/><circle cx="650" cy="450" r="1"/><circle cx="750" cy="550" r="1"/><circle cx="100" cy="100" r="0.8"/><circle cx="200" cy="200" r="0.8"/><circle cx="300" cy="300" r="0.8"/><circle cx="400" cy="400" r="0.8"/><circle cx="500" cy="500" r="0.8"/><circle cx="600" cy="100" r="0.8"/><circle cx="700" cy="200" r="0.8"/><circle cx="100" cy="300" r="0.8"/><circle cx="200" cy="400" r="0.8"/><circle cx="300" cy="500" r="0.8"/><circle cx="400" cy="100" r="0.8"/><circle cx="500" cy="200" r="0.8"/><circle cx="600" cy="300" r="0.8"/><circle cx="700" cy="400" r="0.8"/><circle cx="100" cy="500" r="0.8"/></g></svg>');
            border: 2px solid #333;
            border-radius: 10px;
            box-shadow: 0 0 20px rgba(0, 100, 255, 0.5);
            overflow: hidden;
        }

        
        .score-container {
            position: absolute;
            top: 20px;
            left: 20px;
            font-size: 20px;
            color: #fff;
            z-index: 10;

            text-shadow: 0 0 5px #00f, 0 0 10px #00f;
        }
        
        .health-container {
            position: absolute;

            top: 20px;
            right: 20px;

            font-size: 20px;
            color: #fff;

            z-index: 10;
            text-shadow: 0 0 5px #f00, 0 0 10px #f00;
        }
        
        .health-bar {
            display: inline-block;
            width: 150px;
            height: 15px;
            background-color: #333;
            border-radius: 7px;
            margin-left: 10px;
            overflow: hidden;
            vertical-align: middle;
        }
        
        .health-fill {
            height: 100%;
            background: linear-gradient(to right, #f00, #ff0);
            width: 100%;
            transition: width 0.3s;
        }

        
        .player {
            position: absolute;
            width: 50px;
            height: 50px;
            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50"><path d="M25,5 L10,40 L25,30 L40,40 Z" fill="%2300BFFF" stroke="%230080FF" stroke-width="2"/><circle cx="25" cy="20" r="5" fill="%23FFF"/></svg>');
            background-size: contain;
            background-repeat: no-repeat;
            z-index: 5;

        }
        
        .enemy {
            position: absolute;
            background-size: contain;
            background-repeat: no-repeat;
            z-index: 4;

        }
        
        .enemy-1 {
            width: 40px;
            height: 40px;
            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><path d="M20,5 L5,20 L20,35 L35,20 Z" fill="%23FF4500" stroke="%23FF0000" stroke-width="2"/><circle cx="20" cy="20" r="5" fill="%23FFF"/></svg>');
        }
        
        .enemy-2 {
            width: 50px;
            height: 50px;
            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50"><path d="M10,10 L40,10 L40,40 L10,40 Z" fill="%23FF00FF" stroke="%23800080" stroke-width="2"/><circle cx="25" cy="25" r="7" fill="%23FFF"/></svg>');
        }
        
        .enemy-3 {
            width: 60px;
            height: 60px;
            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 60 60"><circle cx="30" cy="30" r="25" fill="%2300FF00" stroke="%23008000" stroke-width="2"/><circle cx="20" cy="20" r="5" fill="%23FFF"/><circle cx="40" cy="20" r="5" fill="%23FFF"/><path d="M20,40 Q30,50 40,40" stroke="%23000" stroke-width="2" fill="none"/></svg>');

        }
        
        .bullet {
            position: absolute;
            width: 5px;
            height: 15px;
            background-color: #0ff;
            border-radius: 2.5px;
            z-index: 3;
            box-shadow: 0 0 5px #0ff, 0 0 10px #0ff;
        }
        
        .enemy-bullet {
            position: absolute;
            width: 5px;
            height: 15px;

            background-color: #f00;
            border-radius: 2.5px;
            z-index: 3;
            box-shadow: 0 0 5px #f00, 0 0 10px #f00;
        }
        
        .powerup {

            position: absolute;
            width: 30px;
            height: 30px;
            z-index: 4;
            animation: rotate 3s linear infinite;
        }
        
        @keyframes rotate {
            from { transform: rotate(0deg); }
            to { transform: rotate(360deg); }
        }
        
        .powerup-health {
            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 30 30"><circle cx="15" cy="15" r="13" fill="%23FF0000" stroke="%23FFFFFF" stroke-width="2"/><rect x="7" y="13" width="16" height="4" fill="%23FFFFFF"/><rect x="13" y="7" width="4" height="16" fill="%23FFFFFF"/></svg>');
        }
        
        .powerup-shield {
            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 30 30"><circle cx="15" cy="15" r="13" fill="%230000FF" stroke="%23FFFFFF" stroke-width="2"/><path d="M15,5 L25,10 L25,20 L15,25 L5,20 L5,10 Z" fill="%230000AA" stroke="%23FFFFFF" stroke-width="1"/></svg>');
        }
        
        .powerup-weapon {
            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 30 30"><circle cx="15" cy="15" r="13" fill="%23FFFF00" stroke="%23FFFFFF" stroke-width="2"/><path d="M10,20 L15,5 L20,20 L15,15 Z" fill="%23FFFFFF"/></svg>');

        }
        
        .explosion {
            position: absolute;
            width: 50px;
            height: 50px;
            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 50 50"><circle cx="25" cy="25" r="20" fill="%23FF4500"/><circle cx="25" cy="25" r="15" fill="%23FF7F00"/><circle cx="25" cy="25" r="10" fill="%23FFFF00"/><circle cx="25" cy="25" r="5" fill="%23FFFFFF"/></svg>');
            background-size: contain;

            z-index: 6;
            animation: explode 0.5s forwards;
        }
        
        @keyframes explode {
            0% { transform: scale(0.1); opacity: 1; }
            100% { transform: scale(2); opacity: 0; }
        }
        
        .shield {
            position: absolute;
            width: 70px;
            height: 70px;
            background: url('data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 70 70"><circle cx="35" cy="35" r="30" fill="none" stroke="%2300BFFF" stroke-width="3" stroke-opacity="0.7"/></svg>');
            background-size: contain;
            z-index: 4;
            animation: pulse 2s infinite;
        }
        
        @keyframes pulse {
            0% { transform: scale(1); opacity: 0.7; }
            50% { transform: scale(1.1); opacity: 0.5; }
            100% { transform: scale(1); opacity: 0.7; }
        }

        

        .game-over {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;

            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 20;
            display: none;
        }
        
        .game-over-title {
            font-size: 48px;

            font-weight: bold;
            color: #f00;
            margin-bottom: 20px;
            text-align: center;
            text-shadow: 0 0 10px #f00;
        }
        
        .final-score {
            font-size: 36px;
            color: #fff;
            margin-bottom: 30px;
            text-align: center;
            text-shadow: 0 0 5px #0ff;
        }
        
        .restart-button {
            padding: 15px 30px;
            font-size: 20px;
            font-weight: bold;
            background-color: #00f;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;

            text-shadow: 0 0 5px #fff;
            box-shadow: 0 0 10px #00f;
        }
        
        .restart-button:hover {
            background-color: #00a;
            transform: scale(1.05);
            box-shadow: 0 0 20px #00f;
        }
        
        .start-screen {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.8);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            z-index: 20;
        }
        
        .start-screen-title {
            font-size: 48px;
            font-weight: bold;
            color: #0ff;
            margin-bottom: 20px;
            text-align: center;
            text-shadow: 0 0 10px #0ff;

        }
        
        .start-screen-subtitle {
            font-size: 24px;

            color: #fff;
            margin-bottom: 30px;
            text-align: center;
            max-width: 80%;
            line-height: 1.4;
            text-shadow: 0 0 5px #0ff;
        }
        
        .start-button {

            padding: 15px 30px;

            font-size: 20px;
            font-weight: bold;
            background-color: #00f;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: all 0.3s;
            text-shadow: 0 0 5px #fff;
            box-shadow: 0 0 10px #00f;
        }
        
        .start-button:hover {
            background-color: #00a;
            transform: scale(1.05);

            box-shadow: 0 0 20px #00f;
        }
        
        .level-indicator {
            position: absolute;

            top: 50px;
            left: 20px;
            font-size: 20px;
            color: #fff;
            z-index: 10;
            text-shadow: 0 0 5px #0f0, 0 0 10px #0f0;
        }
    </style>
</head>
<body>

    <div class="game-container" id="game-container">
        <div class="score-container">
            分数: <span id="score">0</span>
        </div>
        

        <div class="health-container">
            生命值: <div class="health-bar"><div class="health-fill" id="health-fill"></div></div>
        </div>
        
        <div class="level-indicator">
            等级: <span id="level">1</span>
        </div>

        
        <div class="player" id="player"></div>
        

        <div class="game-over" id="game-over">
            <div class="game-over-title">游戏结束</div>
            <div class="final-score">最终得分: <span id="final-score">0</span></div>
            <button class="restart-button" id="restart-button">再玩一次</button>
        </div>
        
        <div class="start-screen" id="start-screen">
            <div class="start-screen-title">太空射击游戏</div>
            <div class="start-screen-subtitle">使用方向键移动飞船,空格键发射子弹。收集道具提升能力,击败敌人获得分数。</div>

            <button class="start-button" id="start-button">开始游戏</button>

        </div>
    </div>

    
    <script>
        // 游戏元素
        const gameContainer = document.getElementById('game-container');
        const player = document.getElementById('player');
        const scoreElement = document.getElementById('score');
        const levelElement = document.getElementById('level');
        const healthFill = document.getElementById('health-fill');
        const gameOver = document.getElementById('game-over');
        const finalScore = document.getElementById('final-score');
        const restartButton = document.getElementById('restart-button');
        const startScreen = document.getElementById('start-screen');
        const startButton = document.getElementById('start-button');
        

        // 游戏配置
        const containerWidth = gameContainer.offsetWidth;
        const containerHeight = gameContainer.offsetHeight;
        const playerWidth = 50;
        const playerHeight = 50;
        const playerSpeed = 8;

        const bulletSpeed = 10;
        const enemyBulletSpeed = 5;
        const enemySpeed = 3;
        const enemyGenerationInterval = 1500; // 毫秒
        const powerupGenerationInterval = 10000; // 毫秒
        
        // 游戏状态
        let playerX = containerWidth / 2 - playerWidth / 2;
        let playerY = containerHeight - playerHeight - 20;
        let playerHealth = 100;
        let score = 0;
        let level = 1;
        let bullets = [];
        let enemyBullets = [];
        let enemies = [];

        let powerups = [];
        let explosions = [];
        let hasShield = false;
        let shieldElement = null;
        let weaponLevel = 1;
        let weaponTimer = null;
        let gameRunning = false;
        let gameLoop;
        let enemyInterval;

        let powerupInterval;
        let levelInterval;
        let upPressed = false;
        let downPressed = false;
        let leftPressed = false;

        let rightPressed = false;
        let spacePressed = false;
        let lastBulletTime = 0;
        
        // 初始化游戏
        function initGame() {
            // 隐藏开始屏幕
            startScreen.style.display = 'none';
            
            // 重置游戏状态
            playerX = containerWidth / 2 - playerWidth / 2;
            playerY = containerHeight - playerHeight - 20;
            playerHealth = 100;
            score = 0;
            level = 1;
            bullets = [];
            enemyBullets = [];
            enemies = [];
            powerups = [];
            explosions = [];
            hasShield = false;
            if (shieldElement) {
                shieldElement.remove();
                shieldElement = null;
            }
            weaponLevel = 1;
            if (weaponTimer) {
                clearTimeout(weaponTimer);
                weaponTimer = null;
            }
            
            // 清除所有元素
            const existingBullets = document.querySelectorAll('.bullet');

            existingBullets.forEach(bullet => bullet.remove());
            
            const existingEnemyBullets = document.querySelectorAll('.enemy-bullet');
            existingEnemyBullets.forEach(bullet => bullet.remove());
            
            const existingEnemies = document.querySelectorAll('.enemy');
            existingEnemies.forEach(enemy => enemy.remove());
            
            const existingPowerups = document.querySelectorAll('.powerup');
            existingPowerups.forEach(powerup => powerup.remove());
            
            const existingExplosions = document.querySelectorAll('.explosion');
            existingExplosions.forEach(explosion => explosion.remove());
            
            // 更新显示
            scoreElement.textContent = score;
            levelElement.textContent = level;
            healthFill.style.width = `${playerHealth}%`;
            player.style.left = `${playerX}px`;
            player.style.top = `${playerY}px`;
            

            // 开始游戏循环
            gameRunning = true;
            gameLoop = setInterval(updateGame, 16); // 约60帧每秒
            
            // 开始生成敌人
            enemyInterval = setInterval(generateEnemy, enemyGenerationInterval);
            
            // 开始生成道具
            powerupInterval = setInterval(generatePowerup, powerupGenerationInterval);
            
            // 随着时间增加难度
            levelInterval = setInterval(() => {
                if (gameRunning) {
                    level++;
                    levelElement.textContent = level;
                }
            }, 30000); // 每30秒增加一次难度
        }
        
        // 生成敌人
        function generateEnemy() {
            if (!gameRunning) return;
            
            const enemy = document.createElement('div');
            enemy.className = 'enemy';
            
            // 随机选择敌人类型
            const enemyType = Math.floor(Math.random() * 3) + 1;

            let enemyWidth, enemyHeight, enemyHealth;
            
            if (enemyType === 1) {
                enemy.classList.add('enemy-1');
                enemyWidth = 40;
                enemyHeight = 40;
                enemyHealth = 1;
            } else if (enemyType === 2) {
                enemy.classList.add('enemy-2');
                enemyWidth = 50;
                enemyHeight = 50;

                enemyHealth = 2;
            } else {
                enemy.classList.add('enemy-3');
                enemyWidth = 60;
                enemyHeight = 60;
                enemyHealth = 3;
            }
            
            const x = Math.random() * (containerWidth - enemyWidth);
            const y = -enemyHeight;
            
            enemy.style.width = `${enemyWidth}px`;
            enemy.style.height = `${enemyHeight}px`;
            enemy.style.left = `${x}px`;
            enemy.style.top = `${y}px`;
            
            gameContainer.appendChild(enemy);
            
            enemies.push({
                element: enemy,
                x: x,
                y: y,

                width: enemyWidth,

                height: enemyHeight,
                type: enemyType,
                health: enemyHealth,
                lastShot: 0
            });

        }
        
        // 生成道具
        function generatePowerup() {
            if (!gameRunning) return;
            
            const powerup = document.createElement('div');
            powerup.className = 'powerup';
            

            // 随机选择道具类型
            const powerupType = Math.floor(Math.random() * 3) + 1;
            let powerupClass;
            
            if (powerupType === 1) {
                powerupClass = 'powerup-health';
            } else if (powerupType === 2) {

                powerupClass = 'powerup-shield';
            } else {
                powerupClass = 'powerup-weapon';
            }
            
            powerup.classList.add(powerupClass);
            
            const powerupSize = 30;
            const x = Math.random() * (containerWidth - powerupSize);
            const y = -powerupSize;
            
            powerup.style.width = `${powerupSize}px`;
            powerup.style.height = `${powerupSize}px`;
            powerup.style.left = `${x}px`;
            powerup.style.top = `${y}px`;
            
            gameContainer.appendChild(powerup);
            
            powerups.push({
                element: powerup,
                x: x,
                y: y,
                size: powerupSize,
                type: powerupType
            });
        }

        
        // 创建爆炸效果
        function createExplosion(x, y) {
            const explosion = document.createElement('div');
            explosion.className = 'explosion';
            explosion.style.left = `${x}px`;
            explosion.style.top = `${y}px`;
            
            gameContainer.appendChild(explosion);
            

            // 爆炸动画结束后移除元素
            setTimeout(() => {
                explosion.remove();
            }, 500);
        }
        
        // 创建护盾
        function createShield() {
            if (shieldElement) {
                shieldElement.remove();
            }
            

            shieldElement = document.createElement('div');
            shieldElement.className = 'shield';
            updateShieldPosition();
            
            gameContainer.appendChild(shieldElement);
            hasShield = true;
            
            // 护盾持续时间
            setTimeout(() => {
                if (shieldElement) {
                    shieldElement.remove();
                    shieldElement = null;
                    hasShield = false;
                }
            }, 10000); // 10秒
        }
        
        // 更新护盾位置
        function updateShieldPosition() {
            if (shieldElement && hasShield) {
                shieldElement.style.left = `${playerX - 10}px`;
                shieldElement.style.top = `${playerY - 10}px`;
            }
        }
        
        // 升级武器
        function upgradeWeapon() {
            if (weaponTimer) {
                clearTimeout(weaponTimer);
            }
            
            weaponLevel = Math.min(3, weaponLevel + 1);

            
            // 武器升级持续时间
            weaponTimer = setTimeout(() => {
                weaponLevel = 1;
            }, 15000); // 15秒
        }
        
        // 发射子弹
        function fireBullet() {
            const currentTime = Date.now();
            const bulletCooldown = 300 / weaponLevel; // 武器等级越高,发射间隔越短
            
            if (currentTime - lastBulletTime < bulletCooldown) return;
            
            lastBulletTime = currentTime;
            
            if (weaponLevel === 1) {
                // 单发子弹
                createBullet(playerX + playerWidth / 2 - 2.5, playerY);
            } else if (weaponLevel === 2) {
                // 双发子弹

                createBullet(playerX + playerWidth / 4, playerY);
                createBullet(playerX + playerWidth * 3/4, playerY);
            } else {
                // 三发子弹
                createBullet(playerX + playerWidth / 2 - 2.5, playerY);
                createBullet(playerX + playerWidth / 4, playerY + 10);
                createBullet(playerX + playerWidth * 3/4, playerY + 10);
            }
        }
        
        // 创建子弹
        function createBullet(x, y) {
            const bullet = document.createElement('div');
            bullet.className = 'bullet';
            bullet.style.left = `${x}px`;
            bullet.style.top = `${y}px`;
            
            gameContainer.appendChild(bullet);
            

            bullets.push({
                element: bullet,
                x: x,
                y: y
            });
        }
        

        // 敌人发射子弹
        function enemyFireBullet(enemy) {

            const currentTime = Date.now();
            const bulletCooldown = 2000 - level * 100; // 随等级增加发射频率
            
            if (currentTime - enemy.lastShot < bulletCooldown) return;
            
            enemy.lastShot = currentTime;
            
            const bullet = document.createElement('div');
            bullet.className = 'enemy-bullet';
            
            const bulletX = enemy.x + enemy.width / 2 - 2.5;
            const bulletY = enemy.y + enemy.height;
            
            bullet.style.left = `${bulletX}px`;
            bullet.style.top = `${bulletY}px`;
            
            gameContainer.appendChild(bullet);
            
            enemyBullets.push({
                element: bullet,
                x: bulletX,
                y: bulletY
            });
        }
        

        // 更新游戏状态
        function updateGame() {
            if (!gameRunning) return;
            
            // 更新玩家位置
            if (upPressed && playerY > 0) {
                playerY -= playerSpeed;
            }
            if (downPressed && playerY < containerHeight - playerHeight) {
                playerY += playerSpeed;
            }

            if (leftPressed && playerX > 0) {
                playerX -= playerSpeed;
            }
            if (rightPressed && playerX < containerWidth - playerWidth) {
                playerX += playerSpeed;
            }
            
            player.style.left = `${playerX}px`;
            player.style.top = `${playerY}px`;
            

            // 更新护盾位置

            updateShieldPosition();
            
            // 发射子弹

            if (spacePressed) {
                fireBullet();
            }
            
            // 更新子弹位置
            bullets.forEach((bullet, bulletIndex) => {
                bullet.y -= bulletSpeed;
                bullet.element.style.top = `${bullet.y}px`;
                
                // 移除屏幕外的子弹
                if (bullet.y + 15 < 0) {
                    bullet.element.remove();
                    bullets.splice(bulletIndex, 1);
                    return;
                }
                
                // 检查子弹与敌人的碰撞
                enemies.forEach((enemy, enemyIndex) => {
                    if (bullet.x + 5 > enemy.x && 
                        bullet.x < enemy.x + enemy.width && 
                        bullet.y < enemy.y + enemy.height && 
                        bullet.y + 15 > enemy.y) {
                        
                        // 移除子弹
                        bullet.element.remove();
                        bullets.splice(bulletIndex, 1);
                        
                        // 减少敌人生命值
                        enemy.health--;
                        
                        // 如果敌人被击败
                        if (enemy.health <= 0) {
                            // 增加分数
                            score += enemy.type * 10;
                            scoreElement.textContent = score;
                            
                            // 创建爆炸效果
                            createExplosion(enemy.x, enemy.y);
                            
                            // 移除敌人
                            enemy.element.remove();
                            enemies.splice(enemyIndex, 1);
                        }
                        
                        return;
                    }
                });
            });
            
            // 更新敌人子弹位置
            enemyBullets.forEach((bullet, bulletIndex) => {
                bullet.y += enemyBulletSpeed;
                bullet.element.style.top = `${bullet.y}px`;
                
                // 移除屏幕外的子弹
                if (bullet.y > containerHeight) {
                    bullet.element.remove();
                    enemyBullets.splice(bulletIndex, 1);
                    return;
                }
                
                // 检查子弹与玩家的碰撞
                if (!hasShield && 
                    bullet.x + 5 > playerX && 
                    bullet.x < playerX + playerWidth && 
                    bullet.y + 15 > playerY && 
                    bullet.y < playerY + playerHeight) {
                    

                    // 移除子弹
                    bullet.element.remove();
                    enemyBullets.splice(bulletIndex, 1);
                    
                    // 减少玩家生命值
                    playerHealth = Math.max(0, playerHealth - 10);

                    healthFill.style.width = `${playerHealth}%`;
                    
                    // 检查游戏结束
                    if (playerHealth <= 0) {
                        endGame();
                    }
                    
                    return;
                }
                
                // 检查子弹与护盾的碰撞
                if (hasShield && 
                    bullet.x + 5 > playerX - 10 && 
                    bullet.x < playerX + playerWidth + 10 && 
                    bullet.y + 15 > playerY - 10 && 
                    bullet.y < playerY + playerHeight + 10) {
                    
                    // 移除子弹
                    bullet.element.remove();
                    enemyBullets.splice(bulletIndex, 1);
                    return;
                }
            });
            
            // 更新敌人位置
            enemies.forEach((enemy, index) => {
                // 移动敌人
                enemy.y += enemySpeed * (1 + level * 0.1);
                enemy.element.style.top = `${enemy.y}px`;
                
                // 敌人发射子弹
                if (Math.random() < 0.01 * enemy.type) {
                    enemyFireBullet(enemy);
                }
                
                // 检查敌人与玩家的碰撞
                if (!hasShield && 
                    enemy.x + enemy.width > playerX && 
                    enemy.x < playerX + playerWidth && 
                    enemy.y + enemy.height > playerY && 
                    enemy.y < playerY + playerHeight) {
                    
                    // 创建爆炸效果
                    createExplosion(enemy.x, enemy.y);
                    
                    // 移除敌人
                    enemy.element.remove();
                    enemies.splice(index, 1);
                    
                    // 减少玩家生命值
                    playerHealth = Math.max(0, playerHealth - 20);
                    healthFill.style.width = `${playerHealth}%`;
                    
                    // 检查游戏结束
                    if (playerHealth <= 0) {
                        endGame();
                    }
                    
                    return;
                }
                
                // 检查敌人与护盾的碰撞
                if (hasShield && 
                    enemy.x + enemy.width > playerX - 10 && 
                    enemy.x < playerX + playerWidth + 10 && 
                    enemy.y + enemy.height > playerY - 10 && 
                    enemy.y < playerY + playerHeight + 10) {
                    
                    // 创建爆炸效果
                    createExplosion(enemy.x, enemy.y);
                    
                    // 移除敌人
                    enemy.element.remove();
                    enemies.splice(index, 1);
                    
                    // 增加分数
                    score += enemy.type * 5;
                    scoreElement.textContent = score;
                    
                    return;
                }
                
                // 移除屏幕外的敌人
                if (enemy.y > containerHeight) {
                    enemy.element.remove();
                    enemies.splice(index, 1);
                }
            });
            
            // 更新道具位置
            powerups.forEach((powerup, index) => {
                // 移动道具
                powerup.y += 2;
                powerup.element.style.top = `${powerup.y}px`;
                
                // 检查道具与玩家的碰撞
                if (powerup.x + powerup.size > playerX && 
                    powerup.x < playerX + playerWidth && 
                    powerup.y + powerup.size > playerY && 
                    powerup.y < playerY + playerHeight) {
                    
                    // 应用道具效果
                    if (powerup.type === 1) {
                        // 生命值道具
                        playerHealth = Math.min(100, playerHealth + 30);
                        healthFill.style.width = `${playerHealth}%`;
                    } else if (powerup.type === 2) {
                        // 护盾道具
                        createShield();
                    } else {
                        // 武器升级道具
                        upgradeWeapon();

                    }
                    

                    // 移除道具
                    powerup.element.remove();
                    powerups.splice(index, 1);
                    
                    // 增加分数
                    score += 5;
                    scoreElement.textContent = score;
                    
                    return;
                }
                
                // 移除屏幕外的道具
                if (powerup.y > containerHeight) {
                    powerup.element.remove();
                    powerups.splice(index, 1);
                }
            });
        }

        
        // 结束游戏
        function endGame() {
            gameRunning = false;
            clearInterval(gameLoop);
            clearInterval(enemyInterval);
            clearInterval(powerupInterval);
            clearInterval(levelInterval);
            
            if (weaponTimer) {
                clearTimeout(weaponTimer);
                weaponTimer = null;
            }
            
            // 显示游戏结束界面

            gameOver.style.display = 'flex';
            document.getElementById('final-score').textContent = score;
        }
        
        // 键盘控制
        document.addEventListener('keydown', (e) => {

            if (e.code === 'ArrowUp' || e.key === 'ArrowUp') {

                upPressed = true;
            } else if (e.code === 'ArrowDown' || e.key === 'ArrowDown') {
                downPressed = true;
            } else if (e.code === 'ArrowLeft' || e.key === 'ArrowLeft') {
                leftPressed = true;

            } else if (e.code === 'ArrowRight' || e.key === 'ArrowRight') {
                rightPressed = true;

            } else if (e.code === 'Space' || e.key === ' ') {
                spacePressed = true;
                e.preventDefault(); // 防止空格键滚动页面
            }
        });
        
        document.addEventListener('keyup', (e) => {
            if (e.code === 'ArrowUp' || e.key === 'ArrowUp') {
                upPressed = false;
            } else if (e.code === 'ArrowDown' || e.key === 'ArrowDown') {
                downPressed = false;
            } else if (e.code === 'ArrowLeft' || e.key === 'ArrowLeft') {
                leftPressed = false;
            } else if (e.code === 'ArrowRight' || e.key === 'ArrowRight') {
                rightPressed = false;
            } else if (e.code === 'Space' || e.key === ' ') {
                spacePressed = false;
            }

        });
        
        // 触摸控制(移动设备)
        let touchStartX, touchStartY;
        
        gameContainer.addEventListener('touchstart', (e) => {
            e.preventDefault();
            const touch = e.touches[0];
            touchStartX = touch.clientX;
            touchStartY = touch.clientY;
            
            // 如果触摸在屏幕下半部分,发射子弹
            if (touch.clientY > window.innerHeight / 2) {
                spacePressed = true;
            }
        });
        
        gameContainer.addEventListener('touchmove', (e) => {
            e.preventDefault();
            if (!touchStartX || !touchStartY) return;
            
            const touch = e.touches[0];
            const diffX = touch.clientX - touchStartX;

            const diffY = touch.clientY - touchStartY;
            
            // 更新玩家位置
            playerX = Math.max(0, Math.min(containerWidth - playerWidth, playerX + diffX));
            playerY = Math.max(0, Math.min(containerHeight - playerHeight, playerY + diffY));
            
            player.style.left = `${playerX}px`;
            player.style.top = `${playerY}px`;
            
            // 更新触摸起始位置
            touchStartX = touch.clientX;
            touchStartY = touch.clientY;
        });
        
        gameContainer.addEventListener('touchend', () => {
            touchStartX = null;
            touchStartY = null;
            spacePressed = false;
        });
        
        // 事件监听
        restartButton.addEventListener('click', () => {
            gameOver.style.display = 'none';
            initGame();
        });
        
        startButton.addEventListener('click', () => {
            initGame();
        });
    </script>
</body>
</html>
相关推荐
神秘的猪头29 分钟前
🚀 拒绝“一本正经胡说八道”!手把手带你用 LangChain 实现 RAG,打造你的专属 AI 知识库
langchain·llm·openai
ygxb37 分钟前
如何去创建一个规范化的Agent SKIll?
后端·ai编程·claude
NikoAI编程42 分钟前
Claude Code 安装报错?看这一篇就够了
ai编程
chaors1 小时前
从零学RAG0x01之向量化
人工智能·aigc·ai编程
chaors1 小时前
从零学RAG0x02向量数据库
人工智能·aigc·ai编程
栀秋6661 小时前
重塑 AI 交互边界:基于 LangChain 与 MCP 协议的全栈实践
langchain·llm·mcp
推敲1 小时前
第三篇:Spring 项目重构的高级技巧与最佳实践
ai编程
推敲1 小时前
第一篇:Claude Code 入门 —— 理解它如何"读懂"你的 Java 项目
ai编程
推敲1 小时前
第二篇:Claude Code 在 Spring 项目中的实战工作流
ai编程
大模型真好玩2 小时前
LangChain DeepAgents 速通指南(三)—— 让Agent告别混乱:Tool Selector与Todo List中间件解析
人工智能·langchain·trae