28. Random walks

This problem is relatively straightforward. The example solution uses the following code to generate a random walk:

Random Rand = new Random();
Point[] Points = null;

// Generate a random walk.
private void walkButton_Click(object sender, EventArgs e)
{
// Get parameters.
int numSteps = int.Parse(numStepsTextBox.Text);
int stepSize = int.Parse(stepSizeTextBox.Text);

// Start in the center of the PictureBox.
int x = walkPictureBox.ClientSize.Width / 2;
int y = walkPictureBox.ClientSize.Height / 2;

// Build the points.
Points = new Point[numSteps];
for (int i = 0; i < numSteps; i++)
{
Points[i] = new Point(x, y);
switch (Rand.Next(0, 4))
{
case 0: // Up.
y -= stepSize;
break;
case 1: // Right.
x += stepSize;
break;
case 2: // Down.
y += stepSize;
break;
case 3: // Left.
x -= stepSize;
break;
}
}

// Redraw.
walkPictureBox.Refresh();
}

The code first creates a form-level Random object. It also defines a Points array and sets it to null.

When you click the Walk button, its event handler gets the number of steps and the size of each step that you entered in the text boxes. It positions the point (x, y) in the center of the PictureBox and then loops through the desired number of steps.

For each step, the code saves the point (x, y) in the Points array. It then uses the Rand object to randomly move (x, y) up, down, left, or right for the next point in the walk.

The method finishes by refreshing the PictureBox, which makes the following Paint event handler execute:

// Draw the walk.
private void walkPictureBox_Paint(object sender, PaintEventArgs e)
{
if (Points == null) return;

e.Graphics.Clear(walkPictureBox.BackColor);
e.Graphics.DrawLines(Pens.Blue, Points);
}

If the Points array has not yet been created, the method simply exits. Otherwise, it clears the PictureBox and uses the Graphics object's DrawLines method to draw lines connecting the points that define the random walk.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.53.166