Fabian Wennink
Fabian Wennink

Reputation: 137

Windows Phone 8 C# Random Ellipse generation

I'm new to building Windows Phone 8/8.1 apps (second app), and i'm having a pretty annoying problem.

What i'm trying to do, it I want to randomly generate an ellipse on my Canvas. But when i've generated the ellipse, I found out that the ellipse is always generated somewhere on the black line, as you can see in the image down below:

enter image description here

The code that i use to generate the ellipse is this:

    private void CreateDots()
    {

        Random Top = new Random();
        Random Left = new Random();

        int TopPos = Top.Next(0, 390); // screen height
        int LeftPos = Left.Next(0, 800); // screen width

        Ellipse Dot =new Ellipse();
        Dot.Name = "Dot";
        Dot.Fill = new SolidColorBrush(Color.FromArgb(255, 0,0,0));
        Dot.Width = 50;
        Dot.Height = 50;

        Canvas.SetTop(Dot, TopPos);
        Canvas.SetLeft(Dot, LeftPos);

        Canvas.Children.Add(Dot);
    }

Does anybody now how to generate the ellipse anywhere on the screen, and not only on the black line? Thank you in advance for any help.

Upvotes: 0

Views: 110

Answers (1)

Timothy Shields
Timothy Shields

Reputation: 79501

Don't create two Random instances like that. Create a single instance and then use it repeatedly.

Furthermore, persist the Random instance between calls to CreateDots. If you don't and you make calls in rapid succession, you may end up with two consecutive Random instances that have been seeded the same.

Random is by default seeded with the current time.

Your ellipses all tend to lie on the line where Left and Top have the same value because the two Random instances are created in rapid succession and almost always seeded with the same current time. When you then generate the LeftPos and TopPos, both calls to Next are starting from the same state.

Upvotes: 3

Related Questions