【问题标题】:Get random number from different class (Dice Game)从不同类别中获取随机数(骰子游戏)
【发布时间】:2016-03-22 01:17:38
【问题描述】:

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

游戏将创建一个包含 6 个骰子的数组并同时掷出所有骰子,因此我不希望 Die 类在该类的每个实例中创建一个 Random() ,否则所有骰子将具有相同的种子随机数。所以我在我的应用程序的 MainForm 中创建了新的 Random()。

我对从 Die 类调用 Random() 的正确方法感到困惑,而不会公开应该是私有的东西等等。我真的很新,觉得将所有内容公开会更容易,但我想把事情做好。

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

模具类:

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

谢谢。

【问题讨论】:

  • 告诉我,"use only one Random() for the whole program" 的预期优势是什么

标签: c# random dice


【解决方案1】:

您可以在 Die 类中使用 private static 变量。 static 类只会为您的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
        }

    }
}

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2016-05-07
  • 2011-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-17
  • 2021-08-05
  • 2014-02-28
相关资源
最近更新 更多