C#猜随机数游戏 [英] C# guess random number game

查看:216
本文介绍了C#猜随机数游戏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

应该有一个介于1000到9999之间的随机数,用户应该猜出这个数字。我为此制作了4个不同的文本框。如果数字正确且位于正确的位置,则必须变为绿色。如果数字错了,它必须变成红色,如果数字是正确但是它在错误的地方它应该变黄。例如:

如果数字为1245而用户输入2143就应该是这样的:黄色,黄色,绿色,红色...





此代码有效但用户只能猜测一次,第二次点击按钮时会有另一个随机数。我想让它让用户猜测,直到所有文本框变为绿色。我的代码还有很多重复,我不知道如何解决...(所有这些,如果,如果,elses)



代码块添加 - OriginalGriff [/ edit]



我尝试过:



There should be a random number between 1000 to 9999 and the user should guess the number. I made 4 different text boxes for that. If the number is right and it's on the right place it has to become green. If the number's wrong it has to become red and if the number is right but it's in the wrong place it should get yellow. For example:
if the number is 1245 and the user enters 2143 it should be like this : yellow , yellow, green, red ...


This code works but the user can only guess the number once and the second time that the button is clicked there is another random number. I want it to let the user guess until all the text boxes become green. Also there is a lot of repetition in my code that i don't know how to fix... (all those if, else if , elses)

[edit]Code block added - OriginalGriff[/edit]

What I have tried:

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();
        }

        private void button1_Click(object sender, EventArgs e)
        {
                Random random1 = new Random();
                int rand1 = random1.Next(1, 9);

                Random random2 = new Random();
                int rand2 = random2.Next(0, 9);

                Random random3 = new Random();
                int rand3 = random3.Next(0, 9);

                Random random4 = new Random();
                int rand4 = random4.Next(0, 9);

                if (textBox1.Text == rand1.ToString())
                {
                    textBox1.BackColor = Color.LightGreen;
                }
                else if (textBox1.Text == rand2.ToString() || textBox1.Text == rand3.ToString() || textBox1.Text == rand4.ToString())
                {
                    textBox1.BackColor = Color.Yellow;
                }
                else
                {
                    textBox1.BackColor = Color.Red;
                }

                if (textBox2.Text == rand2.ToString())
                {
                    textBox2.BackColor = Color.LightGreen;
                }
                else if (textBox2.Text == rand1.ToString() || textBox2.Text == rand3.ToString() || textBox2.Text == rand4.ToString())
                {
                    textBox2.BackColor = Color.Yellow;
                }
                else { textBox2.BackColor = Color.Red; }

                if (textBox3.Text == rand3.ToString())
                {
                    textBox3.BackColor = Color.LightGreen;
                }
                else if (textBox3.Text == rand1.ToString() || textBox3.Text == rand2.ToString() || textBox3.Text == rand4.ToString())
                {
                    textBox3.BackColor = Color.Yellow;
                }
                else
                {
                    textBox3.BackColor = Color.Red;
                }

                if (textBox4.Text == rand4.ToString())
                {
                    textBox4.BackColor = Color.LightGreen;
                }
                else if (textBox4.Text == rand1.ToString() || textBox4.Text == rand2.ToString() || textBox4.Text == rand3.ToString())
                {
                    textBox4.BackColor = Color.Yellow;
                }
                else
                {
                    textBox4.BackColor = Color.Red;
                }

                label1.Text = rand1.ToString() + rand2.ToString() + rand3.ToString() + rand4.ToString();

        }   
    }
}

推荐答案

从自己做很多事情开始favors:

1)在按钮单击事件处理程序之外创建一个Random实例,并使用它而不是四个。当你创建一个Random实例时,它是从系统时钟初始化的 - 所以除非你有一个非常慢的计算机,这四个实例几乎肯定会产生完全相同的数字序列...

2)停止使用Visual Studio默认名称 - 你可能还记得今天的TextBox8是手机号码,但是当你必须在三周内修改它时,你会这样吗?使用描述性名称 - 例如tbMobileNo - 您的代码变得更容易阅读,更自我记录,更易于维护 - 并且编码速度更快,因为Intellisense可以通过三次击键来tbMobile,其中TextBox8需要思考大概和8次击键...

不要将数字转换为字符串并进行比较 - 将数字作为文本框中的字符串转换为数字并进行比较。这很容易做到:

Start by doing yourself a lot of favours:
1) Create one Random instance outside the button click event handler and use that instead of four. When you create an instance of Random, it is initialized from the system clock - so unless you have an extremely slow computer, the four instances are almost certainly going to generate exactly the same sequence of numbers...
2) Stop using Visual Studio default names for everything - you may remember that "TextBox8" is the mobile number today, but when you have to modify it in three weeks time, will you then? Use descriptive names - "tbMobileNo" for example - and your code becomes easier to read, more self documenting, easier to maintain - and surprisingly quicker to code because Intellisense can get to to "tbMobile" in three keystrokes, where "TextBox8" takes thinking about and 8 keystrokes...
Don't convert numbers to strings and compare them - convert what should be numbers as strings in text boxes to numbers and compare them. That's easy to do:
int valueFromTheUser;
if (!int.TryParse(myTextBox.Text, out valueFromTheUser))
   {
   // Report problem with his input to the user
   ...
   return;
   }
if (myRandomNumber == valueFromTheUser)
   {
   ...



3)编写一个返回bool的方法:将四个数字传递给它,并检查最后三个中的任何一个是否与第一个匹配。然后调用三次,传递转换后的文本框值。突然间,你的重复消失......

