基于vue2写一个简单的游戏代码
时间: 2024-05-09 07:15:21 浏览: 15
这里提供一个简单的猜数字游戏的代码示例,使用Vue2编写。
HTML代码:
```html
<div id="app">
<h1>猜数字游戏</h1>
<p>请猜一个1-100之间的数字</p>
<input type="text" v-model="guessNum">
<button @click="checkGuess">猜一下</button>
<p v-show="!gameOver">{{hint}}</p>
<p v-show="gameOver">{{result}}</p>
</div>
```
Vue实例代码:
```javascript
var app = new Vue({
el: '#app',
data: {
answer: Math.floor(Math.random() * 100 + 1),
guessNum: '',
hint: '',
result: '',
count: 0,
gameOver: false
},
methods: {
checkGuess: function() {
// 检查是否猜中
if (this.guessNum == this.answer) {
this.gameOver = true;
this.result = `恭喜你,猜中了!你一共猜了${this.count}次。`;
} else {
// 猜错了,更新提示信息
this.count++;
if (this.guessNum > this.answer) {
this.hint = '你猜的数字太大了,请再猜一次。';
} else {
this.hint = '你猜的数字太小了,请再猜一次。';
}
}
}
}
});
```
该代码实现了一个简单的猜数字游戏,用户可以输入猜测的数字,程序会判断是否猜中并给出相应提示。游戏结束后会统计猜测次数并显示结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)