您好,欢迎访问三七文档
当前位置:首页 > 商业/管理/HR > 项目/工程管理 > C#三匹马赛跑-使用进度条和Timer实现
C#实现三匹马赛跑,使用进度条和Timer实现编写比赛代码:3匹马比赛,随机产生胜者,使用进度条和Timer实现:在VisualStudio2005中新建WinForm应用程序:界面如下:用label1,label2,label3来显示三匹马的速度窗体还有3个Timer控件,分别作为三匹马的时钟:源代码如下:usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Text;usingSystem.Windows.Forms;namespaceWinApp{publicpartialclassForm赛马:Form{publicForm赛马(){InitializeComponent();}int[]horse=newint[3];//马的速度decimalsecondCount1=0;decimalsecondCount2=0;decimalsecondCount3=0;///summary///窗体Load事件设置时间间隔为0.1秒为进度条赋值最大值////summary///paramname=sender/param///paramname=e/paramprivatevoidForm赛马_Load(objectsender,EventArgse){progressBar1.Maximum=100;progressBar2.Maximum=100;progressBar3.Maximum=100;timer1.Interval=100;//间隔0.1秒timer2.Interval=100;timer3.Interval=100;}///summary///开始比赛事件:文本提示框恢复默认进度条归零,///重新随机出三匹马的速度先停止时钟再启动计时器////summary///paramname=sender/param///paramname=e/paramprivatevoidbtnBegin_Click(objectsender,EventArgse){richTextBox1.Text=;richTextBox2.Text=;richTextBox3.Text=;progressBar1.Value=0;progressBar2.Value=0;progressBar3.Value=0;secondCount1=0;secondCount2=0;secondCount3=0;//清空重新赋值bool[]b=newbool[21];Randomran=newRandom();for(inti=0;ihorse.Length;i++){intnumber=ran.Next(1,21);//假设马的速度为1~20之间各不相同boolbx=b[number];while(bx)//如果b[number]为true说明number被取到请重新取数{number=ran.Next(1,21);bx=b[number];}b[number]=true;horse[i]=number;}label1.Text=string.Format(马1的速度:[{0}]米每秒,horse[0]);label2.Text=string.Format(马2的速度:[{0}]米每秒,horse[1]);label3.Text=string.Format(马3的速度:[{0}]米每秒,horse[2]);timer1.Stop();//停止计时器timer2.Stop();timer3.Stop();timer1.Start();//启动计时器比赛开始timer2.Start();timer3.Start();}///summary///时钟事件当马已跑完时,计时器停止运行////summary///paramname=sender/param///paramname=e/paramprivatevoidtimer1_Tick(objectsender,EventArgse){secondCount1+=0.1M;decimalx=horse[0]*secondCount1;if(x=progressBar1.Maximum){progressBar1.Value=progressBar1.Maximum;richTextBox1.Text=string.Format(马1已跑完全程[{0}]米,速度:[{1}]米每秒,用时[{2}]秒,100,horse[0],secondCount1);timer1.Enabled=false;}else{progressBar1.Value=(int)x;}Application.DoEvents();}privatevoidtimer2_Tick(objectsender,EventArgse){secondCount2+=0.1M;decimaly=horse[1]*secondCount2;if(y=progressBar2.Maximum){progressBar2.Value=progressBar2.Maximum;richTextBox2.Text=string.Format(马2已跑完全程[{0}]米,速度:[{1}]米每秒,用时[{2}]秒,100,horse[1],secondCount2);timer2.Enabled=false;}else{progressBar2.Value=(int)y;}Application.DoEvents();}privatevoidtimer3_Tick(objectsender,EventArgse){secondCount3+=0.1M;decimalz=horse[2]*secondCount3;if(z=progressBar3.Maximum){progressBar3.Value=progressBar3.Maximum;richTextBox3.Text=string.Format(马3已跑完全程[{0}]米,速度:[{1}]米每秒,用时[{2}]秒,100,horse[2],secondCount3);timer3.Enabled=false;}else{progressBar3.Value=(int)z;}Application.DoEvents();}}}程序运行结果如图:再次随机:
本文标题:C#三匹马赛跑-使用进度条和Timer实现
链接地址:https://www.777doc.com/doc-4699900 .html