i'm struggling with the randomizer. I declared the randomizer in the greyhound class as suggested in the book (public Random Randomizer;)...but get a null reference error when using it....
then...declared it as
public Random Randomizer = new Random();
this was the only way i could get it to work...but obviously now i'm running into the bug you warned about in the book....each greyhound instance has its own random() object....and they get the same random seed.
i've tried declaring it in the form initiation....but that doesn't work (don't quite understand why since it is public)
Don't worry -- all of these objects and references will make a lot more sense as you go through the next couple of chapters.
Here's what's going on. When you put this inside the Greyhound class:
CODE
class Greyhound {
public Random Randomizer = new Random();
// ... rest of the class ...
}
then, as you saw, it gives each Greyhound its own instance of Random(). The bug happens because each Random object picks the same random numbers. If they all shared the same instance of Random, then calling its Next() method would pick different random numbers each time.
But you also saw that if you did this:
CODE
class Greyhound {
public Random Randomizer;
// ... rest of the class ...
}
// and later in the Form
Dogs[0] = new Greyhound() { MyPictureBox = dogPictureBox1 /* etc. */ };
then you got a NullReferenceException.
The reason is because the Greyhound object's Random field is set to null, so when you try to call its Next() method like this:
Randomizer.Next(1, 4);
it throws the exception.
What that's telling you is that you need to set that Randomizer field to something.
Go back to the sandwich example and take a close look at exactly how the MenuMaker object is initialized:
MenuMaker menu = new MenuMaker() { Randomizer = new Random() };
Notice how you used that object initializer to set its Randomizer field?
So in this case, you want to create a single instance of Random, and then set each Greyhound object's Randomizer field to contain a reference to that same Random object.
In case it's still not clear, here's another hint -- I stuck it inside a spoiler, because you should try to figure it out first (there's a good lesson in there).
(since this is a spoiler, you need to highlight it with your mouse to see the text)
Here's what to do.
At the top of your form, add this: public Random Randomizer = new Random();
Then, when you initialize each Greyhound object, you have two options. You can set its Randomizer field in the object initializer, which would look something like this:
Dogs[1] = new Greyhound()
{
MyPictureBox = pictureBox1,
StartingPosition = startingPosition,
RacetrackLength = racetrackLength,
Randomizer = randomizer
};
or you can do it explicitly:
Dogs[1] = new Greyhound();
Dogs[1].Randomizer = Randomizer;
// ... etc. ...