uniapp实现猜数字小游戏

一个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>

效果图:

猜数字

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

方哲Beans

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值