飞机大战用JS怎么写添加子弹、分数
- 创建HTML页面,添加画布元素
<!DOCTYPE html>
<html>
<head>
<title>飞机大战</title>
<style>
canvas{
border: 1px solid #000;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script src="game.js"></script>
</body>
</html>
- 创建JS游戏逻辑
// 获取画布元素
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
// 定义变量
var plane = {
x: canvas.width / 2,
y: canvas.height - 50,
speed: 10,
width: 50,
height: 50
};
var bullets = [];
var enemies = [];
var score = 0;
// 监听键盘事件
document.addEventListener('keydown', function(event) {
if(event.keyCode === 37) { // 左箭头
plane.x -= plane.speed;
}
else if(event.keyCode === 39) { // 右箭头
plane.x += plane.speed;
}
else if(event.keyCode === 32) { // 空格键
bullets.push({
x: plane.x + plane.width / 2,
y: plane.y,
speed: 5,
width: 5,
height: 10
});
}
});
// 更新游戏
function update() {
// 清空画布
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制飞机
ctx.fillStyle = '#f00';
ctx.fillRect(plane.x, plane.y, plane.width, plane.height);
// 绘制子弹
ctx.fillStyle = '#00f';
for(var i = 0; i < bullets.length; i++) {
ctx.fillRect(bullets[i].x, bullets[i].y, bullets[i].width, bullets[i].height);
bullets[i].y -= bullets[i].speed;
// 删除超出画布的子弹
if(bullets[i].y < 0) {
bullets.splice(i, 1);
i--;
}
}
// 绘制敌机
ctx.fillStyle = '#0f0';
for(var i = 0; i < enemies.length; i++) {
ctx.fillRect(enemies[i].x, enemies[i].y, enemies[i].width, enemies[i].height);
enemies[i].y += enemies[i].speed;
// 删除超出画布的敌机
if(enemies[i].y > canvas.height) {
enemies.splice(i, 1);
i--;
}
// 检测子弹和敌机是否相撞
for(var j = 0; j < bullets.length; j++) {
if(bullets[j].x + bullets[j].width > enemies[i].x
&& bullets[j].x < enemies[i].x + enemies[i].width
&& bullets[j].y + bullets[j].height > enemies[i].y
&& bullets[j].y < enemies[i].y + enemies[i].height) {
bullets.splice(j, 1);
j--;
enemies.splice(i, 1);
i--;
score += 10;
}
}
}
// 绘制分数
ctx.fillStyle = '#000';
ctx.font = '20px Arial';
ctx.fillText('分数:' + score, 10, 30);
// 添加敌机
if(Math.random() < 0.1) {
enemies.push({
x: Math.random() * canvas.width,
y: 0,
speed: Math.random() * 5 + 1,
width: 50,
height: 50
});
}
}
// 定时更新游戏
setInterval(update, 30);
- 运行HTML页面,即可看到飞机大战游戏,可以使用左右箭头控制飞机移动,空格键发射子弹,子弹击中敌机得分。
原文地址: http://www.cveoy.top/t/topic/beaG 著作权归作者所有。请勿转载和采集!