vue2实现“猜猜红心a在哪里”的小游戏
时间: 2023-12-26 20:05:06 浏览: 23
好的,以下是一个简单的实现步骤:
1. 创建一个 Vue 项目。
2. 在 App.vue 中添加一个 div,用来显示游戏界面。
3. 在 data 中定义一个数组,用来存储猜测的结果。
4. 在 mounted 生命周期函数中,初始化游戏,包括生成随机的红心 a 和游戏界面中的格子。
5. 在游戏界面中,将红心 a 和格子都用一个 div 包裹起来,通过 v-for 指令生成多个格子。
6. 给格子添加点击事件,点击后将该格子的索引值存入猜测结果数组中。
7. 定义一个判断是否猜对的方法,将猜测结果与红心 a 的索引值进行比较,如果相等则猜对,否则提示“猜错了”。
8. 在游戏界面下方添加一个“重新开始”的按钮,点击后重新初始化游戏。
下面是示例代码:
```html
<template>
<div class="game">
<div class="board">
<div v-for="(item, index) in board" :key="index" class="cell" @click="guess(index)">
<div class="heart" v-if="index === heartIndex">a</div>
</div>
</div>
<div class="result">{{ result }}</div>
<button @click="restart">重新开始</button>
</div>
</template>
<script>
export default {
data() {
return {
board: [],
heartIndex: -1,
guesses: [],
result: '',
};
},
mounted() {
this.init();
},
methods: {
init() {
this.board = Array.from({ length: 9 }, (_, index) => index);
this.heartIndex = Math.floor(Math.random() * 9);
this.guesses = [];
this.result = '';
},
guess(index) {
if (this.guesses.includes(index)) {
return;
}
this.guesses.push(index);
if (this.guesses.length === 3) {
this.checkResult();
}
},
checkResult() {
if (this.guesses.includes(this.heartIndex)) {
this.result = '猜对了';
} else {
this.result = '猜错了';
}
},
restart() {
this.init();
},
},
};
</script>
<style scoped>
.board {
display: flex;
flex-wrap: wrap;
width: 300px;
height: 300px;
margin: 0 auto;
}
.cell {
display: flex;
justify-content: center;
align-items: center;
width: 32%;
height: 32%;
border: 1px solid #ccc;
}
.heart {
font-size: 32px;
color: red;
}
.result {
text-align: center;
margin-top: 10px;
}
button {
display: block;
margin: 10px auto;
}
</style>
```