猜数小游戏源码

下载源码:猜数小游戏

100个按钮使用动态生成加载的方式,其中的两个重要方法

 private void InitButton()
        {
            int p_x = 10;
            int p_y = 60;
            for (int i = 0; i < 100; i++)
            {
                Button btn = new Button();
                btn.Name = "btn" + (i + 1).ToString();
                btn.Width = 35;
                btn.Height = 35;
                btn.Text = (i + 1).ToString();
                btn.Location = new Point(p_x, p_y);
                btn.Click += new EventHandler(btn_Click);
                p_x += 36;

                if ((i + 1) % 10 == 0)
                {
                    p_x = 10;
                    p_y += 36;
                }
                Controls.Add(btn);
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "开始")
            {
                timer1.Enabled = true;
                rd = new Random().Next(1, 101);
                button1.Text = "重新开始";
            }
            else if (button1.Text == "重新开始")
            {
                label1.Text = "0";
                rd = new Random().Next(1, 101);
                foreach (var item in Controls)
                {
                    if (item is Button)
                    {
                        Button btn = (item as Button);
                        string name = btn.Name;
                        Regex reg = new Regex("^btn[0-9]{0,3}$");
                        if (reg.IsMatch(name, 0))
                        {
                            timer1.Enabled = true;
                            label1.Text = time.ToString();
                            label1.BackColor = Color.Green;
                            btn.Enabled = true;
                            btn.BackColor = Color.Gainsboro;
                            btn.Text = name.Substring(3);
                        }
                    }
                }
            }
        }

发布者

zebulun

我还是我,不一样的花火!