【发布时间】: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"的预期优势是什么