1. 程式人生 > >C#Windows窗體做一個隨機猜數(1~100)

C#Windows窗體做一個隨機猜數(1~100)

public partial class Form1 : Form
    {
        public int k = 0;   //接收隨機數的值
        int count = 0;  //  計數

        int number = 0; //輸入猜的數值

        public Form1()

        {
            InitializeComponent();
        }
        /// <summary>
        /// 新遊戲按鈕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        ///       
        private void butNewGame_Click(object sender, EventArgs e)
        {
            this.txtNum.Enabled = true;
            this.btnGuess.Enabled = true;     
            Random r = new Random();
            k = r.Next(1, 100);//返回一個1~100的整數(包含1,但不包含100)        
            txtanswer.Text = Convert.ToString(k);//謎底Text框

        }

        public const string Hint = "提示";
        /// <summary>
        /// 猜一猜按鈕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnGuess_Click(object sender, EventArgs e)
        {
            //迴圈判斷猜大還是猜小並計數
            do
            {
                number = Convert.ToInt32(txtNum.Text);
                if (number > k)
                {
                    MessageBox.Show("大了,再猜!!", Hint, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    count++;
                }
                else if (number < k)
                {
                    MessageBox.Show("小了,再猜!!", Hint, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    count++;
                }                         
                break;
            } while (number !=k);
            if (number == k )
            {
                count++;
                MessageBox.Show("恭喜你,猜中了!!一共猜了" + count + "次", Hint, MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
            }
        }
        /// <summary>
        /// 退出按鈕
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

    }