Reputation: 13
I am trying to program the game Farkle. It rolls up to 6 dice at once. I created a Die class to hold the value of the die and a Roll() method to roll the die.
The game will create an array of 6 dice and roll them all at once, so I didn't want the Die class to create a Random() in each instance of the class or else all the dice would have the same seeded random numbers. So I created the new Random() in the MainForm of my application.
I am confused about the correct way to call that Random() from the Die class without making things public that should be private and whatnot. I'm really new and feel like making everything public would be way easier but I want to do things right.
I know it's best to use only one Random() for the whole program so how do I have this separate class call it?
Die 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;
}
}
}
Main Form:
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();
}
}
}
Thank you.
Upvotes: 1
Views: 1990
Reputation: 30813
You can use private static
variable in your Die
class. static
class will only be declared once for all your dices' instances in your 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
}
}
}
Upvotes: 1