星期三, 6月 14, 2017

[C#] 猜數字

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Guess
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        int guess, count, max, min;
        private void label2_Click(object sender, EventArgs e)
        {

        }

        private void labelMsg_Click(object sender, EventArgs e)
        {

        }

        private void buttonExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            count++;
            // labelMsg.Text = count;
            int myGuess = 0;
            try{
                myGuess = int.Parse(textBoxGuess.Text);
            }
            catch(Exception ex){
                MessageBox.Show(ex.Message + ",請輸入數字");
            }
            if (myGuess == guess)
            {
             
                MessageBox.Show("Bingo, you got it!");
                buttonOK.Enabled = false;
            }
            else if(myGuess > guess){
                  MessageBox.Show("再小一點.");
                max = myGuess;
     
            }
            else{
                MessageBox.Show("再大一點.");
                  min =  myGuess;
            }
            labelTitle.Text = min + "< ? < " + max;
            labelMsg.Text = "共猜了"+ count + "次!";
        }
       
        //
       
        private void buttonRetry_Click(object sender, EventArgs e)
        {

        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Random r = new Random();
            guess = r.Next(1, 100);
            min = 1;
            max = 99;
            count = 0;
            labelTitle.Text = min + "< ? < " + max;
            labelMsg.Text = "共猜了" + count + "次";
            textBoxGuess.Text = "";
        }
    }
}

沒有留言: