百余行VUE代码实现贪吃蛇小游戏简易版
前几天使用qt qwidget实现了一个贪吃蛇小游戏后,突然想到vue好像还没有写过贪吃蛇的小demo,所以就花了一点时间写了一个 话不多说 上代码。
<template>
<div class="map">
<span
v-for="(item, index) in map"
:key="index"
:class="{
base: true,
header: index == 0,
body: index != 0,
}"
:style="{
left: item.x * 10 + 'px',
top: item.y * 10 + 'px',
}"
>
</span>
<span
class="base food"
:style="{
left: food.x * 10 + 'px',
top: food.y * 10 + 'px',
}"
></span>
</div>
</template>
<script>
export default {
data() {
return {
map: [],
timer: null,
nowdir: "r",
dir: {
l: {
x: -1,
y: 0,
},
r: {
x: 1,
y: 0,
},
u: {
x: 0,
y: -1,
},
d: {
x: 0,
y: 1,
},
},
food: {
x: 0,
y: 0,
},
dirConst: {
ArrowUp: "u",
ArrowLeft: "l",
ArrowDown: "d",
ArrowRight: "r",
},
};
},
created() {
// 初始化蛇
this.initsnake();
// 初始化食物
this.initfood();
// 蛇动起来
this.initMove();
},
mounted() {
window.addEventListener("keydown", (Event) => {
if (this.dirConst[Event.code]) {
this.changeDirection(this.dirConst[Event.code]);
}
});
},
methods: {
initsnake() {
this.map.push({ x: 2, y: 0 }, { x: 1, y: 0 });
},
initfood() {
this.food.x = parseInt(Math.random() * 100);
this.food.y = parseInt(Math.random() * 100);
},
initMove() {
this.timer = setInterval(() => {
let next = this.snakeNextMove();
if (next.x < 0 || next.x > 99 || next.y < 0 || next.y > 99) {
// 撞墙了
clearInterval(this.timer);
} else if (next.x == this.food.x && next.y == this.food.y) {
this.snakeEat();
} else {
this.snakeMove();
}
}, 50);
},
snakeNextMove() {
// 下一次移动的下标
return {
x: this.map[0].x + this.dir[this.nowdir].x,
y: this.map[0].y + this.dir[this.nowdir].y,
};
},
snakeEat() {
this.map.unshift({
x: this.map[0].x + this.dir[this.nowdir].x,
y: this.map[0].y + this.dir[this.nowdir].y,
});
this.initfood();
},
snakeMove() {
this.map.unshift({
x: this.map[0].x + this.dir[this.nowdir].x,
y: this.map[0].y + this.dir[this.nowdir].y,
});
this.map.pop();
},
changeDirection(dir) {
let str = this.nowdir + dir;
if (str == "lr" || str == "rl" || str == "ud" || str == "du") {
return;
}
this.nowdir = dir;
},
},
};
</script>
<style lang="scss" scoped>
.map {
width: 1000px;
height: 1000px;
display: flex;
position: relative;
border: 10px solid blue;
.base {
width: 10px;
height: 10px;
box-sizing: border-box;
position: absolute;
}
.food {
border: 1px solid forestgreen;
}
.header {
border: 1px solid red;
}
.body {
border: 1px solid black;
}
}
</style>
代码量不多。实现的只是一个简易版的。感兴趣的同学可以试试