您的位置:首页 > Web前端 > Vue.js

如何用VUE和Canvas实现雷霆战机打字类小游戏

2021-04-15 04:06 806 查看

今天就来实现一个雷霆战机打字游戏,玩法很简单,每一个“敌人”都是一些英文单词,键盘正确打出单词的字母,飞机就会发射一个个子弹消灭“敌人”,每次需要击毙当前“敌人”后才能击毙下一个,一个比手速和单词熟练度的游戏。

首先来看看最终效果图:

emmmmmmmmmmmmm,界面UI做的很简单,先实现基本功能,再考虑高大上的UI吧。

首先依旧是来分析界面组成:

(1)固定在画面底部中间的飞机;

(2)从画面上方随机产生的敌人(单词);

(3)从飞机头部发射出去,直奔敌人而去的子弹;

(4)游戏结束后的分数显示。

这次的游戏和之前的比,运动的部分貌似更多且更复杂了。在flappy bird中,虽然管道是运动的,但是小鸟的x坐标和管道的间隔、宽度始终不变,比较容易计算边界;在弹球消砖块游戏中,木板和砖块都是相对简单或者固定的坐标,只用判定弹球的边界和砖块的触碰面积就行。在雷霆战机消单词游戏中,无论是降落的目标单词,还是飞出去的子弹,都有着各自的运动轨迹,但是子弹又要追寻着目标而去,所以存在着一个实时计算轨道的操作。

万丈高楼平地起,说了那么多,那就从最简单的开始着手吧!

1、固定在画面底部中间的飞机

这个很简单没啥好说的,这里默认飞机宽度高度为40像素单位,然后将飞机画在画面的底部中间:

drawPlane() {
let _this = this;
_this.ctx.save();
_this.ctx.drawImage(
_this.planeImg,
_this.clientWidth / 2 - 20,
_this.clientHeight - 20 - 40,
40,
40
);
_this.ctx.restore();
},

2、从画面上方随机产生的敌人

这里默认设置每次在画面中最多只出现3个单词靶子,靶子的y轴移动速度为1.3,靶子的半径大小为10:

const _MAX_TARGET = 3; // 画面中一次最多出现的目标

const _TARGET_CONFIG = {
// 靶子的固定参数

speed: 1.3,

radius: 10

};

然后我们一开始要随机在词库数组里取出_MAX_TARGET个不重复的单词,并把剩下的词放进循环词库this.wordsPool中去:

generateWord(number) {
// 从池子里随机挑选一个词,不与已显示的词重复
let arr = [];
for (let i = 0; i < number; i++) {
let random = Math.floor(Math.random() * this.wordsPool.length);
arr.push(this.wordsPool[random]);
this.wordsPool.splice(random, 1);
}
return arr;
},
generateTarget() {
// 随机生成目标
let _this = this;
let length = _this.targetArr.length;
if (length < _MAX_TARGET) {
let txtArr = _this.generateWord(_MAX_TARGET - length);
for (let i = 0; i < _MAX_TARGET - length; i++) {
_this.targetArr.push({
x: _this.getRandomInt(
_TARGET_CONFIG.radius,
_this.clientWidth - _TARGET_CONFIG.radius
),
y: _TARGET_CONFIG.radius * 2,
txt: txtArr[i],
typeIndex: -1,
hitIndex: -1,
dx: (_TARGET_CONFIG.speed * Math.random().toFixed(1)) / 2,
dy: _TARGET_CONFIG.speed * Math.random().toFixed(1),
rotate: 0
});
}
}
}

可以看出,this.targetArr是存放目标对象的数组:

一个初始的目标有随机分布在画面宽度的x;

y轴值为直径;

txt记录靶子代表的单词;

typeIndex记录“轰炸”这个单词时正在敲击的字符索引下标(用来分离已敲击字符和未敲击字符);

hitIndex记录“轰炸”这个单词时子弹轰炸的索引下标(因为子弹真正轰炸掉目标是在打完单词之后,毕竟子弹有飞行时间,所以通过hitIndex来判断子弹什么时候被击碎消失);

