This broke the program in a very weird way and I'm trying to understand why.
With Randomizer being initialized in each Greyhound object I was getting the following results.
The first dog would always win and the remaining 3 dogs would ALWAYS end up with the same position (somewhere behind the first dog).
Here is the weird thing - if I added a breakpoint early on, stepped through everything while watching the dogs' location, everything would run just fine. But if I moved the breakpoint to the end - where it stops the timer after one dog wins - then I would get the weird result mentioned above - first dog wins, other 3 dogs' locations identical.
Why is the program behaving differently when stepping through all the steps vs running normally or stopping it right before it kills the timer?
Here are the classes set up in this wrong way (please ignore the inefficient code, will get it cleaned up).
Form1.cs
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 Lab_DayAtTheRaces
{
public partial class Form1 : Form
{
Greyhound[] dogs = new Greyhound[4];
public Form1()
{
InitializeComponent();
dogs[0] = new Greyhound() { StartingPosition = 23, RacetrackLength = 482, MyPictureBox = dog1};
dogs[1] = new Greyhound() { StartingPosition = 23, RacetrackLength = 482, MyPictureBox = dog2};
dogs[2] = new Greyhound() { StartingPosition = 23, RacetrackLength = 482, MyPictureBox = dog3};
dogs[3] = new Greyhound() { StartingPosition = 23, RacetrackLength = 482, MyPictureBox = dog4};
}
private void button2_Click(object sender, EventArgs e)
{
RaceTimer.Start();
}
private void RaceTimer_Tick(object sender, EventArgs e)
{
for (int x = 0; x < 4; x++)
{
if (dogs[x].Run())
{
RaceTimer.Stop();
MessageBox.Show("Dog " + x + " has won!");
for (int y = 0; y < 4; y++)
{
dogs[y].TakeStartingPosition();
}
break;
}
}
}
}
}
Greyhound.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing;
namespace Lab_DayAtTheRaces
{
public class Greyhound
{
public int StartingPosition;
public int RacetrackLength;
public PictureBox MyPictureBox = null;
public int Location;
public Random Randomizer;
public bool Run()
{
// move forward either 1,2,3, or 4 spaces at random
// Update the position of my PictureBox on the form
// Return true if I won the race
Randomizer = new Random(); /// <----------- INITIALIZED HERE INSTEAD OF FORM1.CS--------------------
int distance = Randomizer.Next(1,300);
Point p = MyPictureBox.Location;
p.X += distance;
MyPictureBox.Location = p;
if (p.X >= RacetrackLength)
{
return true;
}
else
{
return false;
}
}
public void TakeStartingPosition()
{
Point p = MyPictureBox.Location;
p.X = StartingPosition;
MyPictureBox.Location = p;
}
}
}












