检查输入的数字是高还是低(C#)

时间:2015-05-27 15:15:18

标签: c# winforms visual-studio-2010

我正在上高中课程,并且我已经完成了创建C#Windows窗体应用程序的任务,其中在表单加载时生成随机数,然后用户有7次尝试猜测数字。随机数始终在1到100之间(包括它们)。用户将猜测输入文本框(txtGuess),然后按一个按钮(btnGuess)确认他们的猜测。在每次猜测之后,用户被告知该号码是高于还是低于他们输入的号码。我的代码没有Visual Studio 2010正在接收的错误,但是当我测试它并输入一个数字时,没有任何反应。

(我还有一个标签,可以让用户计算他们已经有多少猜测,并且也没有改变。)

这里是我的代码,任何有关它不起作用的提示都会很棒:)

public partial class Form1 : Form
{
    int guess, num, attempts;
    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        Random random = new Random();
        num = random.Next(100);
        txtGuess.MaxLength = 3;
    }

    private void btnGuess_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar != '\b')      //allows backspace key
        {
            e.Handled = !char.IsNumber(e.KeyChar);      //allows just number keys
        }
    }

    private void loop()
    {
        guess = int.Parse(txtGuess.Text);
        if (guess > num)
        {
            MessageBox.Show("The number is lower.");
        }
        else if (guess < num)
        {
            MessageBox.Show("The number is higher.");
        }
        else
        {
            MessageBox.Show("Good job, you did it!");
            btnGuess.Enabled = false;
        }
        attempts += 1;
        lblAttempts.Text = Convert.ToString(attempts);
    }


    private void btnRestart_Click(object sender, EventArgs e)
    {
        Application.Restart();
    }

    private void btnGuess_Click(object sender, EventArgs e)
    {
        {
            loop();
            if (attempts == 7)
            {
                btnGuess.Enabled = false;
                MessageBox.Show("7 attempts have already being made. Better luck next time!");
            }
            txtGuess.Focus();
        }
    }

    private void btnInfo_Click(object sender, EventArgs e)
    {
        MessageBox.Show("The aim of the game is to correctly guess the randomly generated number in 7 or less tries. The number will always be between, and including 1 to 100. Enter your guess into the text box and hit Guess! you will then be told if the number you entered is higher or lower than the random one. Press the reset button to clear your guess counter and generate a new number.                                                                                                                                                                                                     Have Fun!!");
    }
}

0 个答案:

没有答案
相关问题