从不同的 class 中获取随机数(骰子游戏)

Get random number from different class (Dice Game)

我正在尝试编写游戏 Farkle。它一次最多掷出 6 个骰子。我创建了一个 Die class 来保存骰子的值,并创建了一个 Roll() 方法来滚动骰子。

游戏将创建 6 个骰子的数组并一次掷出所有骰子,所以我不希望骰子 class 在 class 的每个实例中创建一个 Random()否则所有的骰子都会有相同的种子随机数。所以我在我的应用程序的 MainForm 中创建了新的 Random()。

我对从 Die class 中调用 Random() 的正确方法感到困惑,而没有使事情 public 应该是私有的等等。我真的很新,觉得做所有事情 public 会更容易,但我想做正确的事。

我知道最好只对整个程序使用一个 Random() 那么我如何让这个单独的 class 调用它?

死亡 class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Farkle
{
    class Die
    {
        // Fields
        private int _value;

        // Constructor
        public Die()
        {
            _value = 1;
        }

        // Value property
        public int Value
        {
            get { return _value; }
        }

        // Rolls the die
        public void Roll()
        {
            _value = MainForm.rand.Next(6) + 1;
        }

    }
}

主窗体:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Farkle
{
    public partial class MainForm : Form
    {
        private Random rand = new Random(); // Should this be public? Or static?

        public MainForm()
        {
            InitializeComponent();
        }

        // Create dice array
        Die[] diceInHand = new Die[6];

        // Roll each die
        private void MainForm_Load(object sender, EventArgs e)
        {
            foreach (Die die in diceInHand)
                die.Roll();
        }
    }
}

谢谢。

您可以在 Die class 中使用 private static 变量。 static class 只会在 MainForm.

中为所有骰子实例声明一次
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Farkle
{
    class Die
    {
        private static Random rand = new Random(); //note this new item
        // Fields
        private int _value;

        // Constructor
        public Die()
        {
            _value = 1;
        }

        // Value property
        public int Value
        {
            get { return _value; }
        }

        // Rolls the die
        public void Roll()
        {
            _value = rand.Next(6) + 1; //no need to refer to the mainForm
        }

    }
}