php抽奖实现

抽奖地址:https://www.huijindaicn.com/i…
主要代码:(其他引用可以在上面地址页面根据引用地址下载)
1、html页面

<body>
<img class="head" src="/public/images/lottery/bg/head.gif" width="100%" />

<div class="content">
    <div class="cj1">
        <img src="/public/images/lottery/bg/bg.png" width="100%" />
        
        <!-- 点我注册 -->
        <a href="{url x="index" r="user#register"}" target="_blank" class="to_reg"></a>
        <!-- 立即签到 -->
        <a href="{url x="index" r="uc_center"}" target="_blank" class="to_log"></a>
        
        <div class="u_count">
            <label>抽奖次数前5名:</label>
            <div class="c_count"></div>
        </div>

        <!-- 九宫格抽奖 -->
        <div id="lottery">
            <table border="0" cellpadding="0" cellspacing="0">
                <tr>
                    <td class="lottery-unit lottery-unit-0"><img src="/public/attachment/1_images/lottery/jf-10.png"><div class="mask"></div></td>
                    <td class="lottery-unit lottery-unit-1">
                        <img src="/public/attachment/1_images/lottery/zdc.png">
                        <!-- <img src="/public/attachment/1_images/lottery/bbg.png"> -->
                        <img src="/public/images/lottery/pc-4.png" class="wz">
                        <div class="mask"></div>
                    </td>
                    <td class="lottery-unit lottery-unit-2"><img src="/public/attachment/1_images/lottery/hb-5.png"><div class="mask"></div></td>
                    <td class="lottery-unit lottery-unit-3">
                        <img src="/public/attachment/1_images/lottery/ej.png">
                        <!-- <img src="/public/attachment/1_images/lottery/zyp.png"> -->
                        <img src="/public/images/lottery/pc-1.png" class="wz">
                        <div class="mask"></div>
                    </td>
                    <td class="lottery-unit lottery-unit-4"><img src="/public/attachment/1_images/lottery/jf-50.png"><div class="mask"></div></td>
                    <td class="lottery-unit lottery-unit-5">
                        <img src="/public/attachment/1_images/lottery/fxq.png">
                        <!-- <img src="/public/attachment/1_images/lottery/jhq.png"> -->
                        <img src="/public/images/lottery/pc-3.png" class="wz">
                        <div class="mask"></div>
                    </td>
                </tr>
                <tr>
                    <td class="lottery-unit lottery-unit-15">
                        <!-- <img src="/public/attachment/1_images/lottery/px.png"> -->
                        <img src="/public/attachment/1_images/lottery/sh.png">
                        <img src="/public/images/lottery/pc-2.png" class="wz">
                        <div class="mask"></div>
                    </td>
                    <td colspan="4" rowspan="2"><a href="javascript:;"></a></td>
                    <td class="lottery-unit lottery-unit-6"><img src="/public/attachment/1_images/lottery/hb-18.png"><div class="mask"></div></td>
                </tr>
                <tr>
                    <td class="lottery-unit lottery-unit-14"><img src="/public/attachment/1_images/lottery/hb-88.png"><div class="mask"></div></td>
                    <td class="lottery-unit lottery-unit-7">
                        <img src="/public/attachment/1_images/lottery/led.png">
                        <img src="/public/images/lottery/pc-6.png" class="wz">
                        <div class="mask"></div>
                    </td>
                </tr>
                <tr>
                    <td class="lottery-unit lottery-unit-13">
                        <img src="/public/attachment/1_images/lottery/bwb.png">
                        <img src="/public/images/lottery/pc-5.png" class="wz">
                        <div class="mask"></div>
                    </td>
                    <td class="lottery-unit lottery-unit-12"><img src="/public/attachment/1_images/lottery/hb-58.png"><div class="mask"></div></td>
                    <td class="lottery-unit lottery-unit-11"><img src="/public/attachment/1_images/lottery/hf-10.png"><div class="mask"></div></td>
                    <td class="lottery-unit lottery-unit-10">
                        <img src="/public/attachment/1_images/lottery/cdq.png">
                        <!-- <img src="/public/attachment/1_images/lottery/hb-38.png"> -->
                        <img src="/public/images/lottery/pc-7.png" class="wz">
                        <div class="mask"></div>
                    </td>
                    <td class="lottery-unit lottery-unit-9"><img src="/public/attachment/1_images/lottery/hf-20.png"><div class="mask"></div></td>
                    <td class="lottery-unit lottery-unit-8"><img src="/public/attachment/1_images/lottery/jf-300.png"><div class="mask"></div></td>
                </tr>
            </table>
        </div>

        <!-- 九宫格中奖列表 -->
        <div class="list lottery-list"></div>

        <!-- 用户抽奖次数 -->
        <div class="l_count">
            <p>剩余积分:<span class="score"></span></p>
            <p>可抽奖次数:<span class="num"></span></p>
            <p>已抽奖次数:<span class="count"></span></p>
        </div>
    </div>
