【问题标题】:Create two different Random variable [duplicate]创建两个不同的随机变量[重复]
【发布时间】:2021-08-07 14:19:25
【问题描述】:

我正在制作一种扑克游戏,您可以在其中与 ai 对战,并且你们都会得到一组随机数。在为它创建方法时,我注意到程序总是为两者创建相同的数组。

public short[] GenerateNumbers(short[] playerNumbers)  //The generate numbers method creates an array of random numbers
        {
            Random randNumb = new Random();  //Creation of a random type object called randNumb. This object is the one that creates the random numbers in the array

            playerNumbers = new short[5];  //Stating the length of the player's array

            for (int i = 0; i < playerNumbers.Length; i++)  //This loop creates random numbers for every position in the array
            {
                playerNumbers[i] = (short)randNumb.Next(1, 9);
            }

            playerOneHand = playerNumbers;

            return playerOneHand;
        }

        public short[] GenerateAINumbers(short[] aiNumbers)  //The generate numbers method creates an array of random numbers
        {
            Random randAINumb = new Random();  //Creation of a random type object called randNumb. This object is the one that creates the random numbers in the array

            aiNumbers = new short[5];  //Stating the length of the player's array

            for (int j = 0; j < aiNumbers.Length; j++)  //This loop creates random numbers for every position in the array
            {
                aiNumbers[j] = (short)randAINumb.Next(1, 9);
            }

            aiHand = aiNumbers;

            return aiHand;
        }

【问题讨论】:

标签: c#


【解决方案1】:

您可以创建实例级别的随机对象:

private Random rnd = new Random();

public short[] GenerateNumbers(short[] playerNumbers) {...}

public short[] GenerateAINumbers(short[] aiNumbers) {...}

您可以在方法中使用这个 rnd 对象,而不是总是创建一个新对象。

【讨论】:

    猜你喜欢
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-17
    • 2017-07-05
    • 2016-04-12
    • 2012-01-08
    • 1970-01-01
    相关资源
    最近更新 更多