用HTML语言写一段坦克大战,给出完整代码,不要写任何注释
时间: 2024-05-29 20:04:40 浏览: 18
<html>
<body>
<canvas id="myCanvas" width="800" height="600"></canvas>
<script>
// 创建坦克
class Tank {
constructor(x, y, color) {
this.x = x;
this.y = y;
this.color = color;
this.angle = 0;
}
draw(ctx) {
ctx.save();
ctx.translate(this.x, this.y);
ctx.rotate((this.angle / 180) * Math.PI);
ctx.fillStyle = this.color;
ctx.fillRect(-20, -10, 40, 20);
ctx.fillRect(-10, -20, 20, 40);
ctx.restore();
}
move(direction) {
if (direction === 'up') {
this.y -= 5;
} else if (direction === 'down') {
this.y += 5;
} else if (direction === 'left') {
this.x -= 5;
} else if (direction === 'right') {
this.x += 5;
}
}
}
// 初始化画布
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 创建玩家坦克
const player = new Tank(400, 300, 'blue');
// 创建敌人坦克
const enemy = new Tank(200, 100, 'red');
// 游戏循环
function gameLoop() {
// 清除画布
ctx.clearRect(0, 0, 800, 600);
// 画出玩家坦克
player.draw(ctx);
// 画出敌人坦克
enemy.draw(ctx);
// 循环
requestAnimationFrame(gameLoop);
}
// 开始游戏
gameLoop();
// 监听键盘事件
document.addEventListener('keydown', (event) => {
if (event.key === 'ArrowUp') {
player.move('up');
} else if (event.key === 'ArrowDown') {
player.move('down');
} else if (event.key === 'ArrowLeft') {
player.move('left');
} else if (event.key === 'ArrowRight') {
player.move('right');
}
});
</script>
</body>
</html>
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)