dx是靶子每帧在x轴偏移距离;

dy是靶子每帧在y轴偏移距离;

rotate设置靶子自转角度。

好了,生成了3个靶子,我们就让靶子先从上往下动起来吧:

drawTarget() {
// 逐帧画目标
let _this = this;
_this.targetArr.forEach((item, index) => {
_this.ctx.save();
_this.ctx.translate(item.x, item.y); //设置旋转的中心点
_this.ctx.beginPath();
_this.ctx.font = "14px Arial";
if (
index === _this.currentIndex ||
item.typeIndex === item.txt.length - 1
) {
_this.drawText(
item.txt.substring(0, item.typeIndex + 1),
-item.txt.length * 3,
_TARGET_CONFIG.radius * 2,
"gray"
);
let width = _this.ctx.measureText(
item.txt.substring(0, item.typeIndex + 1)
).width; // 获取已敲击文字宽度
_this.drawText(
item.txt.substring(item.typeIndex + 1, item.txt.length),
-item.txt.length * 3 + width,
_TARGET_CONFIG.radius * 2,
"red"
);
} else {
_this.drawText(
item.txt,
-item.txt.length * 3,
_TARGET_CONFIG.radius * 2,
"yellow"
);
}

_this.ctx.closePath();
_this.ctx.rotate((item.rotate * Math.PI) / 180);
_this.ctx.drawImage(
_this.targetImg,
-1 * _TARGET_CONFIG.radius,
-1 * _TARGET_CONFIG.radius,
_TARGET_CONFIG.radius * 2,
_TARGET_CONFIG.radius * 2
);
_this.ctx.restore();
item.y += item.dy;
item.x += item.dx;
if (item.x < 0 || item.x > _this.clientWidth) {
item.dx *= -1;
}
if (item.y > _this.clientHeight - _TARGET_CONFIG.radius * 2) {
// 碰到底部了
_this.gameOver = true;
}
// 旋转
item.rotate++;
});
}

这一步画靶子没有什么特别的,随机得增加dx和dy,在碰到左右边缘时反弹。主要一点就是单词的绘制,通过typeIndex将单词一分为二,敲击过的字符置为灰色,然后通过measureText获取到敲击字符的宽度从而设置未敲击字符的x轴偏移量,将未敲击的字符设置为红色,提示玩家这个单词是正在攻击中的目标。

3、从飞机头部发射出去,直奔敌人而去的子弹

子弹是这个游戏的关键部分,在绘制子弹的时候要考虑哪些方面呢?

(1)目标一直是运动的,发射出去的子弹要一直“追踪”目标,所以路径是动态变化的;

(2)一个目标需要被若干个子弹消灭掉,所以什么时候子弹才从画面中抹去;

(3)当一个目标单词被敲击完了后,下一批子弹就要朝向下一个目标射击,所以子弹的路径是单独的;

(4)如何绘制出子弹的拖尾效果;

(5)如果锁定正在敲击的目标单词,使玩家敲完当前单词才能去击破下一个单词

这里先设置几个变量:

bulletArr: [], // 存放子弹对象

currentIndex: -1  //当前锁定的目标在targetArr中的索引

首先我们先来写一下键盘按下时要触发的函数:

handleKeyPress(key) {
// 键盘按下,判断当前目标
let _this = this;
if (_this.currentIndex === -1) {
// 当前没有在射击的目标
let index = _this.targetArr.findIndex(item => {
return item.txt.indexOf(key) === 0;
});
if (index !== -1) {
_this.currentIndex = index;
_this.targetArr[index].typeIndex = 0;
_this.createBullet(index);
}
} else {
// 已有目标正在被射击
if (
key ===
_this.targetArr[_this.currentIndex].txt.split("")[
_this.targetArr[_this.currentIndex].typeIndex + 1
]
) {
// 获取到目标对象
_this.targetArr[_this.currentIndex].typeIndex++;
_this.createBullet(_this.currentIndex);

if (
_this.targetArr[_this.currentIndex].typeIndex ===
_this.targetArr[_this.currentIndex].txt.length - 1
) {
// 这个目标已经别射击完毕
_this.currentIndex = -1;
}
}
}
},
// 发射一个子弹
createBullet(index) {
let _this = this;
this.bulletArr.push({
dx: 1,
dy: 4,
x: _this.clientWidth / 2,
y: _this.clientHeight - 60,
targetIndex: index
});
}

这个函数做的事情很明确,拿到当前键盘按下的字符,如果currentIndex ===-1,证明没有正在被攻击的靶子,所以就去靶子数组里看,哪个单词的首字母等于该字符,则设置currentIndex为该单词的索引,并发射一个子弹;如果已经有正在被攻击的靶子,则看还未敲击的单词的第一个字符是否符合,若符合,则增加该靶子对象的typeIndex,并发射一个子弹,若当前靶子已敲击完毕,则重置currentIndex为-1。

接下来就是画子弹咯:

drawBullet() {
// 逐帧画子弹
let _this = this;
// 判断子弹是否已经击中目标
if (_this.bulletArr.length === 0) {
return;
}
_this.bulletArr = _this.bulletArr.filter(_this.firedTarget);
_this.bulletArr.forEach(item => {
let targetX = _this.targetArr[item.targetIndex].x;
let targetY = _this.targetArr[item.targetIndex].y;
let k =
(_this.clientHeight - 60 - targetY) /
(_this.clientWidth / 2 - targetX); // 飞机头和目标的斜率
let b = targetY - k * targetX; // 常量b
item.y = item.y - bullet.dy; // y轴偏移一个单位
item.x = (item.y - b) / k;
for (let i = 0; i < 15; i++) {
// 画出拖尾效果
_this.ctx.beginPath();
_this.ctx.arc(
(item.y + i * 1.8 - b) / k,
item.y + i * 1.8,
4 - 0.2 * i,
0,
2 * Math.PI
);
_this.ctx.fillStyle = `rgba(193,255,255,${1 - 0.08 * i})`;
_this.ctx.fill();
_this.ctx.closePath();
}
});
},
firedTarget(item) {
// 判断是否击中目标
let _this = this;
if (
item.x > _this.targetArr[item.targetIndex].x - _TARGET_CONFIG.radius &&
item.x < _this.targetArr[item.targetIndex].x + _TARGET_CONFIG.radius &&
item.y > _this.targetArr[item.targetIndex].y - _TARGET_CONFIG.radius &&
item.y < _this.targetArr[item.targetIndex].y + _TARGET_CONFIG.radius
) {
// 子弹击中了目标
let arrIndex = item.targetIndex;
_this.targetArr[arrIndex].hitIndex++;
if (
_this.targetArr[arrIndex].txt.length - 1 ===
_this.targetArr[arrIndex].hitIndex
) {
// 所有子弹全部击中了目标
let word = _this.targetArr[arrIndex].txt;
_this.targetArr[arrIndex] = {
// 生成新的目标
x: _this.getRandomInt(
_TARGET_CONFIG.radius,
_this.clientWidth - _TARGET_CONFIG.radius
),
y: _TARGET_CONFIG.radius * 2,
txt: _this.generateWord(1)[0],
typeIndex: -1,
hitIndex: -1,
dx: (_TARGET_CONFIG.speed * Math.random().toFixed(1)) / 2,
dy: _TARGET_CONFIG.speed * Math.random().toFixed(1),
rotate: 0
};
_this.wordsPool.push(word); // 被击中的目标词重回池子里
_this.score++;
}
return false;
} else {
return true;
}
}

其实也很简单,我们在子弹对象中用targetIndex来记录该子弹所攻击的目标索引,然后就是一个y = kx+b的解方程得到飞机头部(子弹出发点)和靶子的轨道函数,计算出每一帧下每个子弹的移动坐标,就可以画出子弹了;

