跳到正文

个人记录

bank

tang_zdx约 50 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2026年4月17日
篇幅
约 50 分钟

版本

  1. v3当前
  2. v2
  3. v1
C++
<!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 -->
  <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">

  <!-- 配置Tailwind -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#FF4D4F',
            obstacle: '#8B4513',
            steel: '#808080',
            ground: '#228B22',
          },
          fontFamily: {
            game: ['"Press Start 2P"', 'cursive', 'sans-serif'],
          },
        },
      }
    }
  </script>

  <!-- 自定义工具类 -->
  <style type="text/tailwindcss">
    @layer utilities {
      .pixel-corners {
        clip-path: polygon(
          0% 4px, 4px 4px, 4px 0%, calc(100% - 4px) 0%, calc(100% - 4px) 4px, 100% 4px,
          100% calc(100% - 4px), calc(100% - 4px) calc(100% - 4px), calc(100% - 4px) 100%,
          4px 100%, 4px calc(100% - 4px), 0% calc(100% - 4px)
        );
      }
      .game-shadow {
        box-shadow: 0 0 0 2px #000, inset 0 0 0 2px #fff;
      }
      .explosion {
        animation: explode 0.5s ease-out forwards;
      }
      @keyframes explode {
        0% { transform: scale(0.5); opacity: 1; }
        50% { transform: scale(1.5); opacity: 0.8; }
        100% { transform: scale(2); opacity: 0; }
      }
    }
  </style>

  <!-- 引入像素风格字体 -->
  <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet">
</head>

<body class="bg-gray-900 text-white min-h-screen flex flex-col items-center justify-center p-4 overflow-hidden">
  <!-- 游戏容器 -->
  <div class="relative w-full max-w-4xl">
    <!-- 开始界面 -->
    <div id="start-screen" class="absolute inset-0 z-30 flex flex-col items-center justify-center bg-gray-900/95 backdrop-blur-sm">
      <h1 class="text-[clamp(1.5rem,5vw,3rem)] font-game text-primary mb-8 text-center">坦克对战</h1>
      <div class="flex flex-col gap-4 w-full max-w-xs">
        <button id="start-btn" class="bg-primary hover:bg-primary/80 text-white py-3 px-6 rounded-lg font-game text-sm transition-all transform hover:scale-105 active:scale-95">
          开始游戏
        </button>
        <button id="how-to-play-btn" class="bg-gray-700 hover:bg-gray-600 text-white py-3 px-6 rounded-lg font-game text-sm transition-all">
          游戏说明
        </button>
      </div>
    </div>

    <!-- 游戏说明 -->
    <div id="instructions" class="absolute inset-0 z-40 hidden flex-col items-center justify-center bg-gray-900/95 backdrop-blur-sm p-6">
      <h2 class="text-xl font-game text-primary mb-6 text-center">游戏说明</h2>
      <div class="bg-gray-800 p-6 rounded-lg max-w-md w-full mb-6">
        <ul class="space-y-4 text-sm">
          <li class="flex items-center gap-3">
            <i class="fa fa-keyboard-o text-primary"></i>
            <span>方向键 <strong>↑↓←→</strong> 控制坦克移动</span>
          </li>
          <li class="flex items-center gap-3">
            <i class="fa fa-space-shuttle text-primary"></i>
            <span>空格键 <strong>SPACE</strong> 发射子弹</span>
          </li>
          <li class="flex items-center gap-3">
            <i class="fa fa-shield text-primary"></i>
            <span>击毁敌方坦克得分,避免被敌方击中</span>
          </li>
          <li class="flex items-center gap-3">
            <i class="fa fa-brick text-obstacle"></i>
            <span>棕色砖块可以被击毁,灰色钢铁不能被击毁</span>
          </li>
          <li class="flex items-center gap-3">
            <i class="fa fa-pause text-primary"></i>
            <span>P键暂停游戏</span>
          </li>
        </ul>
      </div>
      <button id="back-btn" class="bg-primary hover:bg-primary/80 text-white py-2 px-4 rounded-lg font-game text-xs transition-all">
        返回
      </button>
    </div>

    <!-- 游戏暂停界面 -->
    <div id="pause-screen" class="absolute inset-0 z-30 hidden flex-col items-center justify-center bg-gray-900/80 backdrop-blur-sm">
      <h2 class="text-2xl font-game text-primary mb-6">游戏暂停</h2>
      <button id="resume-btn" class="bg-primary hover:bg-primary/80 text-white py-3 px-6 rounded-lg font-game text-sm transition-all">
        继续游戏
      </button>
    </div>

    <!-- 游戏结束界面 -->
    <div id="game-over-screen" class="absolute inset-0 z-30 hidden flex-col items-center justify-center bg-gray-900/90 backdrop-blur-sm">
      <h2 class="text-2xl font-game text-secondary mb-2">游戏结束</h2>
      <p class="text-xl mb-2">最终得分: <span id="final-score" class="text-primary">0</span></p>
      <button id="restart-btn" class="bg-primary hover:bg-primary/80 text-white py-3 px-6 rounded-lg font-game text-sm transition-all mt-6">
        重新开始
      </button>
    </div>

    <!-- 游戏信息面板 -->
    <div class="flex justify-between items-center mb-4 px-2">
      <div class="flex items-center gap-2 bg-gray-800 py-2 px-4 rounded-lg">
        <i class="fa fa-trophy text-yellow-500"></i>
        <span class="font-game text-sm">得分: <span id="score" class="text-primary">0</span></span>
      </div>
      <div class="flex items-center gap-2 bg-gray-800 py-2 px-4 rounded-lg">
        <i class="fa fa-heart text-secondary"></i>
        <span class="font-game text-sm">生命: <span id="lives" class="text-primary">3</span></span>
      </div>
      <button id="pause-btn" class="bg-gray-800 hover:bg-gray-700 py-2 px-4 rounded-lg transition-all">
        <i class="fa fa-pause"></i>
      </button>
    </div>

    <!-- 游戏画布 -->
    <canvas id="gameCanvas" class="bg-ground pixel-corners game-shadow w-full"></canvas>
  </div>

  <script>
    // 游戏常量
    const TANK_SIZE = 30;
    const BULLET_SIZE = 6;
    const BULLET_SPEED = 5;
    const TANK_SPEED = 2;
    const OBSTACLE_SIZE = 30;
    const ENEMY_SPAWN_RATE = 5000; // 敌方坦克生成间隔(ms)
    const EXPLOSION_DURATION = 500; // 爆炸动画持续时间(ms)

    // 获取画布和上下文
    const canvas = document.getElementById('gameCanvas');
    const ctx = canvas.getContext('2d');

    // 设置画布尺寸
    function resizeCanvas() {
      // 保持16:9的游戏比例
      const containerWidth = canvas.parentElement.clientWidth;
      const idealHeight = containerWidth * 9 / 16;
      canvas.width = Math.floor(containerWidth / OBSTACLE_SIZE) * OBSTACLE_SIZE;
      canvas.height = Math.floor(idealHeight / OBSTACLE_SIZE) * OBSTACLE_SIZE;
    }

    // 初始化时调整一次画布大小
    resizeCanvas();
    window.addEventListener('resize', resizeCanvas);

    // 游戏状态
    let gameState = {
      running: false,
      paused: false,
      score: 0,
      lives: 3,
      lastEnemySpawn: 0,
      explosions: [],
      bullets: [],
      obstacles: [],
      enemyTanks: [],
      playerTank: null
    };

    // 玩家坦克类
    class Tank {
      constructor(x, y, isPlayer = false) {
        this.x = x;
        this.y = y;
        this.size = TANK_SIZE;
        this.speed = TANK_SPEED;
        this.direction = 'up'; // 初始方向
        this.isPlayer = isPlayer;
        this.color = isPlayer ? '#165DFF' : '#FF4D4F';
        this.lastShot = 0;
        this.shotCooldown = isPlayer ? 500 : 1000; // 射击冷却时间
      }

      // 绘制坦克
      draw() {
        ctx.save();
        ctx.translate(this.x + this.size / 2, this.y + this.size / 2);

        // 根据方向旋转
        switch(this.direction) {
          case 'right': ctx.rotate(Math.PI / 2); break;
          case 'down': ctx.rotate(Math.PI); break;
          case 'left': ctx.rotate(3 * Math.PI / 2); break;
        }

        // 坦克身体
        ctx.fillStyle = this.color;
        ctx.fillRect(-this.size/2, -this.size/2, this.size, this.size);

        // 坦克炮管
        ctx.fillStyle = '#000';
        ctx.fillRect(-3, -this.size/2, 6, -this.size/2);

        // 坦克履带
        ctx.fillStyle = '#333';
        ctx.fillRect(-this.size/2, -this.size/2, 5, this.size);
        ctx.fillRect(this.size/2 - 5, -this.size/2, 5, this.size);

        ctx.restore();
      }

      // 移动坦克
      move(direction) {
        this.direction = direction;
        let newX = this.x;
        let newY = this.y;

        switch(direction) {
          case 'up': newY -= this.speed; break;
          case 'down': newY += this.speed; break;
          case 'left': newX -= this.speed; break;
          case 'right': newX += this.speed; break;
        }

        // 边界检测和碰撞检测
        if (this.isValidMove(newX, newY)) {
          this.x = newX;
          this.y = newY;
        }
      }

      // 检查移动是否有效(不超出边界且不碰撞障碍物)
      isValidMove(newX, newY) {
        // 边界检测
        if (newX < 0 || newX + this.size > canvas.width ||
            newY < 0 || newY + this.size > canvas.height) {
          return false;
        }

        // 障碍物碰撞检测
        for (const obstacle of gameState.obstacles) {
          if (this.checkCollision(newX, newY, obstacle)) {
            return false;
          }
        }

        // 坦克之间的碰撞检测
        const tanks = this.isPlayer ? gameState.enemyTanks : [gameState.playerTank, ...gameState.enemyTanks.filter(t => t !== this)];
        for (const tank of tanks) {
          if (tank && this.checkCollision(newX, newY, tank)) {
            return false;
          }
        }

        return true;
      }

      // 碰撞检测
      checkCollision(x, y, obj) {
        return x < obj.x + obj.size &&
               x + this.size > obj.x &&
               y < obj.y + obj.size &&
               y + this.size > obj.y;
      }

      // 发射子弹
      shoot() {
        const now = Date.now();
        if (now - this.lastShot < this.shotCooldown) {
          return;
        }

        this.lastShot = now;

        // 计算子弹初始位置(炮口位置)
        let bulletX = this.x + this.size / 2 - BULLET_SIZE / 2;
        let bulletY = this.y + this.size / 2 - BULLET_SIZE / 2;

        switch(this.direction) {
          case 'up': bulletY -= this.size / 2; break;
          case 'down': bulletY += this.size / 2; break;
          case 'left': bulletX -= this.size / 2; break;
          case 'right': bulletX += this.size / 2; break;
        }

        // 创建子弹
        gameState.bullets.push(new Bullet(
          bulletX,
          bulletY,
          this.direction,
          this.isPlayer
        ));
      }
    }

    // 子弹类
    class Bullet {
      constructor(x, y, direction, isPlayerBullet) {
        this.x = x;
        this.y = y;
        this.size = BULLET_SIZE;
        this.direction = direction;
        this.speed = BULLET_SPEED;
        this.isPlayerBullet = isPlayerBullet;
        this.color = isPlayerBullet ? '#FFF' : '#FFD700';
      }

      // 绘制子弹
      draw() {
        ctx.fillStyle = this.color;
        ctx.beginPath();
        ctx.arc(this.x + this.size/2, this.y + this.size/2, this.size/2, 0, Math.PI * 2);
        ctx.fill();
      }

      // 更新子弹位置
      update() {
        switch(this.direction) {
          case 'up': this.y -= this.speed; break;
          case 'down': this.y += this.speed; break;
          case 'left': this.x -= this.speed; break;
          case 'right': this.x += this.speed; break;
        }

        // 检查是否超出边界
        return this.x > 0 && this.x < canvas.width &&
               this.y > 0 && this.y < canvas.height;
      }
    }

    // 障碍物类
    class Obstacle {
      constructor(x, y, type = 'brick') {
        this.x = x;
        this.y = y;
        this.size = OBSTACLE_SIZE;
        this.type = type; // 'brick' 可破坏, 'steel' 不可破坏
        this.color = type === 'brick' ? '#8B4513' : '#808080';
      }

      // 绘制障碍物
      draw() {
        ctx.fillStyle = this.color;
        ctx.fillRect(this.x, this.y, this.size, this.size);

        // 绘制纹理
        ctx.strokeStyle = 'rgba(0,0,0,0.3)';
        ctx.lineWidth = 1;

        if (this.type === 'brick') {
          // 砖块纹理
          ctx.beginPath();
          ctx.moveTo(this.x, this.y + this.size/2);
          ctx.lineTo(this.x + this.size, this.y + this.size/2);
          ctx.moveTo(this.x + this.size/2, this.y);
          ctx.lineTo(this.x + this.size/2, this.y + this.size);
          ctx.stroke();
        } else {
          // 钢铁纹理
          ctx.beginPath();
          ctx.moveTo(this.x, this.y);
          ctx.lineTo(this.x + this.size, this.y + this.size);
          ctx.moveTo(this.x + this.size, this.y);
          ctx.lineTo(this.x, this.y + this.size);
          ctx.stroke();
        }
      }
    }

    // 爆炸效果类
    class Explosion {
      constructor(x, y) {
        this.x = x;
        this.y = y;
        this.size = 40;
        this.startTime = Date.now();
      }

      // 绘制爆炸效果
      draw() {
        const elapsed = Date.now() - this.startTime;
        const progress = elapsed / EXPLOSION_DURATION;

        if (progress >= 1) return false;

        ctx.save();
        ctx.globalAlpha = 1 - progress;

        // 绘制爆炸动画
        const gradient = ctx.createRadialGradient(
          this.x + this.size/2, this.y + this.size/2, 0,
          this.x + this.size/2, this.y + this.size/2, this.size * progress
        );
        gradient.addColorStop(0, '#FFD700');
        gradient.addColorStop(0.5, '#FFA500');
        gradient.addColorStop(1, '#FF4500');

        ctx.fillStyle = gradient;
        ctx.beginPath();
        ctx.arc(this.x + this.size/2, this.y + this.size/2, this.size * progress, 0, Math.PI * 2);
        ctx.fill();

        ctx.restore();
        return true;
      }
    }

    // 初始化游戏
    function initGame() {
      // 重置游戏状态
      gameState = {
        running: true,
        paused: false,
        score: 0,
        lives: 3,
        lastEnemySpawn: Date.now(),
        explosions: [],
        bullets: [],
        obstacles: [],
        enemyTanks: [],
        playerTank: new Tank(canvas.width / 2 - TANK_SIZE / 2, canvas.height - TANK_SIZE * 2, true)
      };

      // 更新UI
      updateUI();

      // 生成随机障碍物
      generateObstacles();

      // 开始游戏循环
      gameLoop();
    }

    // 生成随机障碍物
    function generateObstacles() {
      const obstacleCount = Math.floor((canvas.width / OBSTACLE_SIZE) * (canvas.height / OBSTACLE_SIZE) * 0.15);

      for (let i = 0; i < obstacleCount; i++) {
        let x, y, validPosition;

        // 找到有效的位置(不与玩家坦克重叠)
        do {
          validPosition = true;
          x = Math.floor(Math.random() * (canvas.width / OBSTACLE_SIZE)) * OBSTACLE_SIZE;
          y = Math.floor(Math.random() * (canvas.height / OBSTACLE_SIZE)) * OBSTACLE_SIZE;

          // 确保不与玩家坦克重叠
          if (gameState.playerTank && gameState.playerTank.checkCollision(x, y, gameState.playerTank)) {
            validPosition = false;
          }

          // 确保不与已生成的障碍物重叠
          for (const obstacle of gameState.obstacles) {
            if (x === obstacle.x && y === obstacle.y) {
              validPosition = false;
              break;
            }
          }
        } while (!validPosition);

        // 随机生成砖块或钢铁障碍物(7:3比例)
        const type = Math.random() > 0.3 ? 'brick' : 'steel';
        gameState.obstacles.push(new Obstacle(x, y, type));
      }
    }

    // 生成敌方坦克
    function spawnEnemy() {
      const now = Date.now();
      if (now - gameState.lastEnemySpawn < ENEMY_SPAWN_RATE) {
        return;
      }

      gameState.lastEnemySpawn = now;

      // 随机选择一个边缘位置生成敌方坦克
      const side = Math.floor(Math.random() * 4);
      let x, y;

      switch(side) {
        case 0: // 顶部
          x = Math.floor(Math.random() * (canvas.width / TANK_SIZE)) * TANK_SIZE;
          y = 0;
          break;
        case 1: // 右侧
          x = canvas.width - TANK_SIZE;
          y = Math.floor(Math.random() * (canvas.height / TANK_SIZE)) * TANK_SIZE;
          break;
        case 2: // 底部
          x = Math.floor(Math.random() * (canvas.width / TANK_SIZE)) * TANK_SIZE;
          y = canvas.height - TANK_SIZE;
          break;
        case 3: // 左侧
          x = 0;
          y = Math.floor(Math.random() * (canvas.height / TANK_SIZE)) * TANK_SIZE;
          break;
      }

      // 确保不会与障碍物重叠
      let canSpawn = true;
      for (const obstacle of gameState.obstacles) {
        if (x < obstacle.x + obstacle.size &&
            x + TANK_SIZE > obstacle.x &&
            y < obstacle.y + obstacle.size &&
            y + TANK_SIZE > obstacle.y) {
          canSpawn = false;
          break;
        }
      }

      if (canSpawn) {
        gameState.enemyTanks.push(new Tank(x, y, false));
      }
    }

    // 敌方坦克AI
    function enemyAI() {
      for (const enemy of gameState.enemyTanks) {
        // 随机改变方向(1%的概率)
        if (Math.random() < 0.01) {
          const directions = ['up', 'down', 'left', 'right'];
          enemy.direction = directions[Math.floor(Math.random() * directions.length)];
        }

        // 移动
        enemy.move(enemy.direction);

        // 随机射击(0.1%的概率)
        if (Math.random() < 0.001) {
          enemy.shoot();
        }
      }
    }

    // 检测碰撞
    function checkCollisions() {
      // 子弹与障碍物/坦克的碰撞检测
      for (let i = gameState.bullets.length - 1; i >= 0; i--) {
        const bullet = gameState.bullets[i];
        let hit = false;

        // 检测与障碍物的碰撞
        for (let j = gameState.obstacles.length - 1; j >= 0; j--) {
          const obstacle = gameState.obstacles[j];

          if (bullet.x < obstacle.x + obstacle.size &&
              bullet.x + bullet.size > obstacle.x &&
              bullet.y < obstacle.y + obstacle.size &&
              bullet.y + bullet.size > obstacle.y) {

            // 子弹击中障碍物
            gameState.bullets.splice(i, 1);
            hit = true;

            // 如果是砖块障碍物,并且是玩家子弹,可以破坏
            if (obstacle.type === 'brick' && bullet.isPlayerBullet) {
              gameState.obstacles.splice(j, 1);
              gameState.explosions.push(new Explosion(obstacle.x, obstacle.y));
            }

            break;
          }
        }

        if (hit) continue;

        // 检测与坦克的碰撞
        if (bullet.isPlayerBullet) {
          // 玩家子弹击中敌方坦克
          for (let j = gameState.enemyTanks.length - 1; j >= 0; j--) {
            const enemy = gameState.enemyTanks[j];

            if (bullet.x < enemy.x + enemy.size &&
                bullet.x + bullet.size > enemy.x &&
                bullet.y < enemy.y + enemy.size &&
                bullet.y + bullet.size > enemy.y) {

              // 击中敌方坦克
              gameState.bullets.splice(i, 1);
              gameState.enemyTanks.splice(j, 1);
              gameState.explosions.push(new Explosion(enemy.x, enemy.y));

              // 增加分数
              gameState.score += 100;
              updateUI();

              hit = true;
              break;
            }
          }
        } else {
          // 敌方子弹击中玩家坦克
          if (gameState.playerTank &&
              bullet.x < gameState.playerTank.x + gameState.playerTank.size &&
              bullet.x + bullet.size > gameState.playerTank.x &&
              bullet.y < gameState.playerTank.y + gameState.playerTank.size &&
              bullet.y + bullet.size > gameState.playerTank.y) {

            // 击中玩家坦克
            gameState.bullets.splice(i, 1);
            gameState.explosions.push(new Explosion(gameState.playerTank.x, gameState.playerTank.y));

            // 减少生命值
            gameState.lives--;
            updateUI();

            // 检查游戏是否结束
            if (gameState.lives <= 0) {
              endGame();
              return;
            }

            // 重置玩家位置
            gameState.playerTank = new Tank(canvas.width / 2 - TANK_SIZE / 2, canvas.height - TANK_SIZE * 2, true);
            hit = true;
          }
        }
      }
    }

    // 更新游戏状态
    function update() {
      if (!gameState.running || gameState.paused) return;

      // 生成敌方坦克
      spawnEnemy();

      // 敌方AI
      enemyAI();

      // 更新子弹
      for (let i = gameState.bullets.length - 1; i >= 0; i--) {
        if (!gameState.bullets[i].update()) {
          gameState.bullets.splice(i, 1);
        }
      }

      // 检测碰撞
      checkCollisions();

      // 更新爆炸效果
      for (let i = gameState.explosions.length - 1; i >= 0; i--) {
        if (!gameState.explosions[i].draw()) {
          gameState.explosions.splice(i, 1);
        }
      }
    }

    // 绘制游戏
    function draw() {
      // 清空画布
      ctx.fillStyle = '#228B22';
      ctx.fillRect(0, 0, canvas.width, canvas.height);

      // 绘制网格背景
      ctx.strokeStyle = 'rgba(0, 100, 0, 0.3)';
      ctx.lineWidth = 1;

      // 绘制水平线
      for (let y = 0; y <= canvas.height; y += OBSTACLE_SIZE) {
        ctx.beginPath();
        ctx.moveTo(0, y);
        ctx.lineTo(canvas.width, y);
        ctx.stroke();
      }

      // 绘制垂直线
      for (let x = 0; x <= canvas.width; x += OBSTACLE_SIZE) {
        ctx.beginPath();
        ctx.moveTo(x, 0);
        ctx.lineTo(x, canvas.height);
        ctx.stroke();
      }

      // 绘制障碍物
      for (const obstacle of gameState.obstacles) {
        obstacle.draw();
      }

      // 绘制子弹
      for (const bullet of gameState.bullets) {
        bullet.draw();
      }

      // 绘制坦克
      if (gameState.playerTank) {
        gameState.playerTank.draw();
      }

      for (const enemy of gameState.enemyTanks) {
        enemy.draw();
      }

      // 绘制爆炸效果
      for (const explosion of gameState.explosions) {
        explosion.draw();
      }
    }

    // 游戏主循环
    function gameLoop() {
      update();
      draw();

      if (gameState.running) {
        requestAnimationFrame(gameLoop);
      }
    }

    // 更新UI
    function updateUI() {
      document.getElementById('score').textContent = gameState.score;
      document.getElementById('lives').textContent = gameState.lives;
      document.getElementById('final-score').textContent = gameState.score;
    }

    // 结束游戏
    function endGame() {
      gameState.running = false;
      document.getElementById('game-over-screen').classList.remove('hidden');
    }

    // 暂停/继续游戏
    function togglePause() {
      if (!gameState.running) return;

      gameState.paused = !gameState.paused;
      const pauseScreen = document.getElementById('pause-screen');

      if (gameState.paused) {
        pauseScreen.classList.remove('hidden');
      } else {
        pauseScreen.classList.add('hidden');
        gameLoop(); // 继续游戏循环
      }
    }

    // 键盘控制
    const keys = {
      up: false,
      down: false,
      left: false,
      right: false,
      space: false
    };

    document.addEventListener('keydown', (e) => {
      if (!gameState.running || gameState.paused) {
        // 只有在游戏未运行或暂停时不处理移动和射击
        if (e.key === 'p' || e.key === 'P') {
          togglePause();
        }
        return;
      }

      switch(e.key) {
        case 'ArrowUp': keys.up = true; break;
        case 'ArrowDown': keys.down = true; break;
        case 'ArrowLeft': keys.left = true; break;
        case 'ArrowRight': keys.right = true; break;
        case ' ': keys.space = true; break;
        case 'p': case 'P': togglePause(); break;
      }
    });

    document.addEventListener('keyup', (e) => {
      switch(e.key) {
        case 'ArrowUp': keys.up = false; break;
        case 'ArrowDown': keys.down = false; break;
        case 'ArrowLeft': keys.left = false; break;
        case 'ArrowRight': keys.right = false; break;
        case ' ': keys.space = false; break;
      }
    });

    // 处理持续按键
    function handleContinuousInput() {
      if (!gameState.running || gameState.paused || !gameState.playerTank) return;

      if (keys.up) {
        gameState.playerTank.move('up');
      } else if (keys.down) {
        gameState.playerTank.move('down');
      }

      if (keys.left) {
        gameState.playerTank.move('left');
      } else if (keys.right) {
        gameState.playerTank.move('right');
      }

      if (keys.space) {
        gameState.playerTank.shoot();
      }

      requestAnimationFrame(handleContinuousInput);
    }

    // 开始处理输入
    handleContinuousInput();

    // 事件监听
    document.getElementById('start-btn').addEventListener('click', () => {
      document.getElementById('start-screen').classList.add('hidden');
      initGame();
    });

    document.getElementById('how-to-play-btn').addEventListener('click', () => {
      document.getElementById('start-screen').classList.add('hidden');
      document.getElementById('instructions').classList.remove('hidden');
    });

    document.getElementById('back-btn').addEventListener('click', () => {
      document.getElementById('instructions').classList.add('hidden');
      document.getElementById('start-screen').classList.remove('hidden');
    });

    document.getElementById('pause-btn').addEventListener('click', togglePause);
    document.getElementById('resume-btn').addEventListener('click', togglePause);

    document.getElementById('restart-btn').addEventListener('click', () => {
      document.getElementById('game-over-screen').classList.add('hidden');
      initGame();
    });
  </script>
</body>
</html>
原文