【问题标题】:C# How To Increment/Decrement A Label?C#如何增加/减少标签?
【发布时间】:2017-07-19 21:47:35
【问题描述】:

我正在尝试做一个简单的猜数字游戏,但在一个表格中,问题是当我点击 btnGuess 时,分数会上升,即使它是空白的,尽管有比较逻辑。如果我删除第 59 行的guessCount 和 lblguessCount.Text =guessCount.ToString();它只是消极地下降。即使这个数字是正确的猜测,无论它是负数还是正数,它都不会改变......

    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_The_Number_V2
{
    public partial class Form1 : Form
    {
        private int score = 0;
        private int randNum;
        private int guess = 0;
        private int guessCount = 0;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void lblGenerate_Click(object sender, EventArgs e)
        {
            lbldebug.Text = randNum.ToString();
            Random rand = new Random();
            randNum = rand.Next(0, 10);
        }

        private void txtGuess_TextChanged(object sender, EventArgs e)
        {
            guess = Convert.ToInt32(txtGuess.Text);
        }


        private void btnGuess_Click(object sender, EventArgs e)
        {
            {

                if (guess == randNum)
                {
                    score += 1;
                    lblScore.Text = score.ToString();

                }
                else if (guess != randNum)
                {
                    score-=1;
                    lblScore.Text = score.ToString();
                }

                guessCount++;
                lblguessCount.Text = guessCount.ToString();

            }
        }
    }
}

