游戏转盘PHP后台实现奖品发放

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php

header("Content-type:text/html;charset=GB2312"); //设置编码

//中奖奖品
$prizeArr = array(
0 => array('id' => 1, 'prize' => '现金500W', 'v' => 1), //概率为1/200
1 => array('id' => 2, 'prize' => 'iphone7', 'v' => 5),
2 => array('id' => 3, 'prize' => '耐克跑鞋', 'v' => 10),
3 => array('id' => 4, 'prize' => '魔声耳机', 'v' => 24),
4 => array('id' => 5, 'prize' => '蓝牙音响', 'v' => 60),
5 => array('id' => 6, 'prize' => '现金1元', 'v' => 100)
);

/*
* 对数组进行处理
*/
$item = [];
foreach ($prizeArr as $k => $v) {
//使用新数组item
$item[$v['id']] = $v['v'];
}
/*
array(
1 => 1,
2 => 5,
3 => 10,
4 => 24,
5 => 60,
6 => 100
);
*/

function getRand($item)
{
$num = array_sum($item);//计算出分母200
$result = 0;
foreach ($item as $k => $v) {
// var_dump('k = ' . $k . ', v=' . $v);
// var_dump('<br><br>');
$rand = mt_rand(1, $num);//概率区间(整数) 包括1和200
// var_dump('随机数=' . json_encode($rand));
// var_dump('<br><br>');
/*
*这个算法很666
*/
if ($rand <= $v) {
//循环遍历,当下标$k = 1的时候,只有$rand = 1 才能中奖
$result = $k;
// echo '$rand <= $v ,' . $rand . '--' . $v;
// var_dump('<br><br>');
break;
} else {
//当下标$k=6的时候,如果$rand>100 必须$rand < = 100 才能中奖 ,那么前面5次循环之后$rand的概率区间= 200-1-5-10-24-60 (1,100) 必中1块钱
$num -= $v;
// echo ' *' . $rand . '* num=' . $num;
// var_dump('<br><br>');
}
}

// var_dump('$result=' . json_encode($result));
// var_dump('<br><br>');
return $result;
}


$times = 5000000;
$prizes = [];
for ($i = 0; $i < $times; $i++) {
$r = getRand($item);
$p = $prizeArr[$r - 1]['prize'];
if (isset($prizes[$p])) {
$num = $prizes[$p];
$num++;
$prizes[$p] = $num;
} else {
$prizes[$p] = 1;
}
// var_dump(gettype($prizes));
// break;
}

var_dump('概率:');
var_dump($prizes);
var_dump('<br><br>');
foreach ($prizes as $p => $nums) {
var_dump($p . '------>' . $nums / $times);
var_dump('<br><br>');
}
var_dump('<br><br>');
var_dump('<br><br>');
foreach ($item as $p => $nums) {
var_dump($prizeArr[$p - 1]['prize'] . '------>' . $nums / 200);
var_dump('<br><br>');
}

Reference

写在最后

欢迎大家关注鄙人的公众号【麦田里的守望者zhg】,让我们一起成长,谢谢。
微信公众号