vue3按照概率实现九宫格抽奖

在Vue3中,可以使用以下基本的思路来实现九宫格抽奖游戏。

  1. 定义3 X 3 的二维数组并随机从中选择一个元素作为中奖项。
  2. 根据概率计算出每个奖项对应的中奖概率。
  3. 将每个奖项用对应的概率作为权重传入一个概率函数中,按照概率随机生成一个数字并确定中奖项。

下面是代码实例:

<template>
  <div>
    <div class="grid">
      <div class="cell" :class="{'active': selectedIndex === index}" v-for="(item, index) in lotteryList" :key="index">{
   
   { item.title }}</div>
    </div>
    <button @click="startLottery" :disabled="isRunning">开始抽奖</button>
  </div>
</template>

<script>
import { reactive } from 'vue'

interface Lottery {
  title: string;
  probability: number;
}

export default {
  setup() {
    const data = reactive({
      lotteryList: [
        { title: '奖品A', probability: 0.2 },
        { title: '奖品B', probability: 0.1 },
        { title: '奖品C', probability: 0.3 },
        { title: '奖品D', probability: 0.1 },
        { title: '奖品E', probability: 0.2 },
        { title: '奖品F', probability: 0.1 }
      ] as Lottery[],
      selectedIndex: -1,
      isRunning: false
    })

    function startLottery() {
      if (data.isRunning) return

      data.isRunning = true
      const resultIndex = getLotteryResultIndex()
      runLottery(resultIndex)
    }

    function getLotteryResultIndex() {
      const randomNum = Math.random()
      let sum = 0
      for (let i = 0; i < data.lotteryList.length; i++) {
        sum += data.lotteryList[i].probability
        if (randomNum <= sum) {
          return i
        }
      }
    }

    function runLottery(resultIndex: number) {
      data.selectedIndex = -1
      let count = 0
      const animate = () => {
        count++
        data.selectedIndex = count % 9
        if (count < 30) {
          setTimeout(animate, 100)
        } else if (count < 40) {
          setTimeout(animate, 200)
        } else if (count < 48) {
          setTimeout(animate, 300)
        } else if (count < 56) {
          setTimeout(animate, 500)
        } else {
          data.selectedIndex = resultIndex
          data.isRunning = false
        }
      }
      setTimeout(animate, 100)
    }

    return {
      ...data,
      startLottery
    }
  }
}
</script>

<style>
.grid {
  display: flex;
  flex-wrap: wrap;
  width: 300px;
  height: 300px;
  border: 1px solid black;
}

.cell {
  display: flex;
  justify-content: center;
  align-items: center;
  width: calc(33.333% - 2px);
  height: calc(33.333% - 2px);
  border: 1px solid black;
}

.cell.active {
  background-color: tomato;
}
</style>

在上述代码中,我们使用 Vue 3 的reactive函数创建了一个响应式对象,包含奖项列表lotteryList、选中的索引selectedIndex和是否正在抽奖isRunning。在startLottery方法中,我们判断当前是否正在抽奖,然后设置isRunningtrue,并计算出中奖的索引,然后调用runLottery方法。getLotteryResultIndex方法和runLottery方法的实现和之前的示例代码相同。在setup函数中返回需要暴露给模板使用的响应式数据和方法。

猜你喜欢

转载自blog.csdn.net/zzx262625/article/details/130152475