C
C#10mo ago
kcm21

Not so random, random drawing...

I'm doing some drawing in C# as a fun way to learn more about the language, and I'm getting some unexpected results from the Random() method. When trying to distribute a star throughout a black background by entering a random x & y coordinate, the icons just follow somewhat of a line from top left to bottom right. They're placed in a different pattern each time, but still along the same line (see screenshots). Thanks for any suggestions you might give! using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Rebar; namespace Drawing1 { public partial class FormMain : Form { public FormMain() { InitializeComponent(); } private void FormMain_Paint(object sender, PaintEventArgs e) { Graphics g = e.Graphics; Icon starry = new Icon(@"C:\Users\kodym\source\repos\Drawing1\Star.ico"); var rand1 = new Random(); var rand2 = new Random(); for (int i = 0; i < 20; i++) { g.DrawIcon(starry, rand1.Next(1000), rand2.Next(1000)); } } } }
No description
No description
6 Replies
Angius
Angius10mo ago
Try using the same random instance Or better yet, Random.Shared Random can get... wacky, if you don't reuse the same instance Wacky, as in it stops being quite as random
kcm21
kcm21OP10mo ago
Oh great idea! I'll try that now
kcm21
kcm21OP10mo ago
Much better with the single instance!
No description
kcm21
kcm21OP10mo ago
What would the Random.Shared do differently?
Angius
Angius10mo ago
Random.Shared is an instance of Random Basically, the Random class looks something like this:
public class Random
{
public static Random Shared = new Random();

public int Next(int max)
{
// ...
}

// ...
}
public class Random
{
public static Random Shared = new Random();

public int Next(int max)
{
// ...
}

// ...
}
SpReeD
SpReeD10mo ago
For a bit more randomness, especially in a loop, you need to use a different seed than the default time seed, something like Random random = new(BitConverter.ToInt32(Guid.NewGuid().ToByteArray()));
Want results from more Discord servers?
Add your server