您还为写抽奖程序而发愁吗,还为写抽奖程序而困惑吗?你听说过用js也可以实现抽奖吗?赶快来关注一下吧,小涛在高手那里学到了:
<script type=”text/javascript”>
/*
* 抽奖箱
*/
function LotteryBox()
{
this.item_list = new Array(); //奖项列表(不包括空奖)
this.lottery_box = new Array(); //抽奖箱
this.lottery_all = 0; //全部抽奖卷数量
this.lottery_used = new Array(); //已作废的抽奖卷
/*
* 设置抽奖箱
*
* num : 抽奖箱的奖卷数量
*/
LotteryBox.prototype.start = function(num)
{
this.lottery_all = num; //设置抽奖卷总数
var lottery_total = 0;
//所有奖品放置到抽奖箱中
for(var i=0;i<this.item_list.length;i++)
{
for(var j=0;j<this.item_list[i].num;j++)
{
this.lottery_box.push(this.item_list[i]);
lottery_total++;
}
}
var noneItem = new Object();
noneItem.name = ‘<span style=”color:#fff”>空奖</span>’;
noneItem.num = this.lottery_all – lottery_total;
this.addItem(noneItem);
//所有空奖放置到抽奖箱中
for(var i=lottery_total;i<this.lottery_all;i++)
{
this.lottery_box.push(noneItem);
}
};
/**
* 抽取奖卷
* lottery_num : 要抽取的奖卷数量
*/
LotteryBox.prototype.getLottery = function(lottery_num)
{
if ( !lottery_num )
{
lottery_num = 1;
}
var ran_num;
document.writeln(‘<p>您共抽奖’+lottery_num+’次! 结果如下:</p>’);
document.writeln(‘<table border=”1″ bordercolor=”#000000″ bgcolor=”#555555″>’);
document.writeln(‘<tr><th>奖卷号码</th><th>对应奖品</th><th>中奖几率</th></tr>’);
for(var i=0;i<lottery_num;i++)
{
ran_num = this.getUniqueRanNum(this.lottery_used,this.lottery_all);
this.lottery_used.push(ran_num); //该号码作废
document.writeln(‘<tr><td>’+ran_num+'</td><td>’+this.lottery_box[ran_num].name+'</td><td>’+this.getProbability(this.lottery_box[ran_num].num)+'</td></tr>’);
}
document.writeln(‘</table>’);
};
//计算奖项中奖率
LotteryBox.prototype.getProbability = function(num)
{
return num + ‘/’ + this.lottery_all;
};
/*
* 添加奖品到抽奖箱
*/
LotteryBox.prototype.addItem = function(object)
{
this.item_list.push(object);
};
/**
* 检查数字是否在数组之中
*/
LotteryBox.prototype.checkNum = function(num,array)
{
var aLen = array.length;
for(var j=0;j<aLen;j++){
if(num == array[j]){
return true;
}
}
return false;
};
/**
* 返回一个随即数,这个数不能和指定数组中的任何一个相等
*/
LotteryBox.prototype.getUniqueRanNum = function(array,size)
{
var rNum = parseInt(Math.random()*size);
do{
rNum = parseInt(Math.random()*size);
}while(this.checkNum(rNum,array))
return rNum;
};
}
var lotteryBox = new LotteryBox();
var tongjiang = new Object();
tongjiang.name = ‘<span style=”color:goldenrod”>铜奖</span>’;
tongjiang.num = 70; //铜奖在所有奖品中占有的比例
var yinjiang = new Object();
yinjiang.name = ‘<span style=”color:steelblue”>银奖</span>’;
yinjiang.num = 10;
var jinjiang = new Object();
jinjiang.name = ‘<span style=”color:gold;font-weight:bold”>金奖</span>’;
jinjiang.num = 5;
var zuanjiang = new Object();
zuanjiang.name = ‘<span style=”color:orangered;font-weight:bold”>钻石奖</span>’;
zuanjiang.num = 1;
lotteryBox.addItem(tongjiang); //添加铜奖
lotteryBox.addItem(yinjiang); //添加银奖
lotteryBox.addItem(jinjiang); //添加金奖
lotteryBox.addItem(zuanjiang); //添加钻石奖
lotteryBox.start(100); //设置奖卷总数为100
lotteryBox.getLottery(10); //抽奖10次
</script>
这里是通过js 来模拟 抽奖箱抽奖,和现实中的抽奖极为相似,其中在奖卷抽出来后会作废很符合现实中的抽奖,另外各个奖项的中奖率自己可以控制,赶快来尝试一下吧。