4)这是一个糟糕的游戏 - 用户在任何时候正确使用它的几率是1:1000,这是不会发生的:你如果您希望用户多次播放,则每次尝试猜测时都无法生成新的随机数...


3) Write a method which returns a bool: you pass it four numbers, and it checks if any of the the last three match the first one. Then call that three times, passing the converted textbox value. Suddenly, your repetition vanishes...
4) It's a bad "game" - the odds of the user getting it right at any time is 1:1000, which is just not going to happen: you can't generate a new random number each time he tries to guess it if you want your users to play it more than once...


您的代码与您的说明不符。重新阅读您的说明,将其分解为其部分,然后相应地构建您的代码。例如:



1.单击开始/重新启动按钮,清除文本框,生成随机数



2.用户输入4个数字然后按猜测按钮



3.代码检查值并设置颜色状态为每个条目。如果完成,请转到步骤5.



4.循环回到第2步



5.通知游戏结束的用户。



6.询问用户是否想再次玩游戏。



现在您已准备好编写代码了。提示:需要多个按钮。
Your code does not match your instructions. Re-read your instructions, break it down into its parts, then structure your code accordingly. For example:

1. Start/Restart button is clicked, the textboxes are cleared, and a random number is generated

2. The user enters 4 numbers and press the "guess" button

3. The code checks the values and sets the "color" state for each entry. If completed, go to step 5.

4. loop back to step 2

5. Notify the user that the game has ended.

6. Ask the user if they want to play again.

Now you are ready to write your code. Hint: there is more than one button required.


Hi


使用Random类时,最好只有一个和用当前时间播种它。



然后当你点击按钮时你正在做的是重新分配你的随机变量,这就是他们改变的原因。 />


好​​的,所以从你的前端获取你的逻辑并通过适当的命名获得你的前端。我的意思是Form1,button1,真的吗?甚至在代码项目上。让我鼓励你快速成长:)



所以让我们为你的随机处理创建一个manger对象和一个匹配的集合!

但首先要验证你的输入,以产生没有奇怪错误的可读代码。



Hi
When working with a Random class, it's a good idea to have only one and to seed it with the current time.

Then what you're doing when you click the button is to reassign your random variables, which is why they change.

Ok, so get your logics out of your frontend and get your frontend with proper naming. I mean Form1, button1, really? and even on the code project. Let me encourage you to grow out of that fast :)

So let's invent a manger object for your random handling and a set for matching!
But first verify your input, to produce readable code which doesn't have odd errors.

private int GetValidInputOrThrow(TextBox textbox)
    {
        if (string.IsNullOrEmpty(textbox.Text) || textbox.Text.Length != 1)
            throw new ArgumentException("Only one number in each box, please", "textbox");
        return int.Parse(textbox.Text);
    }

private void button1_Click(object sender, EventArgs e)
{
    //TODO: Add a trycatch in case of validation problems
    int one = GetValidInputOrThrow(textBox1);
    int two = GetValidInputOrThrow(textBox2);
    int three = GetValidInputOrThrow(textBox3);
    int four = GetValidInputOrThrow(textBox4);

    MatchSet matchThis = MatchManager.GetMatchSet();

    if (one.Equals(matchThis.NumberOne))
        TextBox1.Backcolor = Color.LightGreen;

        //...





现在为matchmanager类,它基本上包装了一个matchset如果你想要那个选项,还可以使用getnewmatchset重置它。





Now for the matchmanager class which essentially wraps an matchset and enables that to be reset using getnewmatchset, should you want that option as well.

public class RandomMatchManager
    {
        private Random _rnd = new Random((int)DateTime.Now.Ticks);
        private MatchSet _matchSet;

        public MatchSet GetNewMatchSet()
        {
            _matchSet = new MatchSet
            {
                NumberOne = _rnd.Next(0, 9),
                NumberTwo = _rnd.Next(0, 9),
                NumberThree = _rnd.Next(0, 9),
                NumberFour = _rnd.Next(0, 9)
            };
            return _matchSet;
        }

        public MatchSet GetMatchSet()
        {
            if (_matchSet == null)
                return GetNewMatchSet();
            return _matchSet;
        }
    }

    public class MatchSet : IEquatable<MatchSet>
    {
        public int NumberOne { get; set; }
        public int NumberTwo { get; set; }
        public int NumberThree { get; set; }
        public int NumberFour { get; set; }

        public bool Equals(MatchSet other)
        {
            return NumberOne.Equals(other.NumberOne) && NumberTwo.Equals(other.NumberTwo) && NumberThree.Equals(other.NumberThree) && NumberFour.Equals(other.NumberFour);
        }
    }



您会注意到Random保留,并且matchset提供了比较整个集合的能力,个别值有从价值类型来看也是如此。使用当前时间刻度值来创建随机数,以避免得到与随机相同的值系列真的不一定是随机的。



等等最后一位unvealed是以经理类型的形式制作一个懒惰的财产




You will notice that the Random is kept and that the matchset offers the ability to compare the entire set, the individual values have the same from being value types. The Random is newed up with the current time tick value, to avoid getting the same values series as random really isn't necessarily that random :)

And so last bit unrevealed is making a lazy property on the form of the manager type

public partial class Form1 : Form
  {
      private RandomMatchManager MatchManager
      {
          get
          {
              if (_matchManager == null)
                  _matchManager = new RandomMatchManager();
              return _matchManager;
          }
      }
      private RandomMatchManager _matchManager;


这篇关于C#猜随机数游戏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