C#GUI猜测游戏

本文关键字:游戏 C#GUI | 更新日期: 2023-09-27 18:28:46

我正在尝试用C#创建一个表单猜谜游戏,允许用户进行100次猜测,并计算他们错了多少次,对了多少次。我使用了for循环来尝试实现这一点,但每次我输入一个猜测时,一个计数器将等于1,另一个计数器则等于99。问题是它没有退出for循环,我也不知道如何让它退出。

namespace Assignment10
{
public partial class Form1 : Form
{
    Random random = new Random();
    int[] rando = new int[100];
    int answer;
    int counter1 = 0;
    int counter2 = 0;
    int hoverNumber;
    public Form1()
    {
        InitializeComponent();
        start();
    }
    private void exitButton_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }
    private void nextGuess_Click(object sender, EventArgs e)
    {
        guessButton.Enabled = true;
        hoverBox.Text = "??";
    }
    public void start()
    {
        for (int x = 0; x < rando.Length; x++)
        {
            rando[x] = random.Next(0, 100);
            hoverNumber = rando[x];
        }
    }
    private void guessButton_Click(object sender, EventArgs e)
    {
        answer = Convert.ToInt32(GuessBox.Text);
        for (int i = 0; i < rando.Length; ++i)
        {
            if (answer != rando[i])
                counter1++;
            else
                counter2++;
            for (int x = 0; x < 1; ++x)
            {
                if (answer != rando[i])
                {
                    nextGuess.Enabled = true;
                    guessButton.Enabled = false;
                    label3.Text = "The number incorrect is: " + counter1;
                    GuessBox.Clear();
                }
                else if (answer == rando[i])
                {
                    nextGuess.Enabled = true;
                    guessButton.Enabled = false;
                    label2.Text = "The number correct is: " + counter2;
                    GuessBox.Clear();
                }
            }
        }
    }
    private void mouseLabel_MouseHover(object sender, EventArgs e)
    {
        hoverBox.Text = Convert.ToString(hoverNumber - 3);
    }
}
}

C#GUI猜测游戏

根据您的问题,问题可能出现在guessButton_Click方法中,该方法非常混乱。我假设您只想将猜测与当前数字进行比较,而不是遍历数组。每个数字猜一个,对吧?无论如何,由于您已经有了正确和不正确猜测数量的计数器,这简化了事情。只需对照counter1 + counter2的数组索引检查猜测,如下所示:

private void guessButton_Click(object sender, EventArgs e)
{
    answer = Convert.ToInt32(GuessBox.Text);
    if (answer == rando[counter1+counter2])
    {
        counter2++;
        label2.Text = "The number of correct guesses is: " + counter2;
    }
    else (answer != rando[i])
    {
        counter1++;
        label3.Text = "The number if incorrect guesses is: " + counter1;
    }
    nextGuess.Enabled = true;
    guessButton.Enabled = false;
    GuessBox.Clear();
}