</div>
<!-- 中奖列表滚动插件 -->
<script type="text/javascript" src="/public/script/jquery.totemticker.js"></script>
<script type="text/javascript" src="/public/images/lottery/lottery.js"></script>
</body>

2、js 主要代码

lottery.js:

var lottery = {
    index: 0, //当前转动到哪个位置,起点位置
    count: 16, //总共有多少个位置
    timer: 0, //setTimeout的ID,用clearTimeout清除
    speed: 20, //初始转动速度
    times: 0, //转动次数
    cycle: 50, //转动基本次数:即至少需要转动多少次再进入抽奖环节
    prize: -1, //中奖位置
    init: function(id) {
        if ($("#" + id).find(".lottery-unit").length > 0) {
            $lottery = $("#" + id);
            $units = $lottery.find(".lottery-unit");
            this.obj = $lottery;
            this.count = $units.length;
            $lottery.find(".lottery-unit-" + this.index).addClass("active");
        }
    },
    roll: function() {
        var index = this.index;
        var count = this.count;
        var lottery = this.obj;
        $(lottery).find(".lottery-unit-" + index).removeClass("active");
        index += 1;
        if (index > count - 1) {
            index = 0;
        }
        $(lottery).find(".lottery-unit-" + index).addClass("active");
        this.index = index;
        return false;
    },
    stop: function(index) {
        this.prize = index;
        return false;
    }
};

function roll() {
    lottery.times += 1;
    lottery.roll();
    var prize_site = $("#lottery").attr("prize_site");
    if (lottery.times > lottery.cycle + 10 && lottery.index == prize_site) {
        // var prize_id = $("#lottery").attr("prize_id");
        var prize_name = $("#lottery").attr("prize_name");
        // alert("中奖名称:"+prize_name+"\n中奖id:"+prize_id);
        $.showSuccess('恭喜你中得 '+ prize_name,function(){
            get_win_num();
            get_win_list();
            get_tot_num();
        }); 
        clearTimeout(lottery.timer);
        lottery.prize = -1;
        lottery.times = 0;
        click = false;
    } else {
        if (lottery.times < lottery.cycle) {
            lottery.speed -= 10;
        } else if (lottery.times == lottery.cycle) {
            var index = Math.random() * (lottery.count) | 0;
            lottery.prize = index;
        } else {
            if (lottery.times > lottery.cycle + 10 && ((lottery.prize == 0 && lottery.index == 7) || lottery.prize == lottery.index + 1)) {
                lottery.speed += 110;
            } else {
                lottery.speed += 20;
            }
        }
        if (lottery.speed < 40) {
            lottery.speed = 40;
        }
        lottery.timer = setTimeout(roll, lottery.speed);
    }
    return false;
}

/* 获取中奖列表 */
function get_win_list(){
    $.get('/index.php?ctl=lottery&pc_ct=get_new_win&num=100', function(a){
        // console.log(a);
        if(typeof a != 'object'){
            return;
        }
        for(k in a){
            html = '<ul>';
            for(i = 0, l = a[k].length; i < l; i++){
                html += '<li><span>'+ a[k][i].user_name +'</span><span>'+ a[k][i].goods_name +'</span></li>';
            }
            html += '</ul>';
            $('.lottery-list').html(html);
        }
        /* 中奖列表滚动插件 */
        $('.lottery-list ul').totemticker({
            row_height: '21px',
            next: '#ticker-next',
            previous: '#ticker-previous',
            stop: '#stop',
            start: '#start',
            mousestop: true
        });
    }, 'json');
}

/* 获取剩余抽奖次数 */
function get_win_num(){
     $.get('/index.php?ctl=lottery&pc_ct=get_win_num&type=t_box', function(a){
        if(typeof a != 'object'){
            return;
        }
        $('.score').html(a.score);
        $('.num').html(a.num);
        $('.count').html(a.count);
    }, 'json');
}

/* 获取抽奖排行 */
function get_tot_num(){
     $.get('/index.php?ctl=lottery&pc_ct=get_tot_num', function(a){
        if(typeof a != 'object'){
            return;
        }
        var html = '';
        $.each(a, function(i, n){
            html = html+'<span>'+(i+1)+':'+n.user_name+'('+n.num+'次)</span>';
        });
        $('.c_count').html(html);
    }, 'json');
}

var click = false;

$(function() {
    
    var ajax_url = "/index.php?ctl=lottery&pc_ct=get_win";
    lottery.init('lottery');

    /* 开始抽奖 */
    $("#lottery a").click(function() {
        console.log(click);
        if (click) {
            return false;
        } else {
            $.post(ajax_url, {uid: 1}, function(a) { // 获取奖品,也可以在这里判断是否登陆状态
                if(!a.code){
                    var _url = a.status == 2 ? '/index.php?ctl=user&act=login' : '/index.php?ctl=deals';
                    return $.showErr(a.msg, function(){window.location = _url;});
                }else if(a.win){
                    $("#lottery").attr("prize_site", a.win.id);
                    $("#lottery").attr("prize_name", a.win.name);
                    lottery.speed = 100;
                    roll();
                    click = true;
                    return false;
                }else{
                    $.showSuccess('通讯错误 稍后再试');
                }
            }, "json")
        }
    });

    /*获取积分和用户抽奖次数*/
    get_win_num();

    /*获取中奖信息*/
    get_win_list();

    /* 获取抽奖前十名 */
    get_tot_num();
})

3、php代码(奖品获取代码)


   // 摇奖操作 获取中奖结果 并返回 信息
private function get_win() 
{
    $user_id = intval($GLOBALS['user_info']['id']);
    $type = isset($_REQUEST['type']) && preg_match('/^\w+$/', $_REQUEST['type']) ? $_REQUEST['type'] : 't_box';

    $json = array('code' => 0, 'msg' => '', 'uid' => $user_id);

    if(!$user_id){
        $json['msg'] = '请登录后再试!';
        $json['status'] = 2;
        es_session::set("gopreview", "/index.php?ctl=user&act=login");
        return $json;
    }

    $base_score = 300;
    $user_num = $GLOBALS['db']->getOne("SELECT num from ".DB_PREFIX."turntable_user_num where user_id = {$user_id} AND type = 't_box'");
    $user_num = $user_num ? $user_num : 0;
    $user_score = $GLOBALS['db']->getOne("SELECT score from ".DB_PREFIX."user where id = {$user_id}");
    $tot_num = intval($user_score/$base_score) + intval($user_num);
    // return $user_num;
    if(!$tot_num){     // 积分不足且没有赠送的抽奖次数
        $json['msg'] = '您的积分不足,通过投资或签到可获取相应积分!';
        $json['status'] = 3;
        $json['data'] = $_data;
        return $json;
    }

    // 可抽中奖品列表
    $arr = array(   
        '0' => array('id'=>0,'good_id'=>50,'name'=>'平台10积分','v'=>15),
        '1' => array('id'=>1,'good_id'=>70,'name'=>'智能折叠代步车','v'=>1),
        '2' => array('id'=>2,'good_id'=>54,'name'=>'理财红包5元','v'=>30),
        '3' => array('id'=>3,'good_id'=>66,'name'=>'蓝牙运动耳机','v'=>0),
        '4' => array('id'=>4,'good_id'=>51,'name'=>'平台50积分','v'=>15),
        '5' => array('id'=>5,'good_id'=>68,'name'=>'遥控四轴飞行器','v'=>1),
        '6' => array('id'=>6,'good_id'=>53,'name'=>'理财红包18元','v'=>20),
        '7' => array('id'=>7,'good_id'=>60,'name'=>'LED充电台灯','v'=>5),
        '8' => array('id'=>8,'good_id'=>52,'name'=>'平台300积分','v'=>10),
        '9' => array('id'=>9,'good_id'=>59,'name'=>'20元话费','v'=>5),
        '10' => array('id'=>10,'good_id'=>67,'name'=>'太阳能充电器','v'=>3),
        '11' => array('id'=>11,'good_id'=>58,'name'=>'10元话费','v'=>10),
        '12' => array('id'=>12,'good_id'=>56,'name'=>'理财红包58元','v'=>10),
        '13' => array('id'=>13,'good_id'=>61,'name'=>'24小时保温杯','v'=>10),
        '14' => array('id'=>14,'good_id'=>57,'name'=>'理财红包88元','v'=>1),
        '15' => array('id'=>15,'good_id'=>69,'name'=>'智能运动手环','v'=>5),
    );

    $user_ids = array(
        '13' => array(20861,3661,20631,7433,2447,7239,12471,3338,13031,12070), // 24小时保温杯
        '15' => array(2086,8824,6699,747,2291,1127,2955,2408,5127,12070), // 智能运动手环
    );

    /*  正常抽奖  */
    $key = $this->get_rand($arr);
    $win = $arr[$key];

    /*  特殊客户 抽实物  */
    $g_count = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."turntable_user_goods WHERE user_id = ".$GLOBALS['user_info']['id']." AND type='t_box' AND goods_id IN(61,66,67,68,69,70)");
    foreach ($user_ids as $k => $v) {
        if(in_array($user_id, $v) && !$g_count)
        {
            $win = $arr[$k];
            break;
        }
    }
    
    $good = $GLOBALS['db']->getRow("SELECT * FROM ".DB_PREFIX."turntable_goods WHERE id = ".$win['good_id']);

    // 抽奖成功
    if(!empty($good))
    {
        // 扣除抽奖积分,或赠送机会
        $this->upadte_user_num_score($user_num,$user_score);
        // 添加奖品给用户
        $this->update_user_goods($good);
        return array(
                'code' => 1, 
                'status' => 1, 
                'win' => array(
                        'id' => $win['id'],
                        'name' => $good['name'],
                    ),
                );
    }else{
        return array('code' => 0, 'status' => 4, 'msg' => '该活动 处于关闭状态,详情咨询客服!');
    }
}

