php 抽奖实例
php code
<?php
/**
抽奖
min 数组表示每个个奖项对应的最小角度 max 表示最大角度
prize 表示奖项内容, v 表示中奖几率(若数组中七个奖项的v的总和为100,如果v的值为1,则代表中奖几率为1%,依此类推)
*/
$prize_arr = array(
'0' => array('id' => 1, 'min' => 1, 'max' => 29, 'prize' => '一等奖', 'v' => 1),
'1' => array('id' => 2, 'min' => 302, 'max' => 328, 'prize' => '二等奖', 'v' => 2),
'2' => array('id' => 3, 'min' => 242, 'max' => 268, 'prize' => '三等奖', 'v' => 5),
'3' => array('id' => 4, 'min' => 182, 'max' => 208, 'prize' => '四等奖', 'v' => 7),
'4' => array('id' => 5, 'min' => 122, 'max' => 148, 'prize' => '五等奖', 'v' => 10),
'5' => array('id' => 6, 'min' => 62, 'max' => 88, 'prize' => '六等奖', 'v' => 25),
'6' => array('id' => 7, 'min' => array(32, 92, 152, 212, 272, 332),
'max' => array(58, 118, 178, 238, 298, 358), 'prize' => '七等奖', 'v' => 50)
);
function getRand($proArr){
$data = '';
$proSum = array_sum($proArr); //概率数组的总概率精度
foreach ($proArr as $k => $v){ //概率数组循环
$randNum = mt_rand(1, $proSum);
if ($randNum <= $v) {
$data = $k;
break;
} else {
$proSum -= $v;
}
}
unset($proArr);
return $data;
}
foreach ($prize_arr as $v) {
$arr[$v['id']] = $v['v'];
}
$prize_id = getRand($arr); //根据概率获取奖项id
$res = $prize_arr[$prize_id - 1]; //中奖项
$min = $res['min'];
$max = $res['max'];
if ($res['id'] == 7) { //七等奖
$i = mt_rand(0, 5);
$data['angle'] = mt_rand($min[$i], $max[$i]);
} else {
$data['angle'] = mt_rand($min, $max); //随机生成一个角度
}
$data['prize'] = $res['prize'];
echo json_encode($data);
Html Code
<div id="disk"></div>
<div id="start"><img src="images/start.png" id="startbtn" alt="转盘开启"/></div>
<!--CSS指针和圆盘样式如下:-->
<style type="text/css">
#disk{width:417px; height:417px; background:url(images/disk.jpg) no-repeat}
#start{width:163px; height:320px; position:absolute; top:46px; left:130px;}
#start img{cursor:pointer}
</style>
<!--接着我们引入jquery.js、旋转插件jQueryRotate.2.2.js及动画easing插件jquery.easing.min.js。easing 教程我们已经讲过了,jQuery Easing动画插件。-->
<script type = "text/javascript" src = "http://www.sucaihuo.com/Public/js/other/jquery.js" > </script>
<script type = "text/javascript" src = "http://demo.sucaihuo.com/19/jQueryRotate.2.2.js"></script>
<script type = "text/javascript" src = "http://demo.sucaihuo.com/19/jquery.easing.min.js"></script>
<!--最后通过jQueryRotate.js旋转插件,我们让指针转起来。-->
<script>
$(function() {
$(function() {
$("#startbtn").click(function(){
lottery();
});
});
function lottery() {
$.ajax({
type: 'POST',
url: 'ajax.php',
dataType: 'json',
cache: false,
error: function() {
alert('Sorry,出错了!');
return false;
},
success: function(json) {
$("#startbtn").unbind('click').css("cursor", "default");
var angle = json.angle; //指针角度
var prize = json.prize; //中奖奖项标题
$("#startbtn").rotate({
duration: 3000,//转动时间 ms
angle: 0, //从0度开始
animateTo: 3600 + angle,//转动角度
easing: $.easing.easeOutSine, //easing扩展动画效果
callback: function() {
var resulte = confirm('恭喜您中得' + prize + '\n想要继续吗?');
if (resulte) { //若是点击确定,继续抽奖
lottery();
}
}
});
}
});
}
});
</script>
抽奖素材
发表评论