以下是一个简单的飞机大战游戏的JavaScript代码示例:

// 创建画布
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 800;
canvas.height = 600;
document.body.appendChild(canvas);

// 创建飞机
const plane = {
  x: canvas.width / 2,
  y: canvas.height - 50,
  width: 50,
  height: 50,
  speed: 5,
  dx: 0,
  dy: 0
};

// 绘制飞机
function drawPlane() {
  ctx.fillStyle = 'blue';
  ctx.fillRect(plane.x, plane.y, plane.width, plane.height);
}

// 移动飞机
function movePlane() {
  plane.x += plane.dx;
  plane.y += plane.dy;

  // 碰撞检测
  if (plane.x < 0) {
    plane.x = 0;
  }

  if (plane.x + plane.width > canvas.width) {
    plane.x = canvas.width - plane.width;
  }

  if (plane.y < 0) {
    plane.y = 0;
  }

  if (plane.y + plane.height > canvas.height) {
    plane.y = canvas.height - plane.height;
  }
}

// 监听按键事件
function handleKeydown(event) {
  if (event.key === 'ArrowUp' || event.key === 'w') {
    plane.dy = -plane.speed;
  }

  if (event.key === 'ArrowDown' || event.key === 's') {
    plane.dy = plane.speed;
  }

  if (event.key === 'ArrowLeft' || event.key === 'a') {
    plane.dx = -plane.speed;
  }

  if (event.key === 'ArrowRight' || event.key === 'd') {
    plane.dx = plane.speed;
  }
}

function handleKeyup(event) {
  if (
    event.key === 'ArrowUp' ||
    event.key === 'ArrowDown' ||
    event.key === 'w' ||
    event.key === 's'
  ) {
    plane.dy = 0;
  }

  if (
    event.key === 'ArrowLeft' ||
    event.key === 'ArrowRight' ||
    event.key === 'a' ||
    event.key === 'd'
  ) {
    plane.dx = 0;
  }
}

// 游戏循环
function gameLoop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawPlane();
  movePlane();
  requestAnimationFrame(gameLoop);
}

// 初始化游戏
function init() {
  document.addEventListener('keydown', handleKeydown);
  document.addEventListener('keyup', handleKeyup);
  gameLoop();
}

// 启动游戏
init();

这只是一个简单的示例代码,你可以根据自己的需求进行修改和扩展。例如,你可以添加敌机、子弹、碰撞检测等功能来完善游戏

用Javascript写一个飞机大战

原文地址: https://www.cveoy.top/t/topic/hORh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录