拖尾效果就是沿轨道y轴增长方向画出若干个透明度和半径逐渐变小的圆,就能实现拖尾效果了;

在firedTarget()函数中,用来过滤出已击中靶子的子弹,为了不影响还在被攻击的其他靶子在targetArr中的索引,不用splice删除,而是直接重置被消灭靶子的值,从wordPool中选出新的词,并把当前击碎的词重新丢回池子里,从而保证画面中不会出现重复的靶子。

4、游戏结束后的得分文字效果

游戏结束就是有目标靶子触碰到了底部就结束了。

这里其实是个彩蛋了,怎么样可以用canvas画出这种闪烁且有光晕的文字呢?切换颜色并且叠buff就行了,不是,叠轮廓stroke就行了

drawGameOver() {
let _this = this;
//保存上下文对象的状态
_this.ctx.save();
_this.ctx.font = "34px Arial";
_this.ctx.strokeStyle = _this.colors[0];
_this.ctx.lineWidth = 2;
//光晕
_this.ctx.shadowColor = "#FFFFE0";
let txt = "游戏结束,得分:" + _this.score;
let width = _this.ctx.measureText(txt).width;
for (let i = 60; i > 3; i -= 2) {
_this.ctx.shadowBlur = i;
_this.ctx.strokeText(txt, _this.clientWidth / 2 - width / 2, 300);
}
_this.ctx.restore();
_this.colors.reverse();
}

好了好了,做到这里就是个还算完整的小游戏了,只是UI略显粗糙,如果想做到真正雷霆战机那么酷炫带爆炸的效果那还需要很多素材和canvas的绘制。

canvas很强大很好玩,只要脑洞够大,这张画布上你想画啥就可以画啥~

老规矩,po上vue的完整代码供大家参考学习:

<template>
<div class="type-game">
<canvas id="type" width="400" height="600"></canvas>
</div>
</template>

