簡體   English   中英

C#如何增加/減少標簽?

[英]C# How To Increment/Decrement A Label?

我試圖做一個簡單的猜數字游戲,但是在某種形式上,問題是當我單擊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();

            }
        }
    }
}

您的代碼有一些問題。 每次單擊按鈕時,都不應生成新的Random 您應該創建一個類級別的Random變量,並將其默認設置為一個new Random() (一次)。

您還randNum 更改值之前將lblDebug.Text設置為randNum的值。 這意味着它總是顯示先前的隨機數,而不是當前的隨機數。 要解決此問題,只需將Text屬性的分配randNum的分配randNum

同樣,您btnGuess_ClickbtnGuess_Click方法中使用的代碼都會在每次得分不正確時從得分中減去1。 可能我們應該忽略不正確的猜測,而只給它們最少的嘗試次數。

不過,通常情況下,代碼感覺像是在編寫時沒有適當的設計(對不起,如果我錯了)。 我最常做的是先寫出來的場景,然后寫偽代碼,我我的最終代碼的樣子,終於實現,在實際的代碼。

例如:

場景:
1.表格加載。
2.隨機數在1到100之間選擇。
3.通知用戶他們有15次嘗試猜號碼的嘗試。
4.用戶在文本框中輸入數字,然后按一個按鈕
5.如果數字匹配,則祝賀他們並重置游戲(返回步驟2)
6.如果數字不正確,請告訴他們數字過低還是過高,然后轉到步驟4。
7.如果用戶沒有任何猜測,讓他們知道數字是多少,然后重置游戲。

我要編寫的代碼如下所示:

  • 在表單加載中,我們將調用ResetGame方法
  • 在ResetGame方法中,我們將重置猜測的數量,選擇一個隨機數,並放置一個帶有說明的消息框
  • 在Button Click事件中,我們調用一個稱為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;
    }
}
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;}
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM