基于java刮刮乐,概率和后台均实现


package com.sunmo.buz.games.action;

import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;


public class ScratchAction extends DispatchAction
{

    public ActionForward loadaward(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
    {

        Object obj[] = lottery();
        // 这里自己连接数据
        request.setAttribute("award", obj[0]);
        return mapping.findForward("success");

        /*
         * 如果是JSON格式
*response.setCharacterEncoding("UTF-8");
         * response.getWriter().write(JsonUtils.object2json(obj));
         * response.getWriter().flush(); response.getWriter().close(); return
         * null
         */

    }

    // 抽奖并返回角度和奖项
    public Object[] lottery()
    {
        Object[][] lott = getLunckArray();
        // 概率数组
        Integer obj[] = new Integer[lott.length];
        for (int i = 0; i < lott.length; i++)
        {
            obj[i] = (Integer) lott[i][2];
        }
        Integer prizeId = getRand(obj); // 根据概率获取奖项id
        String msg = (String) lott[prizeId][1];// 提示信息
        return new Object[]
        { prizeId, msg };
    }

    protected static Object[][] getLunckArray()
    {

        Object luckArr[][] = new Object[][]
        {
        { 1, "一等奖", 1 },
        { 2, "二等奖", 2 },
        { 3, "三等奖", 5 },
        { 4, "四等奖", 7 },
        { 5, "五等奖", 10 },
        { 6, "六等奖", 25 },
        { 7, "谢谢惠顾", 50 } };

        return luckArr;
    }

    protected static Integer getRand(Integer obj[])
    {
        Integer result = null;
        int sum = 0;// 概率数组的总概率精度
        for (int i = 0; i < obj.length; i++)
        {
            sum += obj[i];
        }
        for (int i = 0; i < obj.length; i++)
        {
            int randomNum = new Random().nextInt(sum);// 随即生成1到sum的整数
            if (randomNum < obj[i])
            {// 中奖
                result = i;
                break;
            }
            else
            {
                sum -= obj[i];
            }
        }
        return result;
    }

}

你可能感兴趣的:(java)