【问题讨论】:

    标签: c# forms increment


    【解决方案1】:

    您的代码存在一些问题。每次单击按钮时不应生成新的Random。您应该创建一个类级别的Random 变量并将其默认设置为new Random()(一次)。

    您还将 lblDebug.Text 设置为 randNum 的值您更改值之前。这意味着它总是显示前一个随机数,而不是当前随机数。要解决此问题,只需将 Text 属性的赋值放在 randNum 的赋值之后。

    此外,您在btnGuess_Click 方法中的代码每次猜错时都会从他们的分数中减去一个。也许我们应该忽略不正确的猜测,而只给他们最少的尝试次数。

    不过,大多数情况下,代码感觉就像是在没有适当设计的情况下编写的(抱歉,如果我错了)。我通常做的是先写出场景,然后编写我喜欢我最终代码看起来的伪代码,最后在实际代码中实现它。

    例如:

    场景:
    1.表单加载。
    2。随机数在 1 到 100 之间选择。
    3。通知用户他们有 15 次尝试猜测该数字。
    4。用户在文本框中输入一个数字并按下按钮
    5。如果数字匹配,恭喜他们并重置游戏(返回步骤#2)
    6。如果数字不正确,请告诉他们是太低还是太高,然后转到第 4 步。
    7.如果用户没有任何猜测,让他们知道数字是多少并重置游戏。

    我想编写的代码如下所示:

    • 在表单加载中,我们将调用 ResetGame 方法
    • 在 ResetGame 方法中,我们将重置猜测次数,选择一个随机数,并放置一个带有说明的消息框
    • 在按钮单击事件中,我们调用了一个名为CheckForWinner 的方法
    • CheckForWinner 方法中,我们看到他们输入了一个有效数字
      • 如果他们没有显示需要纠正猜测的消息
      • 如果有,请查看该数字是否与我们的随机数匹配
      • 如果是,向用户显示一条消息,然后调用ResetGame
      • 如果没有,请调用方法DisplayHighLowMessage
      • 如果没有,我们调用一个方法FinalizeTurn
    • DisplayHighLowMessage 方法中,我们将数字与随机数进行比较,并显示一条消息,指示它是过低还是过高
    • FinalizeTurn方法中,我们增加猜测计数,看看它是否超过最大值
      • 如果大于最大猜数,让用户知道游戏结束,告诉他们数字,并致电ResetGame

    现在我对程序流程和需要创建的方法有了大致的了解,我们可以创建它们了。我们知道我们需要类级别的变量来存储猜测次数、当前分数、当前猜测和随机数。我们还需要一个类级别的 Random 变量,因为它只需要初始化一次。

    代码如下所示:

    public partial class Form1 : Form
    {
        private int score;
        private int randNum;
        private int guess;
        private int guessCount;
        private const int MaxGuesses = 15;
        private readonly Random rnd = new Random();
    
        public Form1()
        {
            InitializeComponent();
        }
    
        private void Form1_Load(object sender, EventArgs e)
        {
            ResetGame();
        }
    
        private void ResetGame()
        {
            // Choose new random number
            randNum = rnd.Next(1, 101);
            lblDebug.Text = randNum.ToString();
    
            // Reset variables
            guessCount = 0;
            lblGuessCount.Text = guessCount.ToString();
            txtGuess.Text = "";
    
            // Show instructions
            MessageBox.Show("I've chosen a random number from 1 to 100." +
                $" You have {MaxGuesses} tries to guess it!");
        }
    
        private void btnGuess_Click(object sender, EventArgs e)
        {
            CheckForWinner();
        }
    
        private void CheckForWinner()
        {
            if (guess == randNum)
            {
                // Increment the score
                score += 1;
                lblScore.Text = score.ToString();
    
                // Tell user they won, and reset game
                MessageBox.Show("Congratulations! You guessed" +
                    $" the number in {guessCount} tries!");
    
                ResetGame();
            }
            else
            {
                // Tell them if they're too high or low, and finish this turn
                DisplayHighLowMessage();
                FinalizeTurn();
            }
        }
    
        private void DisplayHighLowMessage()
        {
            MessageBox.Show(guess < randNum
                ? "That guess is too low!"
                : "That guess is too high!");
        }
    
        private void FinalizeTurn()
        {
            // Increment guess count
            guessCount++;
            lblGuessCount.Text = guessCount.ToString();
    
            // If they've used all their guesses, show them the number and reset the game
            if (guessCount > MaxGuesses)
            {
                MessageBox.Show($"Sorry, you're out of guesses! The number was: {randNum}.");
                ResetGame();
            }
        }
    
        private void txtGuess_TextChanged(object sender, EventArgs e)
        {
            // If the textbox is being cleared, allow it and reset the guess.
            if (txtGuess.Text == "")
            {
                guess = 0;
            }
            // Otherwise, use int.TryParse in case the 'Text' property 
            // doesn't contian a valid number. The code below says, 
            // "if TryParse succeeds, update our guess with the new number"
            int newGuess;
            if (int.TryParse(txtGuess.Text, out newGuess))
            {
                guess = newGuess;
            }
    
            // Ensure our textbox is displaying the current value of 'guess'
            txtGuess.Text = guess.ToString();
            txtGuess.SelectionStart = txtGuess.TextLength;
        }
    }
    

    【讨论】:

    • 好点,我确实想让数字在猜测后生成。我想显示生成的数字以进行调试,感谢您注意到它没有正确实现。我将使用并制作更多方法,这是更好的做法。如果您知道我的意思,我将使用您的代码,但不会复制和粘贴。我真的希望我能找到一个合适的关于课程的好教程,以及如何正确使用它们,每个教程都让我感到困惑。遗憾的是,您的权利我没有考虑清楚,在考虑如何正确实施它们之前,我一直在添加一些东西。
    • 我很好奇我知道这个 MessageBox.Show(guess
    • 三元运算符? : 是一个简单的if/else。如果?之前的条件为真,则返回?之后的值,否则返回:之后的值。
    【解决方案2】:
    private void txtGuess_TextChanged(object sender, EventArgs e)
    {
        if(txtGuess.Text != null)
            guess = Convert.ToInt32(txtGuess.Text);
    }
    
    private void btnGuess_Click(object sender, EventArgs e)
        {
            {
                if(guess <= 10 && guess >= 0)
                {
                    if (guess == randNum)
                    {
                        score += 1;
                        lblScore.Text = score.ToString();
    
                    }
                    else if (guess != randNum)
                    {
                        score-=1;
                        lblScore.Text = score.ToString();
                    }
    
                    guessCount++;
                    lblguessCount.Text = guessCount.ToString();
                }else{score -=1;}
            }
        }
    

    【讨论】:

    • 谢谢,我也试过了,但我认为 score -= 会简单地将 1 或 -1 重写为变量。可悲的是,现在无论发生什么,该应用程序都会变成负数
    • 我在答案中添加了更多代码,我现在必须下班。这段代码应该让你开始。 @LiamVallance
    • 不敢相信我没有想到这个逻辑,虽然我以前从未使用过!=,但它仍然是负数,但我要看看,因为我要睡觉了。顺便说一句,干杯!
    • 什么变量会变成负数?您可以使用运算符&gt;= 例如:if(variable &gt;= 0)
    猜你喜欢
    • 2011-11-27
    • 1970-01-01
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-04
    • 2017-07-27
    • 2017-12-31
    相关资源
    最近更新 更多