当前位置:首页 > JavaScript

js实现雷霆战机

2026-03-15 22:12:04JavaScript

以下是使用JavaScript实现雷霆战机游戏的核心代码框架和实现思路,分为关键模块进行说明:

游戏初始化

创建画布并设置基础参数:

const canvas = document.getElementById('gameCanvas');
const ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;

let score = 0;
let gameOver = false;

玩家战机类

实现战机移动和射击功能:

class Player {
  constructor() {
    this.x = canvas.width/2;
    this.y = canvas.height-50;
    this.width = 50;
    this.height = 50;
    this.speed = 5;
    this.bullets = [];
  }

  draw() {
    ctx.fillStyle = 'blue';
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }

  move(direction) {
    if (direction === 'left' && this.x > 0) this.x -= this.speed;
    if (direction === 'right' && this.x < canvas.width-this.width) this.x += this.speed;
  }

  shoot() {
    this.bullets.push(new Bullet(this.x + this.width/2, this.y));
  }
}

子弹类

class Bullet {
  constructor(x, y) {
    this.x = x;
    this.y = y;
    this.radius = 5;
    this.speed = 7;
  }

  draw() {
    ctx.fillStyle = 'red';
    ctx.beginPath();
    ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
    ctx.fill();
  }

  update() {
    this.y -= this.speed;
  }
}

敌人类

class Enemy {
  constructor() {
    this.x = Math.random() * (canvas.width - 30);
    this.y = -30;
    this.width = 30;
    this.height = 30;
    this.speed = Math.random() * 2 + 1;
  }

  draw() {
    ctx.fillStyle = 'green';
    ctx.fillRect(this.x, this.y, this.width, this.height);
  }

  update() {
    this.y += this.speed;
    if (this.y > canvas.height) {
      gameOver = true;
    }
  }
}

游戏循环

主游戏逻辑和渲染循环:

let player = new Player();
let enemies = [];
let frames = 0;

function gameLoop() {
  if (gameOver) return endGame();

  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // 生成敌人
  if (frames % 100 === 0) {
    enemies.push(new Enemy());
  }

  // 更新玩家和子弹
  player.draw();
  player.bullets.forEach((bullet, index) => {
    bullet.update();
    bullet.draw();
    if (bullet.y < 0) player.bullets.splice(index, 1);
  });

  // 更新敌人
  enemies.forEach((enemy, eIndex) => {
    enemy.update();
    enemy.draw();

    // 碰撞检测
    player.bullets.forEach((bullet, bIndex) => {
      if (collision(bullet, enemy)) {
        enemies.splice(eIndex, 1);
        player.bullets.splice(bIndex, 1);
        score += 10;
      }
    });
  });

  frames++;
  requestAnimationFrame(gameLoop);
}

function collision(bullet, enemy) {
  return bullet.x > enemy.x && 
         bullet.x < enemy.x + enemy.width &&
         bullet.y > enemy.y && 
         bullet.y < enemy.y + enemy.height;
}

控制输入

添加键盘事件监听:

window.addEventListener('keydown', (e) => {
  if (e.key === 'ArrowLeft') player.move('left');
  if (e.key === 'ArrowRight') player.move('right');
  if (e.key === ' ') player.shoot();
});

启动游戏

gameLoop();

实现完整游戏还需要添加:

js实现雷霆战机

  • 生命值系统
  • 不同类型的敌人
  • 道具系统
  • 音效和爆炸效果
  • 游戏开始/结束界面
  • 分数存储功能

核心算法如碰撞检测可采用更高效的QuadTree空间分割技术优化性能,大型项目建议使用游戏引擎如Phaser.js进行开发。

标签: 雷霆战机
分享给朋友: