抽奖程序代码

合集下载

用vb编一个抽奖软件的源代码

用vb编一个抽奖软件的源代码

求用v b编一个抽奖软件的源代码悬赏分:20 - 解决时间:2008-4-15 22:47要求:1.点击‘开始’从tex t或ex cel文件中依次调用每一行的电话号码,滚动显示在界面上,点击‘停止‘ 则停在某一个电话上即可2.请带一些语句说明最好问题补充:这位前辈是不是将input 写成了inpue ,while not(eof(#1))总是提示错误我是个v b小白,能不能说明白点,需要几个控键分别叫啥名字,语句能不能更完整些,谢谢开始和停止为同一个键也可以提问者:qv x i aogang - 试用期一级最佳答案dim i窗口启动:i=0Open App.Path & "\电话号码.tx t" F or Input As #1while eof(1)=falseLine Input #1,aList1.AddItem awendclose #1按开始:timer1.Interval=50按结束:timer1.Interval=0timer的事件:i=i+1if i=List1.ListCount then i=0Label1.Caption = List1.List(i)不好意思啊,由于没有注意,所以先前的答案有两个小错误,现在已修正了所需控件:两个按钮,一个开始,一个结束;一个时钟控件一个列表框;一个标签控件用VB 6.0编写电脑抽奖程序近年来在娱乐节目之中常常见到利用电脑来抽奖,笔者对其发生了兴趣遂自己动手用VB编了一个小程序来实现电脑抽奖的小功能,其原理如下:主要利用VB中的Rnd函数,来实现随机查找和打乱排序的功能,从而实现随机抽奖的目的。

Rnd函数的语法结构是Rnd[(number)],可选的nu mber参数是single或任何有效的数值表达式。

Rnd函数返回小于1但大于或等于0的值。

nu mber 的值决定了Rnd 生成随机数的方式。

为了生成某个范围内的随机整数,可使用以下公式:Int((upperbound -lowerbound +1) × Rnd +lowerbound)这里,upperbound 是随机数范围的上限,而lowerbound 则是随机数范围的下限。

幸运抽奖java代码-个人编程

幸运抽奖java代码-个人编程

幸运抽奖java代码-个人编程import java.util.*;public class 实现登录功能{public static void main(String[] args) {//注册成功后,用户选择"登录"菜单,进入登录功能,输入注册时用的用户名和密码,登录成功。

//系统提示欢迎信息,如果用户名和密码输入错误,提示用户继续输入,最多有3次输入机会Scanner input =new Scanner(System.in);String jixu;String user=""; //登录用户名String password=""; //登录密码String user1=""; //登录用户名String mima=""; //登录密码boolean isLogin = false;boolean isRegister=false;do{System.out.println("*****欢迎进入奖客富翁系统*****");System.out.println("\t1.注册");System.out.println("\t2.登陆");System.out.println("\t3.抽奖");System.out.println("*************************");System.out.println("请输入菜单:");int menu =input.nextInt();for (int i = 0; i <menu; i++){System.out.print("");}switch(menu){case 1:System.out.println("[奖客富翁系统>注册]");System.out.println("请填写个人注册信息:");System.out.println("用户名:");user =input.next();System.out.println("密码:");password =input.next();System.out.println("注册成功,请记好您的会员卡号。

C语言实现随机抽奖程序

C语言实现随机抽奖程序

C语⾔实现随机抽奖程序本⽂实例为⼤家分享了C语⾔实现抽奖⼩程序的具体代码,供⼤家参考,具体内容如下#include<stdio.h>#include<stdlib.h>#include <time.h> // 使⽤当前时钟做种⼦#include <windows.h>/*做⼀个抽奖程序,⼀等奖1%⼆等奖5%三等奖10%要求1:基本功能实现,按下任意字母按键打印⼀次抽奖结果。

要求2:程序开始的时候可以选择模式,键盘A键按下,代表⾃动模式;M代表⼿动模式,⾃动模式抽奖可以⼀直抽,直到抽到1等奖为⽌。

要求3:在要求2的前提下,(⾃动模式)先打印第⼀次抽到三等奖所需要的次数,然后打印第⼀次抽到⼆等奖所需要的次数,最后打印第⼀次获得⼀等奖所需要的次数,程序结束*///随机数取段落,保证抽到的误差较⼩#define CJ_game(a) if(a>=0&&a<=327) printf("恭喜你!获得⼀等奖!!\n");\else if(a>=4000&&a<=5638) printf("恭喜你!获得⼆等奖!!\n");\else if(a>=400&&a<=3676) printf("恭喜你!获得三等奖!!\n");\else printf("再接再厉\n")void CJ_mode_auto() //⾃动模式{int First_f = 0,Second_f = 0,Third_f = 0; //定义第⼀次抽取到奖品的标志位int Sjs = 0,Game_state = 1;int F_count = 0,S_count = 0,T_count = 0,count = 0;//定义抽到奖品的计数位printf("\n");printf("\n");printf("==========模式A:⾃动抽奖游戏开始==========\n");while(Game_state){Sleep(200);Sjs=rand();CJ_game(Sjs);count++;// printf("%d\n",count); //测试位if(Sjs >= 400 && Sjs <= 3676){T_count++;if(T_count == 1){Third_f = count;}}if(Sjs >= 4000 && Sjs <= 5638){S_count++;if(S_count == 1){Second_f = count;}}if(Sjs >= 0 && Sjs <= 327){F_count++;if(F_count == 1){First_f = count;}}if(First_f && Second_f && Third_f){Game_state = 0;}}printf("第⼀次抽到⼀等奖所需要的次数为:%d\n",First_f);printf("第⼀次抽到⼆等奖所需要的次数为:%d\n",Second_f);printf("第⼀次抽到三等奖所需要的次数为:%d\n",Third_f);printf("抽到⼀等奖的总次数为:%d\n",F_count);printf("抽到⼆等奖的总次数为:%d\n",S_count);printf("抽到三等奖的总次数为:%d\n",T_count);printf("=====请选择新的游戏模式:M:⼿动,A:⾃动=====\n");}void CJ_mode_handch(void) //⼿动抽奖{char ch;int Sjs;printf("\n");printf("\n");printf("==========模式M:⼿动抽奖游戏开始==========\n");printf("==========按0退出⾃动模式==========\n");while(1){printf("=====请输⼊⼀个字母:");//scanf(" %c",&ch); //如果需要输⼊字符然后回车的,需要在%c前⾯加空格或者\n,来过滤缓冲区的“回车” ch = getch(); //从键盘获取字符if( (ch>='a'&&ch<='z') || (ch>='A'&&ch<='Z') ){Sjs = rand();// printf("%d\n",Sjs);CJ_game(Sjs);}else if(ch == '0'){printf("=====退出⼿动抽奖模式=====\n");printf("=====请输⼊新的游戏模式:M:⼿动,A:⾃动\n");break;}else{printf("=====请输⼊字母=====\n");}}}int main(){srand((unsigned)time( NULL ) ); // 初始化随机数char mode;printf("=======游戏开始==========\n");printf("=====请选择抽奖模式======\n");printf("=====按M进⼊模式M:⼿动抽奖=====\n");printf("=====按A进⼊模式A:⾃动抽奖=====\n");printf("=====按0结束游戏!!=====\n");while(1){mode = getch();if(mode =='A'){CJ_mode_auto();}else if(mode =='M'){CJ_mode_handch();}else if(mode == '0'){printf("游戏结束!");break;}else{printf("请输⼊正确的模式\n");}}return 0;}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

C#模拟实现抽奖小程序的示例代码

C#模拟实现抽奖小程序的示例代码

C#模拟实现抽奖⼩程序的⽰例代码⽬录1.抽奖主界⾯2.操作步骤2.1 抽奖界⾯2.2 抽奖结果导出3.源码3.1 数据库连接3.2 抽奖程序1.抽奖主界⾯2.操作步骤S键开始;0、1、2、3、4、5键分别对应6次奖项;分别是特等奖、⼀等奖、⼆等奖、三等奖、四等奖、五等奖9键是加抽奖;空格退出抽奖结果界⾯;P键关闭⽓泡效果。

2.1 抽奖界⾯2.2 抽奖结果导出*************特等奖奖获得者:(抽奖时间:2021/12/30 22:41:22)***************⼯号:100899 姓名:⽯臻臻的杂货铺领域:后端*************⼀等奖奖获得者:(抽奖时间:2021/12/30 22:42:09)***************⼯号:100931 姓名:牧⽺⼈_阿标领域:移动*************三等奖奖获得者:(抽奖时间:2021/12/30 22:42:17)***************⼯号:100978 姓名:前端⽼实⼈领域:前端⼯号:100952 姓名:Oliver尹领域:前端⼯号:100990 姓名:愿许浪尽天涯领域:运维与安全⼯号:101024 姓名:乔乔家的龙⼥仆领域:其他*************特等奖奖获得者:(抽奖时间:2021/12/30 22:42:46)***************⼯号:100900 姓名:川川菜鸟领域:⼤数据*************六等奖获得者:(抽奖时间:2021/12/30 22:42:51)***************⼯号:101013 姓名:忧伤额蜗⽜领域:移动⼯号:101017 姓名:ML.star 领域:后端⼯号:100921 姓名:坚果前端の博客领域:移动⼯号:100986 姓名:Mr数据杨领域:全栈⼯号:100969 姓名:⼤数据⼩禅领域:⼤数据⼯号:100898 姓名:⼩⼩明-代码实体领域:其他⼯号:100949 姓名:执久呀领域:后端⼯号:100977 姓名:yang_z_1 领域:⼤数据⼯号:100944 姓名:可可卷领域:AI⼯号:100988 姓名:曲鸟领域:全栈⼯号:101018 姓名:余光、领域:前端⼯号:100962 姓名:拈花倾城领域:运维与安全⼯号:100918 姓名:艾醒领域:AI⼯号:100979 姓名:林深时不见⿅领域:后端⼯号:100964 姓名:繁星蓝⾬领域:⼤数据⼯号:101022 姓名:互联⽹-⼩阿宇领域:运维与安全⼯号:100980 姓名:振华OPPO 领域:移动⼯号:100923 姓名:_陈哈哈领域:全栈⼯号:100930 姓名:Java执梗领域:后端⼯号:100917 姓名:1_bit 领域:全栈3.源码3.1 数据库连接using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using System.Data.OleDb;using System.Collections;namespace BoeLottery.Model{public class LotteryDataContext{public LotteryDataContext(){if (!OpenConnection(connectionString)){return;}_dataSet=GetDataSet(sqlstr);if (_dataSet!=null){_dataTable = _dataSet.Tables[0];rowData = new List<KeyValuePair<int, int>>();}MaxNO=IMaxNO = GetMaxNoDB();GetDataByte();MaxNO = GetMaxNoDB()+1;}private OleDbDataAdapter dataAdapter = null;private OleDbConnection connection = null;private string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Data//lottery.mdb;Jet OLEDB:Database Password=123456"; string sqlstr = "select * from lottery ";DataSet _dataSet = null;DataTable _dataTable = null;public int MaxNO {get;set;}public int IMaxNO { get; set; }/// <summary>/// Open Connection/// </summary>/// <param name="connectionString"></param>/// <returns></returns>public bool OpenConnection(string connectionString){try{connection = new OleDbConnection(connectionString);connection.Open();}catch (System.Exception ex){if (connection!=null){connection.Close();}return false;throw ex;}return true;}public bool CloseConnection(){if (connection!=null){connection.Close();}return true;}public DataSet GetDataSet(string sqlString){try{DataSet dataSet = new DataSet();dataAdapter = new OleDbDataAdapter(sqlString, connection);dataAdapter.Fill(dataSet);return dataSet;}catch (System.Exception ex){throw ex;}}public List<KeyValuePair<int,int>> rowData { get; set; }public OleDbDataReader GetDataReader(string sqlString){OleDbCommand command = new OleDbCommand(sqlString, connection);OleDbDataReader dataReader = command.ExecuteReader();return dataReader;}public void GetDataByte(){string data = Helper.Logger.ReadLog("System.Data.DataMangentExtensions.dll"); string[] dataSplit=data.Split(';');foreach (string item in dataSplit){GetAdDB(Convert.ToInt32(item));}}public int GetMaxNoDB(){//if (_dataSet.Tables["lottery"].Rows.Count == 0) return 0; 对不对return _dataTable.Rows.Count;}/// <summary>/// 根据ID获取⽤户信息/// </summary>/// <param name="employeeId"></param>/// <returns></returns>public Employee GetQueryData(int employeeId){Employee employee = new Employee();employee.EmployeeID = employeeId;IEnumerable<DataRow> queryData = from p in _dataTable.AsEnumerable() where (int)p.Field<Int16>("userid") == employeeId select p;foreach(var data in queryData){employee.EmployeeNo=data.Field<string>("userno");employee.EmployeeName = data.Field<string>("username");employee.EmployeeDep = data.Field<string>("userdep");}return employee;}/// <summary>/// 根据EmployNo获取⽤户信息/// </summary>/// <param name="employNo"></param>/// <returns></returns>public Employee GetQueryDataByNo(int employNo){IEnumerable<DataRow> queryData = from p in _dataTable.AsEnumerable() where p.Field<string>("userno") == employNo.ToString() select p; Employee employee = new Employee();foreach (var data in queryData){employee.EmployeeNo= data.Field<string>("userno");employee.EmployeeID = (int)data.Field<Int16>("userid");employee.EmployeeName = data.Field<string>("username");employee.EmployeeDep = data.Field<string>("userdep");}return employee;}public void GetAdDB(int employNo){IEnumerable<DataRow> queryData = from p in _dataTable.AsEnumerable() where p.Field<string>("userno") == employNo.ToString() select p; if (queryData.Count() == 0) return;DataRow row = _dataTable.NewRow();foreach(var data in queryData){row["userno"]=data.Field<string>("userno");row["userid"] = GetMaxNoDB()+1;rowData.Add(new KeyValuePair<int,int>((int)data.Field<Int16>("userid"), GetMaxNoDB() + 1));//rowData.Add(new KeyValuePair<int,int>(GetMaxNoDB() + 1,(int)data.Field<Int16>("userid")));//row["userid"] = (int)data.Field<Int16>("userid");row["username"] = data.Field<string>("username");row["userdep"] = data.Field<string>("userdep");}_dataTable.Rows.Add(row);}}}3.2 抽奖程序//各奖项所有的⼈数 { 特等奖、⼀等奖、⼆等奖、三等奖、四等奖 }public int[] WinnerNums = {4, 4, 12, 16, 40, 60, 80};//抽奖次数public int[] LotteryTimes = {4, 4, 3, 4, 2, 3, 4};public int[] HasNotWonNums=new int[7] ;//= { 5, 1, 1, 1, 12 };#endregion#region 设置绑定ICommandpublic ICommand StartLotteryCommand { get; private set; } // 开始抽奖public ICommand SpecialLotteryCommand { get; private set; } //特等奖public ICommand FirstLotteryCommand { get; private set; }public ICommand SecondLotteryCommand { get; private set; }public ICommand ThirdLotteryCommand { get; private set; }public ICommand FouthLotteryCommand { get; private set; }public ICommand SouvenirLotteryCommand { get; private set; }public ICommand SixvenirLotteryCommand { get; private set; }public ICommand ExtendLotteryCommand { get; private set; } //加抽奖#endregionpublic MainViewModel(){//HasNotWonNums = LotteryTimes; //未中奖的赋值for (int i = 0; i < 7;i++ ){HasNotWonNums[i] = LotteryTimes[i];}//GetWinner();//添加⼋个时钟AddTimer(10);StartLotteryCommand = new RelayCommand(()=>{TimerStart();});SpecialLotteryCommand = new RelayCommand(()=>{logger.WriteLog("*************特等奖奖获得者:(抽奖时间:" + DateTime.Now.ToString() + ")***************"); Messenger.Default.Send("特等", "showResultGrade");Lotterying(0);//添加显⽰逻辑});ExtendLotteryCommand = new RelayCommand(() =>{logger.WriteLog("*************加抽奖奖获得者:(抽奖时间:" + DateTime.Now.ToString() + ")***************"); TimerStop();List<Employee> employWinners = GetLotteryList(1);if (employWinners.Count == 0){return;}Messenger.Default.Send("加抽", "showResultGrade");ShowResult(employWinners);//添加显⽰逻辑});FirstLotteryCommand = new RelayCommand(()=>{logger.WriteLog("*************⼀等奖奖获得者:(抽奖时间:" + DateTime.Now.ToString() + ")***************"); Messenger.Default.Send("⼀等", "showResultGrade");Lotterying(1);});SecondLotteryCommand = new RelayCommand(()=>{logger.WriteLog("*************⼆等奖奖获得者:(抽奖时间:" + DateTime.Now.ToString() + ")***************");Messenger.Default.Send("⼆等", "showResultGrade");Lotterying(2);});ThirdLotteryCommand = new RelayCommand(()=>{logger.WriteLog("*************三等奖奖获得者:(抽奖时间:" + DateTime.Now.ToString() + ")***************");Messenger.Default.Send("三等", "showResultGrade");Lotterying(3);});FouthLotteryCommand = new RelayCommand(() =>{logger.WriteLog("*************四等奖奖获得者:(抽奖时间:" + DateTime.Now.ToString() + ")***************");Messenger.Default.Send("四等", "showResultGrade");Lotterying(4);});SouvenirLotteryCommand = new RelayCommand(()=>{logger.WriteLog("*************五等奖获得者:(抽奖时间:" + DateTime.Now.ToString() + ")***************");Messenger.Default.Send("五等", "showResultGrade");Lotterying(5);});//public ICommand SixvenirLotteryCommand { get; private set; }SixvenirLotteryCommand = new RelayCommand(() =>{logger.WriteLog("*************六等奖获得者:(抽奖时间:" + DateTime.Now.ToString() + ")***************");Messenger.Default.Send("六等", "showResultGrade");Lotterying(6);});Messenger.Default.Register<string>(this, "AppClose",(msg) =>{logger.Close();lotteryDataContext.CloseConnection();});}以上就是C#模拟实现抽奖⼩程序的⽰例代码的详细内容,更多关于C#抽奖⼩程序的资料请关注其它相关⽂章!。

python实现公司年会抽奖程序

python实现公司年会抽奖程序

python实现公司年会抽奖程序本⽂实例为⼤家分享了python实现年会抽奖程序的具体代码,供⼤家参考,具体内容如下发⼀下⾃⼰写的公司抽奖程序。

需求:公司年会要⼀个抽奖程序,转盘上的每⼀个⼈名是随机中奖的,中奖后的⼈不可以再次中奖,按住抽奖,就会⼀直在转,放开后,要再转⼀两圈才停。

刚好⾃⼰在学python cocos2d,就⽤这个刚学的东东,直接上源码# coding:utf-8#import sys# import os# sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../..'))# 解决程序中要显⽰中⽂问题reload(sys)sys.setdefaultencoding('utf8')from pyglet import image, fontfrom pyglet.gl import *from pyglet.window import keyfrom cocos.actions import *from cocos.director import directorfrom yer import Layerfrom yer import ColorLayerfrom cocos.scene import Scenefrom cocos.sprite import Spritefrom cocos.text import *from cocos.menu import *import randomfrom cocos.audio.effect import Effectconsts_window = {"width": 680,"height": 700,"vsync": True,"resizable": True,'audio_backend':'sdl'}def get_sprite_test( index ):d = tests[index]return Scene( d( index ) )class SpriteLayer( Layer ):is_event_handler = True #: enable pyglet's eventsdef __init__( self, index=1 ):super(SpriteLayer, self ).__init__()self.index = indexself.top_text = "⼴州德瀚信息信息科技有限公司-年会抽奖"self.image = pyglet.resource.image('r1.png',0.01)# self.image = image.AnimationFrame(image.load('r1.png'),0.1)self.image.anchor_x = self.image.width / 2self.image.anchor_y = self.image.height / 2self.rimage = pyglet.resource.image('r2.png',0.01)# self.rimage = image.AnimationFrame(image.load('r2.png'),0.1)self.rimage.anchor_x = self.image.width / 2self.rimage.anchor_y = self.image.height / 2self.bgimage = pyglet.resource.image('bg1.png')self.bgimage.anchor_x = self.image.width / 2self.bgimage.anchor_y = self.image.height / 2self.pressbgimage = pyglet.resource.image('bg2.png') self.pressbgimage.anchor_x = self.image.width / 2self.pressbgimage.anchor_y = self.image.height / 2self.prizeimage = pyglet.resource.image('name.png') self.prizeimage.anchor_x = self.image.width / 2self.prizeimage.anchor_y = self.image.height / 2def on_key_release( self, keys, mod ):# LEFT: go to previous scene# RIGTH: go to next scene# ENTER: restart sceneif keys == key.LEFT:self.index -= 1if self.index < 1:self.index = len( tests )elif keys == key.RIGHT:self.index += 1if self.index > len( tests ):self.index = 1if keys in (key.LEFT, key.RIGHT):director.replace( get_sprite_test( self.index ) )return Trueclass PrizeMenu(Menu):def __init__( self ):super( PrizeMenu, self ).__init__()self.menu_valign = BOTTOMself.menu_halign = RIGHTself.font_item['color'] = (0,0,0,255)self.font_item_selected['color'] = (32,16,32,255)# print dir(self)# then add the itemsitems = [( MenuItem('⼀等奖', self.prize_go ) ),( MenuItem('⼆等奖', self.prize_go ) ),( MenuItem('三等奖', self.prize_go ) ),( MenuItem('参与奖', self.prize_go ) ),]# self.create_menu( items, selected_effect=zoom_in(), # unselected_effect=zoom_out())self.create_menu( items, shake(), shake_back())def on_quit( self ):pyglet.app.exit()def prize_go( self ):s = self.parentif s.is_begin:s.top_notice.element.text=""else:# s.stop_num = 1s.go_prize()# def main():# pyglet.font.add_directory('.')# director.init( resizable=True)# director.run( Scene( PrizeMenu() ) )# if __name__ == '__main__':# main()class StartPrize( SpriteLayer ):def __init__( self,index ):super( StartPrize, self ).__init__(index)self.current_num = 0 #当前位置self.is_begin = False #是否已经开始self.prize_cycle = 0 #转动圈数self.prize_speed = 0.05 #初始速度self.prize_speed_slow = 0.3 #慢速度self.stop_num = 0 #停⽌的位置self.alread_get_prize = [] # 已经得奖的⼈self.start_slow = Falseself.can_stop = Falseself.press_go = Falseself.sprite = Sprite( self.image )# self.sprite = Sprite( image.Animation([image.AnimationFrame(image.load('r1.png'),0.001)] )) self.alread_prize_sprite = Sprite( self.rimage )self.bgsprite = Sprite( self.bgimage )self.pressbgsprite = Sprite( self.pressbgimage )self.prizesprite = Sprite( self.prizeimage )self.top_label = Label( self.top_text )# 注意是要有个elementself.top_label.element.x = -250self.top_label.element.y = 350self.top_label.element.color = (0,0,0,255)self.top_label.element.font_size = 20self.top_notice = Label( "点击中间开始抽奖" )self.top_notice.element.x = 120self.top_notice.element.y = 300self.top_notice.element.color = (255,0,0,255)self.top_notice.element.font_size = 20self.pressbgsprite.do(Hide())self.alread_prize_sprite.do(Hide())# self.sprite.do(Hide())def on_enter( self ):super(StartPrize,self).on_enter()bgcolor = ColorLayer(255,255,255,255, consts_window['width'], consts_window['height'])bgcolor.position = (-320,-320)# 背景颜⾊self.add( bgcolor )# 标题self.add( self.top_label )self.add( self.top_notice )# 转动的背景图self.add( self.sprite ,z=3)self.add( self.alread_prize_sprite ,z=3)# ⼈名图self.add( self.prizesprite ,z=4)# 背景图self.add( self.bgsprite,z=1 )self.add( self.pressbgsprite,z=1 )self.position = 320,320# menu = PrizeMenu()# menu.position = (-320,-320)# self.add(menu)# self.sprite.do( Repeat(Rotate( 360, 4 ) ))def on_key_press( self, keys, mod ):super(StartPrize,self).on_key_release(keys, mod)if keys == key.ENTER:if self.is_begin:self.top_notice.element.text="正在抽奖中。

JavaScript简单抽奖程序的实现及代码

JavaScript简单抽奖程序的实现及代码

JavaScript简单抽奖程序的实现及代码简单抽奖程序的实现及代码1.需求说明某公司年终抽奖,需要有如下功能1)可以根据实际情况设置到场⼈数的最⼤值2)点击“开始”,⼤屏幕滚动,点击“停⽌”,获奖者的编号出现在⼤屏幕上3)在界⾯⾥显⽰全部奖项获奖⼈编号4)不重复获奖5)不会因为输⼊错误⽽导致抽奖结果异常。

2.代码呈上1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 TRANSITIONAL//EN"><html><head><title>某公司周年庆抽奖</title><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><script language="javascript">var timer;var flag = new Array(100);var existingnum = new Array(100);var clickTimes = 0;var randnum;var cellnum =1;var mobile;var num ;function check_input(){var input = document.getElementById("real_num").value;var re = /^[1-9]+[0-9]*]*$/;if (!re.test(input)){alert("请输⼊正整数");window.location.href=window.location.href;return false;}}//get the random numbers from the mobile array every 0.05sfunction setTimer(){timer = setInterval("getRandNum();",50);document.getElementById("start").disabled = true;document.getElementById("end").disabled = false;}function getRandNum(){document.getElementById("result").value = mobile[GetRnd(0,num)];}function GetRnd(min,max){randnum = parseInt(Math.random()*(max-min+1));return randnum;}//------------------------------------------------//turn the input's running downfunction clearTimer(){noDupNum();clearInterval(timer);document.getElementById("start").disabled = false;document.getElementById("end").disabled = true;}// Re defined array:change the length of the array and delete the checked onefunction noDupNum(){mobile.removeEleAt(randnum);var o = 0;for(p=0; p<mobile.length;p++){if(typeof mobile[p]!="undefined"){mobile[o] = mobile[p];o++;}}num = mobile.length-1;}function setValues(){document.getElementById(cellnum).value = document.getElementById("result").value ;cellnum++;}function set_array(){var real_num = document.getElementById("real_num").value ;mobile= new Array(real_num);var o = 0;for(i=1; i<=real_num;i++){mobile[o] = i;o++;}num = mobile.length-1;document.getElementById("set_number").disabled = true;}Array.prototype.removeEleAt = function(dx){if(isNaN(dx)||dx>this.length){return false;}this.splice(dx,1);}</script></head><body><center><div id="main"><div><h1>获奖⼩伙伴</h1><p><input id="result" type="text" size="30" style="height:130px;width:800px;border:2px solid red;font-size:120;" readonly/> </p><p><input id="start" type="button" value="开始" style="border: 1px solid; border-color: #aaa 000 #000 #aaa;width:4em; background: #fc0;" onclick="setTimer()" /><input id="end" type="button" value="停" style="border: 1px solid; border-color: #aaa 000 #000 #aaa;width:4em; background: #fc0;"onclick="clearTimer();setValues();" disabled/></p><p><strong>⼀等奖(1名)</strong></p><table width="190" height="30" border="1"><tr><td><input name="text1" type="text" id="3" style="height:30px;width:190px;border:1px solid red;font-size:25;" size="28" readonly/></td></tr></table><p>⼆等奖(2名)</p><table width="380" height="30" border="1"><tr><td><input name="text2" type="text" id="2" style="height:30px;width:190px;border:1px solid red;font-size:25;" size="28" readonly/></td><td><input name="text3" type="text" id="1" style="height:30px;width:190px;border:1px solid red;font-size:25;" size="20" readonly/></td></tr></table></div></div><p></p><p></p><div id="setter" style="border:1px solid;width:45em"><h3>系统设置</h3><table width="300" height="30" border="1"><tr><td>活动⼈数</td><td><input type="text" id="real_num" style="width:11em"></td><td><input id="set_number" type="button" value="设置" style="border: 1px solid; border-color: #aaa 000 #000 #aaa;width:4em; background: #fc0;" onclick="check_input();set_array();"/></td></tr><tr></tr></table><br/><input id="set_number" type="button" value="重新开始抽奖" style="border: 1px solid; border-color: #aaa 000 #000 #aaa;width:45em;height: 3em;background: #fc0;" onclick="window.location.href=window.location.href;"/><p></p></div><center></body></html>复制代码3.丑陋截图我很丑,但是我很温柔~。

python制作抽奖程序代码详解

python制作抽奖程序代码详解

python制作抽奖程序代码详解实现制作抽奖程序,需要认知到我们可以看到⼀般抽奖程序界⾯上是有很多按钮的,⽐如中奖区域,按键开始区域等等,所以我们先要设置界⾯,然后把这些按钮添加到界⾯中去,想必这对于学过tkinter的同学应该不难。

下⾯结合实现步骤:设计界⾯、利⽤循环、多线程来完成抽奖程序设置吧。

实现代码:import random #导⼊内置的random模块list1=list(range(0,15)) #将range元素进⾏列表转换并赋值给列表list1print("抽奖号码是:",list1) #打印所有的参与抽奖的号码list2=[] #定义空列表list2,⽤来储存中奖号码while len(list1)>0:result =random.choice(list1) #在列表list1⾥选择抽取的号码并赋值给resultif result in list1 and result%2==0 and result%3==0:print("您的号码是:{},恭喜您,您中⼀等奖".format(result))list1.remove(result)list2.append(result)elif result%5==0:print("您的号码是:{},恭喜您,您中了⼆等奖".format(result))list1.remove(result)list2.append(result)elif result%3==0:print("您的号码是:{},恭喜您,您中了三等奖".format(result))list1.remove(result)list2.append(result)elif result%2!=0 and result%3!=0 and result%5!=0:print("您的号码是:{},您未中奖".format(result))elif result==list1[-1] or result==list1[0]: #当抽取到列表list1最后⼀个或者第⼀个元素时print("您的号码是:{},抽奖结束".format(result)) #打印号码,并打印抽奖结束print("中奖名单是:", list2)print("未中奖名单是:", list1)Break输出结果:抽奖号码是: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]您的号码是:5,恭喜您,您中了⼆等奖您的号码是:10,恭喜您,您中了⼆等奖您的号码是:6,恭喜您,您中⼀等奖您的号码是:3,恭喜您,您中了三等奖您的号码是:13,您未中奖您的号码是:11,您未中奖您的号码是:14,抽奖结束中奖名单是: [5, 10, 6, 3]未中奖名单是: [0, 1, 2, 4, 7, 8, 9, 11, 12, 13, 14]实例扩展:import xlrd,random#导⼊读取excel的模块xlrd,取随机数的模块randomdata = xlrd.open_workbook("01.xls")#xlrd模块中的函数table = data.sheet_by_index(0)#同上num = input("请输⼊抽奖⼈数:")start = input("请输⼊起始位置:")end = input("请输⼊结束位置:")start = eval(start)#将字符串转换为整数end = eval(end)num = eval(num)print("获奖名单为:")for i in range(num):idx = random.randint(start,end+1)tmp = table.cell_value(idx,1)#将读取到的元素临时存储到tmp中print(tmp)#输出tmp中存储的值到此这篇关于python制作抽奖程序代码详解的⽂章就介绍到这了,更多相关如何使⽤python制作抽奖程序内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!。

用Python实现简单的抽奖程序

用Python实现简单的抽奖程序

⽤Python实现简单的抽奖程序抽奖基本需求1、假设中奖概率为:获得 a道具 10% b道具 20% c道具 30% d道具 40%2、基本的想法是:⽣成1-100的连续数组,随机⽣成⼀个整数,如果是1-10 则中a、10-30 中b、30-60中c、60-100中d实现⽅法⼀:布尔判断1、第⼀种⽅法,直接判断数据在哪个范围,⾮常简单def choujiang0():#⽣成⼀个1-100的随机整数x = np.random.randint(0,100,dtype='int')if x>=0 and x<10:return 'a'if x>=10 and x<30:return 'b'if x>=30 and x<60:return 'c'if x>=60:return 'd'实现⽅法⼆:算法判断2、第⼆种⽅法:作为⼀个程序猿,不能满⾜于这种太简单的⽅法,不适合拓展嘛,所以想办法做改造下,⽤⼀个算法来实现抽奖,主要有以下两种⽅式:2.1 把⼀个初始概率⽤字典来做配置,注意这⾥字典的键值是10、30、60、100,然后通过程序⽣成整数,判断这个整数落在区间⾥的概率,对应字典得到获得的奖励,以下是choujiang1⽅法:ratio = {10:'a',30:'b',60:'c',100:'d'}def choujiang1():#⽣成⼀个1-100的随机整数x = np.random.randint(1,101,dtype='int')#⽣成⼀个1-100的数组mother = [x for x in range(1,101,1)]#判断x在数组的什么位置x_position = mother.index(x)pre_number = 0for key in ratio.keys():if x_position - pre_number>=0 and x_position-int(key)<0:return ratio[key]if pre_number == 0:pre_number=int(key)return -12.2 在第⼀点判断整理落在哪个区间的⽅法,有两种,第⼀种⽐较简单,通过for循环遍历字典,从数字0开始,如果满⾜⼤于等于前区间⼩于后区间,则直接读取字典值作为奖励,⽅法没问题,但次数多了这种遍历效率不⾼;第⼆种使⽤⼆分法,相对复杂⼀点,但是算法效率⾼⼀些,需要额外写⼀个⼆分法的递归⽅法search,来判断随机数值落在哪个区间,以下是search⽅法和choujiang2⽅法:search⽅法:这个⽅法尤为重要,可以说是经典递归的基础⽅法#⼆分查询⽅法def search(seq,number,lower=0,upper=None):if upper==None:upper = len(seq) - 1#print('now lower is ',lower,' upper is ',upper)if upper==lower:#print('now lower is ',lower,' upper is ',upper)return upperelse:middle = (upper+lower)//2if number>seq[middle]:#print('now lower is ',middle+1,' upper is ',upper)return search(seq,number,middle+1,upper)else:#print('now lower is ',lower,' upper is ',middle)return search(seq,number,lower,middle)choujiang2⽅法:#第⼆种抽奖⽅式ratio = {10:'a',30:'b',60:'c',100:'d'}list_ratio = []for i in ratio.keys():list_ratio.append(i)list_ratio = sorted(list_ratio)def choujiang2():#⽣成⼀个1-100的随机整数x = np.random.randint(1,101,dtype='int')i = search(list_ratio,x,lower=0)key = list_ratio[i]return ratio[key]验证和效率1、如何验证验证⼀下概率是否符合我们的期望,代码如下:def test_choujiang(func,*args,**kwargs):Counter = {'a':0,'b':0,'c':0,'d':0}n = 1000000for i in range(n):result = func(*args,**kwargs)for key in Counter.keys():if result==key:Counter[key] += 1print('a的概率是:{}'.format(Counter['a']/n))print('b的概率是:{}'.format(Counter['b']/n))print('c的概率是:{}'.format(Counter['c']/n))print('d的概率是:{}'.format(Counter['d']/n))%time test_choujiang(choujiang0)2、⽐较不同抽奖⽅法的效率采⽤⼆分法的抽奖⽅法,相对来说灵活性好且效率最⾼。

JAVA抽奖系统源代码.doc

JAVA抽奖系统源代码.doc

JAVA抽奖系统源代码/*主界面* MainFrame.java** Created on __DATE__, __TIME__*/package com.insigma.frame;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.IOException;import java.io.InputStreamReader;import .URLDecoder;import javax.swing.JDialog;import javax.swing.JFrame;import javax.swing.UIManager;importorg.jvnet.substance.SubstanceLookAndFeel; importorg.jvnet.substance.painter.StandardGradientPainter;importorg.jvnet.substance.theme.SubstanceTerracotta Theme;import mutil.CardThread; import mUtil; import mutil.ImageThread;/**** @author __USER__*/public class MainFrame extends javax.swing.JDialog{/** Creates new form MainFrame */public MainFrame(java.awt.Frame parent, boolean modal){super(parent, modal);initComponents();this.setLocationRelativeTo(null);// 居中显示try{UIManager.setLookAndFeel(new SubstanceLookAndFeel());JFrame.setDefaultLookAndFeelDecorated(tr ue);JDialog.setDefaultLookAndFeelDecorated(tr ue);SubstanceLookAndFeel.setCurrentTheme(new SubstanceTerracottaTheme());//SubstanceLookAndFeel.setSkin(new EmeraldDuskSkin());//SubstanceLookAndFeel.setCurrentButtonShap er(new//ClassicButtonShaper());//SubstanceLookAndFeel.setCurrentWatermark (new//SubstanceBubblesWatermark());//SubstanceLookAndFeel.setCurrentBorderPain ter(new// StandardBorderPainter());//SubstanceLookAndFeel.setCurrentGradientPai nter(new//StandardGradientPainter());//水晶蓝//SubstanceLookAndFeel.setCurrentTitlePainter( new// FlatTitlePainter());} catch (Exception e){System.err.println("Something went wrong!");}try{showPerson();} catch (IOException e){// TODO Auto-generated catch blocke.printStackTrace();}}public void showPerson() throws IOException {String filename = URLDecoder.decode(Class.class.getResource("/com/insigma/config/name.txt").getPath());FileInputStream fileInputStream = new FileInputStream(filename);InputStreamReader inputStreamReader =new InputStreamReader(fileInputStream, "gbk");BufferedReader bufferedReader = new BufferedReader(inputStreamReader);String name = "";String bufname = "";int key = 1;while ((name = bufferedReader.readLine()) != null){if (bufname.equals(""))bufname = name;elsebufname = bufname + "\n" + name;CommUtil.map.put(key, name);key++;}this.jTextArea4.setText(bufname);this.jLabel4.setText("准备......!");}/** This method is called from within the constructor to* initialize the form.* WARNING: Do NOT modify this code. The content of this method is* always regenerated by the Form Editor.*///GEN-BEGIN:initComponents// <editor-fold defaultstate="collapsed" desc="Generated Code">private void initComponents(){jLabel1 = new javax.swing.JLabel();jLabel2 = new javax.swing.JLabel();jLabel3 = new javax.swing.JLabel();jScrollPane1 = new javax.swing.JScrollPane();jTextArea1 = new javax.swing.JTextArea();jScrollPane2 = new javax.swing.JScrollPane();jTextArea2 = new javax.swing.JTextArea();jScrollPane3 = new javax.swing.JScrollPane();jTextArea3 = new javax.swing.JTextArea();jLabel4 = new javax.swing.JLabel();jLabel5 = new javax.swing.JLabel();jScrollPane4 = new javax.swing.JScrollPane();jTextArea4 = new javax.swing.JTextArea();jButton1 = new javax.swing.JButton();jButton2 = new javax.swing.JButton();jButton3 = new javax.swing.JButton();jLabel6 = new javax.swing.JLabel();setDefaultCloseOperation(javax.swing.Windo wConstants.DISPOSE_ON_CLOSE);setTitle("\u516c\u53f8\u5e74\u7ec8\u62bd\u5 956\u7cfb\u7edf");jLabel1.setText("\u4e00\u7b49\u5956\u83b7\u5f97\u8005\uff1a");jLabel2.setText("\u4e8c\u7b49\u5956\u83b7\u 5f97\u8005\uff1a");jLabel3.setText("\u4e09\u7b49\u5956\u83b7\u 5f97\u8005\uff1a");jTextArea1.setColumns(20);jTextArea1.setRows(5);jScrollPane1.setViewportView(jTextArea1);jTextArea2.setColumns(20);jTextArea2.setRows(5);jScrollPane2.setViewportView(jTextArea2);jTextArea3.setColumns(20);jTextArea3.setRows(5);jScrollPane3.setViewportView(jTextArea3);jLabel4.setFont(new java.awt.Font("宋体", 1, 18));jLabel4.setForeground(newjava.awt.Color(255, 0, 0));jLabel4.setBorder(javax.swing.BorderFactor y.createLineBorder(newjava.awt.Color(0, 0, 0)));jLabel5.setText("\u62bd\u5956\u8005\u540d\ u5355\uff1a");jTextArea4.setColumns(20);jTextArea4.setRows(5);jScrollPane4.setViewportView(jTextArea4);jButton1.setText("\u5f00\u59cb");jButton1.addActionListener(newjava.awt.event.ActionListener(){public void actionPerformed(java.awt.event.ActionEvent evt){jButton1ActionPerformed(evt);}});jButton2.setText("\u6682\u505c");jButton2.setEnabled(false);jButton2.addActionListener(newjava.awt.event.ActionListener(){public void actionPerformed(java.awt.event.ActionEvent evt){jButton2ActionPerformed(evt);}});jButton3.setText("\u91cd\u7f6e");jButton3.setEnabled(false);jButton3.addActionListener(newjava.awt.event.ActionListener(){public void actionPerformed(java.awt.event.ActionEvent evt){jButton3ActionPerformed(evt);}});jLabel6.setFont(new java.awt.Font("微软雅黑", 1, 36));jLabel6.setForeground(newjava.awt.Color(153, 0, 153));jLabel6.setText("\u516c\u53f8\u5e74\u7ec8\u62bd\u5956");javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());getContentPane().setLayout(layout);layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayo ut.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG).addGroup( layout.createSequentialGroup().addGap(98, 98,98) .addComponent(jButton1).addGap(47, 47,47) .addComponent(jButton3).addGap(44, 44,44) .addComponent(jButton2).addGap(104,104,104)).addGroup( layout.createSequentialGroup().addContainerGap().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG).addComponent(jScrollPane1,javax.swing.GroupLayout.PREFERRED_SIZ E,142,javax.swing.GroupLayout.PREFERRED_SIZ E).addComponent(.addPreferredGap(ponentPlaceme nt.RELATED,14,Short.MAX_V ALUE).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG).addComponent(.addComponent(jScrollPane2,javax.swing.GroupLayout.PREFERRED_SIZ E,137,javax.swing.GroupLayout.PREFERRED_SIZ E)).addGap(33,33,33).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG).addComponent(jScrollPane3,javax.swing.GroupLayout.PREFERRED_SIZ E,126,javax.swing.GroupLayout.PREFERRED_SIZ E).addComponent(jLabel3))) .addGroup(layout.createSequentialGroup().addGap(108,108,108).addComponent(jLabel6)).addComponent(jLabel5).addGroup(layout.createSequentialGroup().addComponent(jScrollPane4,javax.swing.GroupLayout.PREFERRED_SIZ E,134,javax.swing.GroupLayout.PREFERRED_SIZ E).addPreferredGap(ponentPlacement.RELATED,80,Short.MAX_V ALUE).addComponent(jLabel4,javax.swing.GroupLayout.PREFERRED_SIZ E,116,javax.swing.GroupLayout.PREFERRED_SIZ E).addGap(122,122,122))).addPreferredGap(ponentPlaceme nt.RELATED))).addGap(13, 13, 13)));layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayo ut.Alignment.LEADING).addGroup(layout.createSequentialGroup().addComponent(jLabel6).addGap(26, 26, 26).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING).addGroup(layout.createSequentialGroup().addComponent(jLabel1).addPreferredGap(ponentPlaceme nt.RELATED).addComponent(jScrollPane1,javax.swing.GroupLayout.PREFERRED_SIZ E,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.PREFERRED_SIZ E)).addGroup(layout.createSequentialGroup().addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASEL INE).addComponent(jLabel3).addComponent(jLabel2)).addPreferredGap(ponentPlaceme nt.RELATED).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI NG).addComponent(jScrollPane3,javax.swing.GroupLayout.PREFERRED_SIZ E,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.PREFERRED_SIZ E).addComponent(jScrollPane2,javax.swing.GroupLayout.PREFERRED_SIZ E,javax.swing.GroupLayout.DEFAULT_SIZE,javax.swing.GroupLayout.PREFERRED_SIZ E)))).addGap(28, 28, 28).addComponent(jLabel5).addPreferredGap(ponentPlaceme nt.RELATED).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILI NG).addComponent(jLabel4,javax.swing.GroupLayout.DEFAULT_SIZE,148,Short.MAX_V ALUE).addComponent(jScrollPane4,javax.swing.GroupLayout.DEFAULT_SIZE,148,Short.MAX_V ALUE)).addPreferredGap(ponentPlaceme nt.RELATED).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILI NG).addComponent(jButton1).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASEL INE).addComponent(jButton3).addComponent(jButton2))).addContainerGap()));pack();}// </editor-fold>//GEN-END:initComponents/*** 重置事件* @param evt*/private void jButton3ActionPerformed(java.awt.event.Actio nEvent evt){this.jButton1.setEnabled(true);this.jButton3.setEnabled(false);CommUtil.boo = false;//重置计数器CommUtil.firstsum = 0;CommUtil.secondsum = 0; CommUtil.thirdsum = 0;//清空抽奖框this.jTextArea1.setText("");this.jTextArea2.setText("");this.jTextArea3.setText("");//重置人员try{showPerson();} catch (IOException e){// TODO Auto-generated catch blocke.printStackTrace();}}/*** 暂停事件* @param evt*/private void jButton2ActionPerformed(java.awt.event.Actio nEvent evt){CommUtil.boo = false;this.jButton2.setEnabled(false);this.jButton1.setEnabled(true);}/*** 开始事件* @param evt*/private void jButton1ActionPerformed(java.awt.event.Actio nEvent evt){CommUtil.boo = true;this.jLabel4.setText(null);CardThread cardthread = newCardThread(this);cardthread.start();ImageThread imageThread = new ImageThread(this);imageThread.start();new Thread(cardthread).start();new Thread(cardthread).start();new Thread(cardthread).start();new Thread(cardthread).start();this.jButton1.setEnabled(false);this.jButton2.setEnabled(true);}/*** @param args the command line arguments*/public static void main(String args[]){java.awt.EventQueue.invokeLater(new Runnable(){public void run(){MainFrame dialog = new MainFrame(new javax.swing.JFrame(), true);dialog.addWindowListener(new java.awt.event.WindowAdapter(){public void windowClosing(java.awt.event.WindowEvent e){System.exit(0);}});dialog.setVisible(true);}});}//GEN-BEGIN:variables// Variables declaration - do not modify public javax.swing.JButton jButton1;public javax.swing.JButton jButton2;public javax.swing.JButton jButton3;public javax.swing.JLabel jLabel1;private javax.swing.JLabel jLabel2;private javax.swing.JLabel jLabel3;public javax.swing.JLabel jLabel4;private javax.swing.JLabel jLabel5;private javax.swing.JLabel jLabel6;private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; private javax.swing.JScrollPane jScrollPane3; private javax.swing.JScrollPane jScrollPane4; public javax.swing.JTextArea jTextArea1; public javax.swing.JTextArea jTextArea2; public javax.swing.JTextArea jTextArea3; public javax.swing.JTextArea jTextArea4;// End of variables declaration//GEN-END:variables}抽奖功能:package mutil;import com.insigma.frame.MainFrame;public class CardThread extends Thread{private MainFrame mainframe;public CardThread(MainFrame mainframe) {this.mainframe = mainframe;}public void run(){synchronized (mainframe){firstCard();secondCard();thirdCard();}if (CommUtil.isEnd()){mainframe.jButton1.setEnabled(false);mainframe.jLabel4.setText("抽奖结束!");mainframe.jButton2.setEnabled(false);mainframe.jButton3.setEnabled(true);}}/*** 抽一等奖*/public void firstCard(){while (CommUtil.boo && CommUtil.firstsum < CommUtil.firstcount) {int key = (int) (Math.random() * 60 + 1);if (CommUtil.getPerson(key)){String name =CommUtil.map.get(key);if (mainframe.jTextArea1.getText() != null&& !mainframe.jTextArea1.getText().equals( "")){mainframe.jTextArea1.setText(mainframe.jTe xtArea1.getText()+ "\n" + name);} else{mainframe.jTextArea1.setText(name);}CommUtil.deletePerson(key);String bufname = CommUtil.mapToString();mainframe.jTextArea4.setText(bufname);CommUtil.firstsum++;try{sleep(1000);} catch (InterruptedException e){// TODO Auto-generated catch blocke.printStackTrace();}}}}/*** 抽三等奖*/public void thirdCard(){while (CommUtil.boo && CommUtil.thirdsum < CommUtil.thirdcount) {int key = (int) (Math.random() * 60 + 1);if (CommUtil.getPerson(key)){String name = CommUtil.map.get(key);if (mainframe.jTextArea3.getText() != null&& !mainframe.jTextArea3.getText().equals( "")){mainframe.jTextArea3.setText(mainframe.jTe xtArea3.getText()+ "\n" + name);} else{mainframe.jTextArea3.setText(name);}CommUtil.deletePerson(key);String bufname =CommUtil.mapToString();mainframe.jTextArea4.setText(bufname);CommUtil.thirdsum++;try{sleep(1000);} catch (InterruptedException e){// TODO Auto-generated catch blocke.printStackTrace();}}}}/*** 抽二等奖*/public void secondCard(){while (CommUtil.boo && CommUtil.secondsum < CommUtil.secondcount){int key = (int) (Math.random() * 60 + 1);if (CommUtil.getPerson(key)){String name = CommUtil.map.get(key);if (mainframe.jTextArea2.getText() != null&& !mainframe.jTextArea2.getText().equals( "")){mainframe.jTextArea2.setText(mainframe.jTe xtArea2.getText()+ "\n" + name);} else{mainframe.jTextArea2.setText(name);}CommUtil.deletePerson(key);String bufname = CommUtil.mapToString();mainframe.jTextArea4.setText(bufname);CommUtil.secondsum++;try{sleep(1000);} catch (InterruptedException e){// TODO Auto-generated catch blocke.printStackTrace();}}}}}工具类:package mutil;import java.util.HashMap;import java.util.Map;import java.util.Set;public class CommUtil{public static boolean boo = false;public static Map<Integer, String> map = new HashMap<>();/*** 奖项获奖人数*/public static int firstcount = 1;public static int secondcount = 3;public static int thirdcount = 5;/*** 计数器*/public static int firstsum = 0;public static int secondsum = 0;public static int thirdsum = 0;/*** 查找人员*/public static boolean getPerson(int key) {boolean boo = false;if(map.get(key)!=null&& !map.get(key).equals("")){boo = true;}return boo;}public static boolean isEnd(){boolean boo = false;if(firstcount == firstsum && secondcount==secondsum && thirdcount==thirdsum){boo = true;}return boo;}/*** 删除人员*/public static boolean deletePerson(int key) {boolean boo = false;map.remove(key);return boo;}/*** map转换为字符串*/public static String mapToString(){String bufname = "";Set<Map.Entry<Integer, String>> entries = map.entrySet();for (Map.Entry<Integer, String> entry : entries){String name = entry.getValue();if(bufname.equals(""))bufname = name;elsebufname = bufname+"\n"+name;}return bufname;}}显示头像:package mutil;import com.insigma.frame.MainFrame;public class ImageThread extends Thread{private MainFrame mainframe;public ImageThread(MainFrame mainframe) {this.mainframe = mainframe;}public void run(){showImage();if (CommUtil.isEnd()){mainframe.jLabel4.setIcon(null);}}public void showImage(){while (CommUtil.boo && !CommUtil.isEnd()){int key = (int) (Math.random() * 60 + 1);if (CommUtil.getPerson(key)){String name = CommUtil.map.get(key);if (name != null){name = name.substring(0, name.indexOf(","));mainframe.jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/insigma/imag/" + name + ".jpg")));try{sleep(1000);} catch (InterruptedException e)。

c#写的实用抽奖程序,附源代码

c#写的实用抽奖程序,附源代码

c#写的实⽤抽奖程序,附源代码
前段时间⽤c#写了个抽奖程序,基于.net framework2.0 IDE:VS2008,现在拿出来和⼤家共享下.
其实这个程序不是我的原创,源代码是从CSDN下载的我根据⾃⼰需要做了⼀些修改和算法上的优化.
另外还做了个⼩⼩的⼿脚,呵呵... 就是可以固定中奖者.具体的⽤法是直接在程序启动的时候加上参数即可:
启动参数
Lucky.exe 特等奖⼀等奖1|⼀等奖2|⼀等奖3 ⼆等奖1|⼆等奖2|⼆等奖3|⼆等奖4 ...
如果不需要这个功能可以直接忽略...
将抽奖⼈员名单写在staff.txt⾥即可...
PS:我不是专业的程序员,所以代码很乱,⾼⼿可以直接路过.献丑了呵呵!
主界⾯的背景图我删除了,有需要⾃⼰找张加⼊即.右下⾓有个输⼊框是⽤来调整祝福语字体⼤⼩的,设置完双击⽣效.废话不多说了我把源代码附上有兴趣的朋友拿去研究吧...。

用JavaScript编程语言编写随机选择抽奖程序示例

用JavaScript编程语言编写随机选择抽奖程序示例

用JavaScript编程语言编写随机选择抽奖程序示例文章标题:用JavaScript编程语言编写随机选择抽奖程序示例介绍内容:抽奖活动是一种常见的活动形式,而编程语言可以帮助我们实现自动化的随机选择抽奖程序。

本文将介绍如何使用JavaScript 编程语言编写一个简单而实用的随机选择抽奖程序示例。

首先,我们需要在HTML页面中创建一个抽奖按钮和一些候选人的列表,如下所示:```html<!DOCTYPE html><html><head><title>随机选择抽奖程序示例</title></head><body><h1>随机选择抽奖程序示例</h1><button onclick="selectWinner()">抽奖按钮</button><ul id="candidates"><li>候选人1</li><li>候选人2</li><li>候选人3</li><li>候选人4</li><!--可以继续添加更多候选人--></ul><h2 id="winner"></h2><script src="script.js"></script></body></html>```在上述HTML页面中,我们创建了一个抽奖按钮,并在<ul>标签中列出了一些候选人的姓名。

点击抽奖按钮后,我们将在JavaScript代码中编写逻辑来随机选择一个候选人作为获奖者,并将结果显示在<h2>标签中。

抓阄程序python代码

抓阄程序python代码

抓阄程序python代码
抓阄程序Python代码
以下是一个简单的抓阄程序Python代码,可以用于随机抽取一定数量的人员或物品:
```python
import random
# 输入参与抓阄的人员或物品列表
items = input("请输入参与抓阄的人员或物品,用逗号分隔:").split(",")
# 输入要抽取的数量
num = int(input("请输入要抽取的数量:"))
# 随机抽取
result = random.sample(items, num)
# 输出结果
print("抽取结果为:")
for i in result:
print(i)
```
使用方法:
1. 打开Python编辑器,将上述代码复制粘贴到编辑器中。

2. 运行程序,按照提示输入参与抓阄的人员或物品列表,每个人员或
物品之间用逗号分隔。

3. 输入要抽取的数量。

4. 程序将随机抽取指定数量的人员或物品,并输出结果。

注意事项:
1. 输入的人员或物品列表必须用逗号分隔,不能有空格。

2. 输入的要抽取的数量必须是正整数。

3. 如果要抽取的数量大于参与抓阄的人员或物品数量,程序将会报错。

总结:
抓阄程序是一种常见的随机抽取程序,可以用于各种场合,如抽奖、
分组、随机点名等。

Python语言具有简单易学、代码简洁、功能强大
等优点,非常适合编写抓阄程序。

以上代码只是一个简单的示例,可以根据实际需求进行修改和扩展。

基于Python编写一个B站全自动抽奖的小程序

基于Python编写一个B站全自动抽奖的小程序

基于Python编写⼀个B站全⾃动抽奖的⼩程序⽬录导语开发⼯具环境搭建原理简介导语应好友邀请,帮他写了个⼩程序,功能类似于实时监控⾃⼰关注的UP主,如果关注的UP主中有⼈发布了抽奖的动态,就⾃动参与这个抽奖。

这样就能不错过任何⼀个可以暴富的机会了。

写完之后感觉这个想法还是挺有意思的,于是上来分享⼀波。

废话不多说,让我们愉快地开始吧~开发⼯具Python版本:3.7.8相关模块:DecryptLogin模块;以及⼀些python⾃带的模块。

环境搭建安装Python并添加到环境变量,pip安装需要的相关模块即可。

原理简介我们主要⽤到的⼯具是公众号前⼏天刚发布的DecryptLogin包⾸先,我们需要⽤它来模拟登录B站,具体⽽⾔,需要先pip安装⼀下:pip install DecryptLogin然后利⽤Client类来实现模拟登录,该类可以保存当前的登录会话,在该会话没过期之前再次运⾏程序是不需要重复发送登录请求的,可以避免因为频繁登录账号⽽触发⽹站的风控机制:from DecryptLogin import loginclient = login.Client()bili = client.bilibili(reload_history=True)infos_return, session = bili.login(ername, '微信公众号: Charles的⽪卡丘', 'scanqr')接着,我们来抓包看看抓取⾃⼰的关注列表要请求哪个API吧,具体⽽⾔,如下图所⽰:代码简单实现如下:'''获得关注列表'''def getfollowings(self, session, infos_return):url = 'https:///x/relation/followings'params = {'vmid': infos_return['data']['mid'],'pn': '1','ps': '20','order': 'desc','order_type': 'attention','jsonp': 'jsonp',}response = session.get(url, params=params, headers=self.headers)total = response.json()['data']['total']followings_ids, page = [], 1while True:for item in response.json()['data']['list']:followings_ids.append(item['mid'])if len(followings_ids) >= total: breakpage += 1params['pn'] = str(page)response = session.get(url, params=params, headers=self.headers)return followings_ids类似地,我们可以获得我们关注的UP主的当前所有动态的接⼝如下:'''获得UP主的动态'''def getupdates(self, infos_return, host_uid, session):url = f'https:///dynamic_svr/v1/dynamic_svr/space_history?visitor_uid={infos_return["data"]["mid"]}&host_uid={host_uid}&offset_dynamic_id=0&need_top=1&platform=web' response = session.get(url, headers=self.headers)response_json, updates = response.json(), {}for card in response_json['data']['cards']:dynamic_id = card['desc']['dynamic_id']desp = re.findall(r'"description":"(.*?)"', card['card'])[0]updates[dynamic_id] = despreturn updates转发动态的接⼝如下:'''转发动态'''def forwardupdate(self, session, infos_return, dynamic_id):url = '/dynamic_repost/v1/dynamic_repost/repost'data = {'uid': infos_return['data']['mid'],'dynamic_id': dynamic_id,'content' : random.choice(ments),'ctrl': '[{"data":"5581898","location":2,"length":4,"type":1},{"data":"10462362","location":7,"length":5,"type":1},{"data":"1577804","location":13,"length":4,"type":1}]','csrf_token': session.cookies.get('bili_jct')}response = session.post(url, data=data, headers=self.headers)return response.json()接下来要做的就是如何判断这个动态是不是抽奖动态了,这⾥我们设置利⽤关键词作为判断依据:# 监控新的动态self.logging('开始监控是否有新的抽奖信息发布')while True:time.sleep(self.time_interval)self.logging('开始检测是否有新的抽奖信息发布')for userid in tqdm(followings_ids):updates_old = followings_infos.pop(userid)updates_latest = self.getupdates(infos_return, userid, session)for dynamic_id in updates_latest.keys():if dynamic_id not in updates_old:desp = updates_latest[dynamic_id]if '#互动抽取#' in desp:result = self.forwardupdate(session, infos_return, dynamic_id)self.logging('检测到有新的抽奖信息发布, 已经尝试转发, 返回的结果为{result}')followings_infos[userid] = updates_latest即当动态中有#互动抽取#这四个字的时候,我们就认定这是⼀条抽奖⽤的动态,并对其进⾏转发。

js抽奖实现随机抽奖代码效果

js抽奖实现随机抽奖代码效果

js抽奖实现随机抽奖代码效果随机抽取,简单代码。

复制代码代码如下:<html><title>随机抽奖程序</title><head><meta http-equiv=Content-Type content="text/html; charset=gb2312"></head><body><script type="text/javascript">var alldata = "a,b,c,d,e"var alldataarr = alldata.split(",");var num = alldataarr.length-1 ;var timerfunction change(){document.getElementById("oknum").innerHTML = alldataarr[GetRnd(0,num)];}function start(){clearInterval(timer);timer = setInterval('change()',10);}function ok(){clearInterval(timer);document.getElementById("showresult").value=document.getElementById("oknum").innerText; }function GetRnd(min,max){return parseInt(Math.random()*(max-min+1));}</script><center><div id="oknum" name="oknum" >请单击开始</div><button onclick="start()" accesskey="s">开始</button><button onclick="ok()" accesskey="o">停⽌</button>您的选择是:<input type="text" id="showresult" value=""></center></body></html>。

抽奖程序——精选推荐

抽奖程序——精选推荐

题目:趣味抽奖程序1.设计目的●训练随机数的控制●训练结构体数据编程●训练文件编程2.设计要求●事先把教工的编号、姓名、部门存入电脑●运行过程:⏹选择抽奖的等级,并输入该等级的人数⏹人员滚动显示,按任意键抽取(一个或一组),本等级抽取完毕,集中显示⏹直到抽取所有等级的人员●一个人只能被抽中一次●设计类:⏹密码类⏹加密类⏹文件操作类⏹抽奖类3.设计内容(1)程序流程程序流程(主函数的流程和功能)如图所示:主函数代码如下:#include<fstream>#include<iostream>#include<time.h>#include<stdlib.h>#include<string>#include<conio.h>using namespace std;struct user // 存放密码{char username[11];char password[11];}up[10]={"",""};char filename[20]={""}; // 存放文件名struct stu{int bh;char xm[10];int dj;}x[31]={0,"",0};int num,i;void main(){char yn='n',choice;system("color 1f");cout<<"\n\n\n\t\t\t欢迎登陆趣味抽奖系统 "<<endl<<endl<<endl; InputUserName();InputPassWord();Inputcjxx(); // 输入班级基本信息do{system("cls");system("color 4c");cout<<"***************************************"<<endl;cout<<"* 欢迎使用趣味抽奖程序 *"<<endl;cout<<"***************************************"<<endl<<endl;cout<<" 1. 输入人员基本信息" <<endl<<endl;cout<<" 2. 分组抽奖" <<endl<<endl;cout<<" 3. 显示抽奖结果" <<endl<<endl;cout<<" 4. 用户及密码维护" <<endl<<endl;cout<<" 0. 退出系统" <<endl<<endl;cout<<"****************************************"<<endl;cout<<" 请选择(0-4):";cin>>choice;switch(choice){case '1':Inputryxx();break;case '2':fzchoujiang();break;case '3':Printxx();break;case '4':ModifyUser();break;case '0':cout<<"\n\n是否结束程序(y/n)? ";cin>>yn;}} while(yn=='n' || yn=='N');}(2)数据设计①学生信息:学号、姓名和成绩存放在一个结构体数组x[]中,数组x为全局变量,可以供每个功能使用。

抽奖游戏编程实现

抽奖游戏编程实现

抽奖游戏编程实现抽奖游戏是一种受欢迎的活动,它为玩家提供了获得奖品的机会。

编程实现一个抽奖游戏可以让我们更好地理解随机数生成、程序逻辑以及用户交互等方面的知识。

在本文中,我将介绍如何编程实现一个简单的抽奖游戏,并提供代码示例供参考。

首先,我们需要定义游戏的规则和奖品设置。

在这个抽奖游戏中,我们假设有10个奖品,分别编号为1至10。

玩家每次抽奖可获得一个随机奖品。

游戏初始时,所有奖品都是可用的,但每个奖品只能被抽取一次。

接下来,我们需要使用编程语言来实现这个抽奖游戏。

以Python语言为例,我们可以使用random模块生成随机数,来代表玩家的抽奖结果。

下面是一个基本的抽奖游戏的Python代码示例:```pythonimport randomdef lottery_game():prizes = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 奖品列表lottery_round = 1 # 抽奖轮数while len(prizes) > 0:print("第 {} 轮抽奖开始!".format(lottery_round))input("按下回车键进行抽奖...")selected_prize = random.choice(prizes) # 随机选择一个奖品print("恭喜你,你抽到了奖品 {}!".format(selected_prize))prizes.remove(selected_prize) # 从奖品列表中移除已被抽取的奖品lottery_round += 1print("抽奖游戏结束!")lottery_game()```在这段代码中,我们定义了一个函数`lottery_game()`来实现抽奖游戏的逻辑。

首先,我们创建了一个包含10个奖品编号的列表`prizes`。

然后,我们使用`while`循环来模拟多轮抽奖过程。

C语言实现简单的抽奖系统

C语言实现简单的抽奖系统

C语⾔实现简单的抽奖系统本⽂实例为⼤家分享了C语⾔实现简单的抽奖系统的具体代码,供⼤家参考,具体内容如下效果图#include<stdio.h>#include<string.h>#include<stdlib.h>#include<conio.h>#include<time.h>#include <windows.h>struct data{char id[20];char name[20];};int t1,t2,t3;struct data information[110]; //普通⼈员信息struct data prize1[110]; //总获奖⼈员信息struct data prize2[110]; //总获奖⼈员信息struct data prize3[110]; //总获奖⼈员信息int people=0; //参与抽奖总⼈数int people1=0,people2=0,people3=0; //普通⼀等奖、⼆等奖、三等奖的⼈数char strid[20];//从⽂件中读取信息,放到普通⼈员信息中void Read_information();//打印菜单void Print_menu();//设置奖项⼈数void Set_awards();//开始抽奖void Begin_luck();//删除该学号⼈员在普通⼈员中的信息void Delet_information();void main(){Read_information();Print_menu();}void Read_information()//从⽂件中读取信息{FILE *fp=fopen("抽奖⼈员名单.txt","r");while(!feof(fp)){//存储该信息到普通⼈员信息中,便于设置内幕⼈员fscanf(fp,"%s%s",information[people].id,information[people].name);people++;}fclose(fp);}void Print_menu(){int choose;while(1){system("cls");printf("\n\n");printf("\t\t\t*********************************************************\n");printf("\t\t\t*\t <-欢迎来到抽奖系统->\t\t\t*\n");printf("\t\t\t*\t <-⽬前参与抽奖的总⼈数为%d⼈->\t\t*\n", people); printf("\t\t\t*\t < ⼀等奖设置为%d⼈ >\t\t\t*\n",people1);printf("\t\t\t*\t < ⼆等奖设置为%d⼈ >\t\t\t*\n",people2);printf("\t\t\t*\t < 三等奖设置为%d⼈ >\t\t\t*\n",people3);printf("\t\t\t*\t\t\t\t\t\t\t*\n");printf("\t\t\t*\t\t开始抽奖请按1\t\t\t\t*\n");printf("\t\t\t*\t\t设置奖项⼈数2\t\t\t\t*\n");printf("\t\t\t*\t\t结束程序请按0\t\t\t\t*\n");printf("\t\t\t*\t\t\t\t\t\t\t*\n");printf("\t\t\t*********************************************************\n"); printf("\n\n\t\t\t\t\t请输⼊选项:");scanf("%d",&choose);switch(choose){case 0:return;case 1:Begin_luck();break;case 2:Set_awards();break;}}}//设置奖项⼈数void Set_awards(){int choose;while(1){system("cls");printf("请输⼊三等奖⼈数(正整数):\n");scanf("%d",&t3);if( t3<0 || t3>people){printf("输⼊不合法,请输⼊1到%d之内的数字",people);getch();}else{people3=t3;break;}}while(1){system("cls");printf("请输⼊⼆等奖⼈数:\n");scanf("%d",&t2);if( t2<0 || t2>people){printf("输⼊不合法,请输⼊1到%d之内的数字",people);getch();}else{people2=t2;break;}}while(1){system("cls");printf("请输⼊⼀等奖⼈数:\n");scanf("%d",&t1);if( t1<0 || t1>people){printf("输⼊不合法,请输⼊1到%d之内的数字",people); getch();}else{people1=t1;break;}}printf("设置完毕按任意键返回\n");getch();return;}void Begin_luck() //开始抽奖{if(people1==0 || people2==0 || people3==0){printf("请设置奖项⼈数\n");printf("按任意键返回\n");getch();return;}if( (people1+people2+people3) > people ){printf("中奖⼈数超过总⼈数,请重新设置\n");printf("按任意键返回\n");getch();return;}int i,j=0,choose,t;system("cls");/*******************三等奖⼈员****************************/printf("下⾯开始抽取三等奖⼈员,按任意键继续\n");getch();while(people3--){if(people3<0)break;srand((unsigned)time(0));t=rand()%people;prize3[j++]=information[t];strcpy(strid,information[t].id);Delet_information();}printf("以下是三等奖名单,按任意键继续\n");for(i=0;i<j;i++)printf("%s\n",prize3[i].name);getch();/*******************⼆等奖⼈员****************************/printf("下⾯开始抽取⼆等奖⼈员,按任意键继续\n");getch();while(people2--){if(people2<0)break;srand((unsigned)time(0));t=rand()%people;prize2[j++]=information[t];strcpy(strid,information[t].id);Delet_information();}printf("以下是⼆等奖名单,按任意键继续\n");for(;i<j;i++)printf("%s\n",prize2[i].name);getch();/*******************⼀等奖⼈员****************************/printf("下⾯开始抽取⼀等奖⼈员,按任意键继续\n");getch();while(people1--){if(people1<0)break;srand((unsigned)time(0));t=rand()%people;prize1[j++]=information[t];strcpy(strid,information[t].id);Delet_information();}printf("以下是⼀等奖名单,按任意键继续\n");for(;i<j;i++)printf("%s\n",prize1[i].name);getch();people=0;Read_information();people1=t1,people2=t2,people3=t3;}void Delet_information() //删除该学号⼈员在普通⼈员中的信息{int i,j;for(i=0;i<people;i++)if(strcmp(information[i].id,strid)==0){people--;for(j=i;j<people;j++)information[j]=information[j+1];return;}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

<html>
<title>模拟抽奖</title>
<head>
<meta name="keywords"content="">
<meta http-equiv=Content-Type content="text/html; charset=gb2312">
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
var alldata = "51windows,blueidea,csdn,google,baidu,msn,qq,cctv,microsoft,adobe"//抽奖的姓名,以,为分隔var alldataarr = alldata.split(",")
var num = alldataarr.length-1
var timer
function change(){
document.getElementById("oknum").value = alldataarr[GetRnd(0,num)];}
function start(){
clearInterval(timer);
timer = setInterval('change()',50); //50(毫秒)为变换间隔,越小变换的越快
}
function ok(){ clearInterval(timer);}
function GetRnd(min,max){
return parseInt(Math.random()*(max-min+1));}
</SCRIPT>
模拟抽奖:<input type="text"id="oknum"name="oknum"value="">
<button onclick="start()"accesskey="s">开始(<U>S</U>)</button>
<button onclick="ok()"accesskey="o">停止(<U>O</U>)</button>
</body>
</html>。

相关文档
最新文档