<script>
const _MAX_TARGET = 3; // 画面中一次最多出现的目标
const _TARGET_CONFIG = {
// 靶子的固定参数
speed: 1.3,
radius: 10
};
const _DICTIONARY = ["apple", "orange", "blue", "green", "red", "current"];
export default {
name: "TypeGame",
data() {
return {
ctx: null,
clientWidth: 0,
clientHeight: 0,
bulletArr: [], // 屏幕中的子弹
targetArr: [], // 存放当前目标
targetImg: null,
planeImg: null,
currentIndex: -1,
wordsPool: [],
score: 0,
gameOver: false,
colors: ["#FFFF00", "#FF6666"]
};
},
mounted() {
let _this = this;
_this.wordsPool = _DICTIONARY.concat([]);
let container = document.getElementById("type");
_this.clientWidth = container.width;
_this.clientHeight = container.height;
_this.ctx = container.getContext("2d");
_this.targetImg = new Image();
_this.targetImg.src = require("@/assets/img/target.png");

_this.planeImg = new Image();
_this.planeImg.src = require("@/assets/img/plane.png");

document.onkeydown = function(e) {
let key = window.event.keyCode;
if (key >= 65 && key <= 90) {
_this.handleKeyPress(String.fromCharCode(key).toLowerCase());
}
};

_this.targetImg.onload = function() {
_this.generateTarget();
(function animloop() {
if (!_this.gameOver) {
_this.drawAll();
} else {
_this.drawGameOver();
}
window.requestAnimationFrame(animloop);
})();
};
},
methods: {drawGameOver() {
let _this = this;
//保存上下文对象的状态
_this.ctx.save();
_this.ctx.font = "34px Arial";
_this.ctx.strokeStyle = _this.colors[0];
_this.ctx.lineWidth = 2;
//光晕
_this.ctx.shadowColor = "#FFFFE0";
let txt = "游戏结束,得分:" + _this.score;
let width = _this.ctx.measureText(txt).width;
for (let i = 60; i > 3; i -= 2) {
_this.ctx.shadowBlur = i;
_this.ctx.strokeText(txt, _this.clientWidth / 2 - width / 2, 300);
}
_this.ctx.restore();
_this.colors.reverse();
},
drawAll() {
let _this = this;
_this.ctx.clearRect(0, 0, _this.clientWidth, _this.clientHeight);
_this.drawPlane(0);
_this.drawBullet();
_this.drawTarget();
_this.drawScore();
},drawPlane() {
let _this = this;
_this.ctx.save();
_this.ctx.drawImage(
_this.planeImg,
_this.clientWidth / 2 - 20,
_this.clientHeight - 20 - 40,
40,
40
);
_this.ctx.restore();
},generateWord(number) {
// 从池子里随机挑选一个词,不与已显示的词重复
let arr = [];
for (let i = 0; i < number; i++) {
let random = Math.floor(Math.random() * this.wordsPool.length);
arr.push(this.wordsPool[random]);
this.wordsPool.splice(random, 1);
}
return arr;
},
generateTarget() {
// 随机生成目标
let _this = this;
let length = _this.targetArr.length;
if (length < _MAX_TARGET) {
let txtArr = _this.generateWord(_MAX_TARGET - length);
for (let i = 0; i < _MAX_TARGET - length; i++) {
_this.targetArr.push({
x: _this.getRandomInt(
_TARGET_CONFIG.radius,
_this.clientWidth - _TARGET_CONFIG.radius
),
y: _TARGET_CONFIG.radius * 2,
txt: txtArr[i],
typeIndex: -1,
hitIndex: -1,
dx: (_TARGET_CONFIG.speed * Math.random().toFixed(1)) / 2,
dy: _TARGET_CONFIG.speed * Math.random().toFixed(1),
rotate: 0
});
}
}
},
getRandomInt(n, m) {
return Math.floor(Math.random() * (m - n + 1)) + n;
},
drawText(txt, x, y, color) {
let _this = this;
_this.ctx.fillStyle = color;
_this.ctx.fillText(txt, x, y);
},
drawScore() {
// 分数
this.drawText("分数:" + this.score, 10, this.clientHeight - 10, "#fff");
},drawTarget() {
// 逐帧画目标
let _this = this;
_this.targetArr.forEach((item, index) => {
_this.ctx.save();
_this.ctx.translate(item.x, item.y); //设置旋转的中心点
_this.ctx.beginPath();
_this.ctx.font = "14px Arial";
if (
index === _this.currentIndex ||
item.typeIndex === item.txt.length - 1
) {
_this.drawText(
item.txt.substring(0, item.typeIndex + 1),
-item.txt.length * 3,
_TARGET_CONFIG.radius * 2,
"gray"
);
let width = _this.ctx.measureText(
item.txt.substring(0, item.typeIndex + 1)
).width; // 获取已敲击文字宽度
_this.drawText(
item.txt.substring(item.typeIndex + 1, item.txt.length),
-item.txt.length * 3 + width,
_TARGET_CONFIG.radius * 2,
"red"
);
} else {
_this.drawText(
item.txt,
-item.txt.length * 3,
_TARGET_CONFIG.radius * 2,
"yellow"
);
}

_this.ctx.closePath();
_this.ctx.rotate((item.rotate * Math.PI) / 180);
_this.ctx.drawImage(
_this.targetImg,
-1 * _TARGET_CONFIG.radius,
-1 * _TARGET_CONFIG.radius,
_TARGET_CONFIG.radius * 2,
_TARGET_CONFIG.radius * 2
);
_this.ctx.restore();
item.y += item.dy;
item.x += item.dx;
if (item.x < 0 || item.x > _this.clientWidth) {
item.dx *= -1;
}
if (item.y > _this.clientHeight - _TARGET_CONFIG.radius * 2) {
// 碰到底部了
_this.gameOver = true;
}
// 旋转
item.rotate++;
});
},handleKeyPress(key) {
// 键盘按下,判断当前目标
let _this = this;
if (_this.currentIndex === -1) {
// 当前没有在射击的目标
let index = _this.targetArr.findIndex(item => {
return item.txt.indexOf(key) === 0;
});
if (index !== -1) {
_this.currentIndex = index;
_this.targetArr[index].typeIndex = 0;
_this.createBullet(index);
}
} else {
// 已有目标正在被射击
if (
key ===
_this.targetArr[_this.currentIndex].txt.split("")[
_this.targetArr[_this.currentIndex].typeIndex + 1
]
) {
// 获取到目标对象
_this.targetArr[_this.currentIndex].typeIndex++;
_this.createBullet(_this.currentIndex);

if (
_this.targetArr[_this.currentIndex].typeIndex ===
_this.targetArr[_this.currentIndex].txt.length - 1
) {
// 这个目标已经别射击完毕
_this.currentIndex = -1;
}
}
}
},
// 发射一个子弹
createBullet(index) {
let _this = this;
this.bulletArr.push({
dx: 1,
dy: 4,
x: _this.clientWidth / 2,
y: _this.clientHeight - 60,
targetIndex: index
});
},
firedTarget(item) {
// 判断是否击中目标
let _this = this;
if (
item.x > _this.targetArr[item.targetIndex].x - _TARGET_CONFIG.radius &&
item.x < _this.targetArr[item.targetIndex].x + _TARGET_CONFIG.radius &&
item.y > _this.targetArr[item.targetIndex].y - _TARGET_CONFIG.radius &&
item.y < _this.targetArr[item.targetIndex].y + _TARGET_CONFIG.radius
) {
// 子弹击中了目标
let arrIndex = item.targetIndex;
_this.targetArr[arrIndex].hitIndex++;
if (
_this.targetArr[arrIndex].txt.length - 1 ===
_this.targetArr[arrIndex].hitIndex
) {
// 所有子弹全部击中了目标
let word = _this.targetArr[arrIndex].txt;
_this.targetArr[arrIndex] = {
// 生成新的目标
x: _this.getRandomInt(
_TARGET_CONFIG.radius,
_this.clientWidth - _TARGET_CONFIG.radius
),
y: _TARGET_CONFIG.radius * 2,
txt: _this.generateWord(1)[0],
typeIndex: -1,
hitIndex: -1,
dx: (_TARGET_CONFIG.speed * Math.random().toFixed(1)) / 2,
dy: _TARGET_CONFIG.speed * Math.random().toFixed(1),
rotate: 0
};
_this.wordsPool.push(word); // 被击中的目标词重回池子里
_this.score++;
}
return false;
} else {
return true;
}
},
drawBullet() {
// 逐帧画子弹
let _this = this;
// 判断子弹是否已经击中目标
if (_this.bulletArr.length === 0) {
return;
}
_this.bulletArr = _this.bulletArr.filter(_this.firedTarget);
_this.bulletArr.forEach(item => {
let targetX = _this.targetArr[item.targetIndex].x;
let targetY = _this.targetArr[item.targetIndex].y;
let k =
(_this.clientHeight - 60 - targetY) /
(_this.clientWidth / 2 - targetX); // 飞机头和目标的斜率
let b = targetY - k * targetX; // 常量b
item.y = item.y - 4; // y轴偏移一个单位
item.x = (item.y - b) / k;
for (let i = 0; i < 15; i++) {
// 画出拖尾效果
_this.ctx.beginPath();
_this.ctx.arc(
(item.y + i * 1.8 - b) / k,
item.y + i * 1.8,
4 - 0.2 * i,
0,
2 * Math.PI
);
_this.ctx.fillStyle = `rgba(193,255,255,${1 - 0.08 * i})`;
_this.ctx.fill();
_this.ctx.closePath();
}
});
}
}
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.type-game {
#type {
background: #2a4546;
}
}
</style>

以上就是如何用VUE和Canvas实现雷霆战机打字类小游戏的详细内容,更多关于VUE雷霆战机小游戏的资料请关注脚本之家其它相关文章!

您可能感兴趣的文章:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  VUE Canvas 游戏