一、实现思路
1. 创建游戏画布和画笔;
2. 定义坦克、子弹和敌人,并设置相应的属性;
3. 定义相应的事件监听器,例如键盘事件监听器和计时器事件监听器,实现坦克和子弹的移动以及碰撞检测等功能;
4. 实现游戏界面的渲染,例如画出坦克、子弹和敌人的形状,并根据相应的属性进行渲染;
5. 实现游戏的控制逻辑,例如坦克与子弹的交互以及敌人与子弹的交互,以此来实现游戏胜利或失败的判断。
二、代码示例
1. 定义坦克和子弹,以及相应的移动和碰撞检测函数
class Tank {
constructor(x, y, direction) {
this.x = x;
this.y = y;
this.direction = direction; // 方向
this.speed = 5; // 移动速度
this.width = 50; // 宽
this.height = 50; // 高
}
move() {
if(this.direction === 'up'){
this.y -= this.speed;
}else if(this.direction === 'down'){
this.y += this.speed;
}else if(this.direction === 'left'){
this.x -= this.speed;
}else if(this.direction === 'right'){
this.x += this.speed;
}
}
isCollision(target) {
let overlapX = false; // x方向是否重叠
let overlapY = false; // y方向是否重叠
if(Math.abs(this.x - target.x) < this.width / 2 + target.width / 2) {
overlapX = true;
}
if(Math.abs(this.y - target.y) < this.height / 2 + target.height / 2) {
overlapY = true;
}
if(overlapX && overlapY) {
return true;
}
return false;
}
}
class Bullet {
constructor(x, y, direction, tankWidth, tankHeight) {
this.x = x;
this.y = y;
this.direction = direction; // 方向
this.speed = 10; // 移动速度
this.width = 10; // 宽
this.height = 10; // 高
this.tankWidth = tankWidth; // 所属坦克的宽
this.tankHeight = tankHeight; // 所属坦克的高
}
move() {
if(this.direction === 'up'){
this.y -= this.speed;
}else if(this.direction === 'down'){
this.y += this.speed;
}else if(this.direction === 'left'){
this.x -= this.speed;
}else if(this.direction === 'right'){
this.x += this.speed;
}
}
isOutCanvas(canvasWidth, canvasHeight) {
if(this.x - this.width / 2 < 0 || this.x + this.width / 2 > canvasWidth || this.y - this.height / 2 < 0 || this.y + this.height / 2 > canvasHeight){
return true;
}
return false;
}
isCollision(target) {
let overlapX = false; // x方向是否重叠
let overlapY = false; // y方向是否重叠
if(Math.abs(this.x - target.x) < this.tankWidth / 2 + this.width / 2) {
overlapX = true;
}
if(Math.abs(this.y - target.y) < this.tankHeight / 2 + this.height / 2) {
overlapY = true;
}
if(overlapX && overlapY) {
return true;
}
return false;
}
}
function checkCollision() {
// 子弹与坦克碰撞检测
for(let i = 0; i < bullets.length; i++){
for(let j = 0; j < enemyTanks.length; j++){
if(bullets[i].isCollision(enemyTanks[j])) {
// 移除子弹和敌人坦克
bullets.splice(i, 1);
enemyTanks.splice(j, 1);
// 记录分数
score++;
// 更新UI
renderScore();
}
}
if(playerTank && bullets[i].isCollision(playerTank)) {
// 游戏失败,移除玩家坦克,清空计时器
clearInterval(timer);
playerTank = null;
alert('游戏失败!');
}
}
// 玩家坦克与敌人坦克碰撞检测
for(let i = 0; i < enemyTanks.length; i++){
if(playerTank && playerTank.isCollision(enemyTanks[i])) {
// 游戏失败,移除玩家坦克,清空计时器
clearInterval(timer);
playerTank = null;
alert('游戏失败!');
}
}
// 游戏胜利
if(enemyTanks.length === 0 && playerTank) {
clearInterval(timer);
alert('游戏胜利!');
}
}
本文链接:http://task.lmcjl.com/news/8471.html