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));
}
}
}
}
6 Replies
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 randomOh great idea! I'll try that now
Much better with the single instance!
What would the Random.Shared do differently?
Random.Shared
is an instance of Random
Basically, the Random
class looks something like this:
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()));