基于vue2写一个简单网页游戏代码
时间: 2024-05-10 14:17:07 浏览: 14
好的,我可以为您提供一个猜数字游戏的代码示例。代码如下:
```html
<!DOCTYPE html>
<html>
<head>
<title>猜数字游戏</title>
<meta charset="UTF-8">
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<style>
body {
font-family: Arial, sans-serif;
}
.container {
width: 500px;
margin: 0 auto;
}
.form-group {
margin-bottom: 10px;
}
label {
display: inline-block;
width: 80px;
text-align: right;
margin-right: 10px;
}
input {
padding: 5px;
border-radius: 5px;
border: 1px solid #ccc;
}
button {
padding: 5px 10px;
font-size: 16px;
border-radius: 5px;
background-color: #4CAF50;
color: #fff;
border: none;
cursor: pointer;
}
button:hover {
background-color: #3E8E41;
}
</style>
</head>
<body>
<div id="app" class="container">
<h1>猜数字游戏</h1>
<form @submit.prevent="guessNumber">
<div class="form-group">
<label for="guess">请输入您猜测的数字:</label>
<input type="number" id="guess" v-model="guess" required>
</div>
<button type="submit">提交</button>
</form>
<div v-if="message" style="margin-top: 20px;">
<p v-html="message"></p>
<button @click="reset">再玩一次</button>
</div>
</div>
<script>
var app = new Vue({
el: '#app',
data: {
number: Math.floor(Math.random() * 100) + 1,
guess: null,
message: null
},
methods: {
guessNumber: function() {
if (this.guess === this.number) {
this.message = '<span style="color: green;">恭喜您猜对了!</span>';
} else if (this.guess > this.number) {
this.message = '<span style="color: red;">您猜的数字太大了。</span>';
} else {
this.message = '<span style="color: red;">您猜的数字太小了。</span>';
}
},
reset: function() {
this.number = Math.floor(Math.random() * 100) + 1;
this.guess = null;
this.message = null;
}
}
});
</script>
</body>
</html>
```
此代码实现了一个简单的猜数字游戏,用户输入一个数字,与生成的随机数字进行比较,如果猜对了则显示恭喜信息,否则提示用户数字大小。
注:此代码仅用于学习参考,实际项目中可能需要进行更多的优化和完善。