1. 程式人生 > >c#窗體猜數字小遊戲(初級版)

c#窗體猜數字小遊戲(初級版)

        private void button1_Click(object sender, EventArgs e)
        {
            Random a = new Random();                //用隨機數賦值
            n = a.Next(1, 101);                     //答案的值
            int x = 10;
            int y = 60;
            for(int i=0;i<100;i++)                  //建立100個按鈕
            {
                label1.Visible = false;
                Button bt = new Button();
                bt.BackColor = System.Drawing.Color.Blue;//改變按鈕的背景色
                bt.Text = (i + 1).ToString();           //給按鈕的text屬性賦值
                bt.Name = (i + 1).ToString();           //給按鈕的名字賦值
                bt.Width = 40;                          //設定按鈕的寬和高
                bt.Height = 40;
                bt.Location = new Point(x, y);          //設定按鈕的位置
                bt.Click += new EventHandler(bt_Click); //給按鈕點選新增事件
                x += 36;
                if((i+1)%10==0)                         //每十個換一行
                {
                    x = 10;
                    y += 36;
                }
                Controls.Add(bt);                   //將按鈕放入窗體控制元件集合中
            } 
        }
         private void bt_Click(object sender,EventArgs e)
        {
            Button but = (Button)sender;
            int t = int.Parse(but.Text);            //把按鈕的Text的值轉換為整型
                if(t==n)
                {
                label1.Text = "恭喜你答對了!";
                label1.Visible = true;
                but.BackColor = System.Drawing.Color.Red;
                }
                else if (t<n)
                    but.Text = "小";
                else
                    but.Text = "大";
        }
        private void button2_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}