// 抽奖概率算法
private function get_rand($proArr) 
{   
    $result = '';
    foreach ($proArr as $key => $val) { 
        $arr[$key] = $val['v']; 
    } 
    // 概率数组的总概率  
    $proSum = array_sum($arr);
    // 概率数组循环   
    foreach ($arr as $k => $v) {   
        $randNum = mt_rand(1, $proSum);  
        if ($randNum <= $v) {   
            $result = $k;   
            break;   
        } else {   
            $proSum -= $v;  
        }         
    }     
    return $result;  
}

// 获取最新中奖列表
private function get_new_win()
{
    $num = isset($_REQUEST['num']) ? intval($_REQUEST['num']) : 10;
    $type = isset($_REQUEST['type']) ? $_REQUEST['type'] : 't_box';
    $list = array();
    $sql = "SELECT g.id, g.user_id, u.user_name, g.goods_id, g.goods_name, g.time
            FROM ".DB_PREFIX."turntable_user_goods g
            LEFT JOIN ".DB_PREFIX."user u ON u.id = g.user_id
            WHERE g.is_effect = 1 AND g.type = '{$type}'
            ORDER BY g.id DESC limit {$num}";

    $list = $GLOBALS['db']->getAll($sql);
    if(is_array($list)){
        foreach ($list as $key => $v) {
            $list[$key]['user_name'] = utf_substr($v['user_name']);
        }
    }        
    return array('list' => $list);
}

/* 获取中奖前五名 */
private function get_tot_num()
{
    $sql = "SELECT count(*) as num,u.user_name FROM fanwe_turntable_user_goods t 
            LEFT JOIN fanwe_user u ON t.user_id = u.id
            WHERE t.type = 't_box' GROUP BY t.user_id ORDER BY num desc LIMIT 5";
    $list = $GLOBALS['db']->getAll($sql);
    if(is_array($list)){
        foreach ($list as $key => $v) {
            $list[$key]['user_name'] = utf_substr($v['user_name']);
        }
    }
    return $list;
}

// 获取自己所剩抽奖次数 和 积分 
private function get_win_num()
{
    $types = isset($_REQUEST['types']) ? $_REQUEST['types'] : 't_box';
    $arr = array();

    $user_num = $GLOBALS['db']->getOne("SELECT num from ".DB_PREFIX."turntable_user_num where user_id = {$GLOBALS['user_info']['id']} AND type = 't_box'");
    $user_score = $GLOBALS['db']->getOne("SELECT score from ".DB_PREFIX."user where id = {$GLOBALS['user_info']['id']}");
    $user_num = $user_num ? $user_num : 0;
    $arr['num'] = intval($user_score/300) + intval($user_num);
    $arr['score'] = $user_score;
    $arr['count'] = $GLOBALS['db']->getOne("SELECT count(*) FROM ".DB_PREFIX."turntable_user_goods WHERE user_id = ".$GLOBALS['user_info']['id']." AND type='t_box'");
    return $arr;
}
    原文作者:人偶_阿诺
    原文地址: https://segmentfault.com/a/1190000007637956
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