以下是一个简单的Uniapp实现买定离手小游戏的代码示例:
- 在Vue组件中定义初始化数据:
data() {
return {
price: 5, // 商品价格
userScore: 100, // 用户初始积分
selectedNum: 0, // 用户选择的数量
totalCost: 0, // 用户总花费
isWin: false, // 是否中奖
isLose: false // 是否未中奖
}
}
- 编写方法,根据用户的选择计算总花费:
methods: {
// 选择数量
selectNum(num) {
this.selectedNum = num;
this.totalCost = this.price * num;
}
}
- 编写方法,模拟游戏中的抽奖过程:
// 开始游戏
startGame() {
if (this.selectedNum > 0 && this.totalCost <= this.userScore) {
// 模拟抽奖过程,50%的概率中奖
let randomNum = Math.random();
if (randomNum > 0.5) {
this.isWin = true;
this.userScore += this.totalCost * 2;
} else {
this.isLose = true;
this.userScore -= this.totalCost;
}
} else {
alert('请选择数量并确保积分足够');
}
}
- 在模板中渲染组件:
<template>
<div class="container">
<div class="game">
<div class="title">
<h2>买定离手小游戏</h2>
</div>
<div class="content">
<div class="price">商品价格:{{ price }}积分</div>
<div class="user-score">当前积分:{{ userScore }}</div>
<div class="num-select">
<div class="select-title">选择数量:</div>
<div class="select-btn" @click="selectNum(1)">1</div>
<div class="select-btn" @click="selectNum(2)">2</div>
<div class="select-btn" @click="selectNum(3)">3</div>
<div class="select-btn" @click="selectNum(4)">4</div>
<div class="select-btn" @click="selectNum(5)">5</div>
</div>
<div class="total-cost">总花费:{{ totalCost }}积分</div>
<div class="btn-start" @click="startGame()">开始游戏</div>
<div class="result" v-if="isWin">恭喜中奖!获得{{ totalCost * 2 }}积分</div>
<div class="result" v-if="isLose">真遗憾,未中奖~</div>
</div>
</div>
</div>
</template>
- 最后,为了增强游戏体验,可以为组件添加CSS样式:
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.game {
width: 400px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 10px;
}
.title {
text-align: center;
margin-bottom: 20px;
}
.content {
display: flex;
flex-direction: column;
align-items: center;
}
.num-select {
display: flex;
align-items: center;
}
.select-title {
margin-right: 10px;
}
.select-btn {
width: 30px;
height: 30px;
border: 1px solid #ccc;
border-radius: 50%;
margin-right: 10px;
display: flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.select-btn:hover {
background-color: #eee;
}
.btn-start {
width: 100px;
height: 40px;
background-color: #007bff;
color: #fff;
text-align: center;
line-height: 40px;
border-radius: 20px;
margin-top: 20px;
cursor: pointer;
}
.btn-start:hover {
background-color: #0069d9;
}
.result {
margin-top: 20px;
font-size: 16px;
text-align: center;
font-weight: bold;
}