一个uniapp的样例,超级简单~
效果图在最后~
外观:
- 首先定义文字区块,用来告诉玩家现在改干什么以及猜的数字是猜大了还是猜小了。
<view class="content">
{{text}}
</view>
.content{
width: 100%;
height: 100rpx;
background-color: aquamarine;
text-align: center;
}
这是初始文本:
text:"请点击随机数字开始游戏",
- 接下来是随机数字按钮,用来生成随机数字以开始游戏。
<button @click="getRandom()" type="primary">随机数字</button>
这里用getRandom方法获得随机数,方法如下:
getRandom() {
this.num=Math.random()*100
this.num=Math.round(this.num)
this.text="请输入数字来猜数字"
},
- 然后是输入框,用来获取玩家输入的数字,用input组件实现:
<input placeholder="请输入数字" class="cin" @input="onKeyInput(event)" type="number"/>
.cin{
width: 100%;
height: 100rpx;
background-color: antiquewhite;
text-align: center;
}
用onKeyInput方法来获得玩家输入的数字,具体如下:
onKeyInput() {
this.inputValue=event.target.value
},
<button type="default" @click="check">提交数字</button>
主要方法(判断玩家输入数字与随机数的关系)
其实就是一个简单的js条件判断语句:
check() {
if(this.inputValue==this.num){
this.text="恭喜你,猜对啦!点击随机数字重新开始游戏。"
}else if(this.inputValue>this.num){
this.text="猜大了"
}else{
this.text="猜小了"
}
}
完整代码:
<template>
<view>
<view class="content">
{{text}}
</view>
<button @click="getRandom()" type="primary">随机数字</button>
<input placeholder="请输入数字" class="cin" @input="onKeyInput(event)" type="number"/>
<button type="default" @click="check">提交数字</button>
</view>
</template>
<script>
export default {
data() {
return {
num:0,
text:"请点击随机数字开始游戏",
inputValue: ''
}
},
methods: {
getRandom() {
this.num=Math.random()*100
this.num=Math.round(this.num)
this.text="请输入数字来猜数字"
},
onKeyInput() {
this.inputValue=event.target.value
},
check() {
if(this.inputValue==this.num){
this.text="恭喜你,猜对啦!点击随机数字重新开始游戏。"
}else if(this.inputValue>this.num){
this.text="猜大了"
}else{
this.text="猜小了"
}
}
}
}
</script>
<style>
.content{
width: 100%;
height: 100rpx;
background-color: aquamarine;
text-align: center;
}
.cin{
width: 100%;
height: 100rpx;
background-color: antiquewhite;
text-align: center;
}
</style>
效果图: