返回
用CSS3+Vue打造趣味十足的养鱼小游戏:点击投食,鱼儿争抢食物不断成长
前端
2024-01-21 05:40:32
在工作繁忙之余,很多人都喜欢在办公室或者家里养几条小鱼,用来缓解压力,陶冶情操。然而,对于一些上班族来说,照顾鱼儿可能是一件比较麻烦的事情。现在,我们可以利用CSS3和Vue.js来创建一个虚拟的养鱼小游戏,让大家在闲暇之余也能体验养鱼的乐趣。
游戏规则
这个CSS3+Vue养鱼小游戏非常简单,规则如下:
- 当你点击屏幕时,屏幕上会出现随机位置的食物。
- 鱼儿会争抢食物,吃到食物的鱼儿会变得更大一点。
- 如果鱼儿长时间吃不到食物,它们会慢慢变小,最终消失。
游戏实现
这个游戏是用CSS3和Vue.js实现的。我们首先创建一个Vue组件来表示鱼缸。然后,我们使用CSS3来创建鱼儿和食物的样式。最后,我们使用Vue.js来控制游戏逻辑。
鱼缸组件
// 鱼缸组件
const FishTank = {
template: '<div class="fish-tank"></div>',
data() {
return {
fish: [], // 鱼儿数组
food: [], // 食物数组
timer: null // 游戏定时器
};
},
mounted() {
this.init();
},
methods: {
init() {
// 创建鱼儿
for (let i = 0; i < 10; i++) {
this.fish.push({
x: Math.random() * 300,
y: Math.random() * 300,
size: 20
});
}
// 创建食物
for (let i = 0; i < 10; i++) {
this.food.push({
x: Math.random() * 300,
y: Math.random() * 300
});
}
// 启动游戏定时器
this.timer = setInterval(() => {
this.update();
}, 100);
},
update() {
// 更新鱼儿位置
this.fish.forEach(fish => {
fish.x += Math.random() * 2 - 1;
fish.y += Math.random() * 2 - 1;
// 检查鱼儿是否吃到食物
this.food.forEach((food, index) => {
if (fish.x > food.x - fish.size / 2 && fish.x < food.x + fish.size / 2 && fish.y > food.y - fish.size / 2 && fish.y < food.y + fish.size / 2) {
// 鱼儿吃到食物,鱼儿变大,食物消失
fish.size += 2;
this.food.splice(index, 1);
}
});
// 检查鱼儿是否超出鱼缸范围
if (fish.x < 0) {
fish.x = 0;
} else if (fish.x > 300) {
fish.x = 300;
}
if (fish.y < 0) {
fish.y = 0;
} else if (fish.y > 300) {
fish.y = 300;
}
});
// 检查鱼儿是否消失
this.fish = this.fish.filter(fish => fish.size > 0);
// 创建食物
if (this.food.length < 10) {
this.food.push({
x: Math.random() * 300,
y: Math.random() * 300
});
}
}
}
};
鱼儿组件
// 鱼儿组件
const Fish = {
props: ['x', 'y', 'size'],
template: '<div class="fish" :style="{ left: x + \'px\', top: y + \'px\', width: size + \'px\', height: size + \'px\' }"></div>'
};
食物组件
// 食物组件
const Food = {
props: ['x', 'y'],
template: '<div class="food" :style="{ left: x + \'px\', top: y + \'px\' }"></div>'
};
游戏主程序
// 游戏主程序
const app = new Vue({
components: {
FishTank,
Fish,
Food
},
template: '<fish-tank></fish-tank>'
}).$mount('#app');
结语
这个CSS3+Vue养鱼小游戏非常有趣,可以用来打发时间,放松心情。大家可以根据自己的喜好,修改游戏规则,或者添加更多的功能。希望大家能够喜欢这个游戏!