基于C#实现的简单的随机抽号器

版权声明:转载声明来源,请勿用于商业用途! https://blog.csdn.net/qq_27180763/article/details/83863327

由于老师需要,让我写一个随机抽号器,,就很简单的写一个,用C#写的。主要依靠random来实现一个随机数以及list可变长数组实现的。
由于项目难度不大,我就直接放代码了。

using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Windows.Forms;

namespace 随机抽号器
{
    public partial class Form1 : Form
    {
        private int person_number=0;
        private int time = 1;
        private List<int> arr = new List<int>();
        public Form1()
        {
            InitializeComponent();
            Thread thread = new Thread(set_index);
            thread.IsBackground = true;
            thread.Start();
            button3.Enabled = false;
        }

        private void set_index()
        {
            while (true)
            {
                Random rd = new Random(Convert.ToInt32(DateTime.Now.ToString("ddHHmmss", DateTimeFormatInfo.InvariantInfo)));
                while (person_number != 0)
                {
                    Random rd2 = new Random(rd.Next(1, 65535) - rd.Next(1, 65535));
                    int side = rd2.Next(1, person_number + 1);
                    if (!arr.Contains(side))
                    {
                        arr.Add(side);
                    }
                }

                if (person_number == arr.Count && person_number!=0&&arr.Count!=0)
                {
                    break;
                }
                Thread.Sleep(1000);
            }
        
        }

        private void button1_Click(object sender, EventArgs e)
        {
            button3.Enabled = true;
            if (textBox1.Text == "")
            {
                MessageBox.Show("请先输入人数!");
            }
            else {
                person_number =Convert.ToInt32(textBox1.Text);
                richTextBox1.AppendText("成功选择人数!当前抽号人数:" + textBox1.Text + "人\r\n");
                button1.Enabled = false;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            richTextBox1.AppendText("\r\n成功清空当前人数,请重新选择人数!\r\n\r\n");
            button1.Enabled = true;
            button3.Enabled = true;
            person_number = 0;
            time = 1;
            arr.Clear();
            Thread thread = new Thread(set_index);
            thread.IsBackground = true;
            thread.Start();

        }

        private void button3_Click(object sender, EventArgs e)
        {
            richTextBox1.AppendText("第" + time.ToString() + "个人的工号是:" + arr[0] + "\r\n");
            arr.RemoveAt(0);
            if ((time)== person_number) {
                button3.Enabled = false;
                richTextBox1.AppendText("操作完成!所有工号已分配!");
            }
            time++;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
        }
    }
}

运行效果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_27180763/article/details/83863327