0
  • I'm sorry incase this is a bad question, I'm only working with Pascal because of some computer class homework where we have to draw a picture using Pascal *

I'm basicly trying to draw stars at random locations, the problem I'm facing right now is that when I call the procedure inside a loop only 1-2 stars are being drawn even though the loop runs 1000 times.

I've tried generating one by one by clicking a button, and it worked so I'm assuming it has something to do with Random not properly working inside a loop.

     randomize();

     i := 0;
      while i < 1000 do begin
         x := random(Image1.Width);
         y := random(Image1.Height);

         Ellipse(x, y, x+3, y+3);

         i += 1;
      end;

TRINIOX
  • 19
  • 5
  • `Random` works just fine within a loop. In fact, the function has no idea it is being called from inside a loop -- it has no way of finding out. (And that applies to most languages.) So your problem lies elsewhere. A few off-topic hints: Don't call `Randomize` repeatedly. Only call it *once* when your application starts (or at least before you need to use random numbers). Also, notice that Pascal has no `+=` operator. But I think that is a FreePascal extension. Most Pascal developers these days use Delphi, and there there is no operator `+=`. Also, I'd use a `for` loop here. – Andreas Rejbrand Apr 28 '20 at 17:30
  • Where are you using this code? If you are writing a native Win32 application using GDI, you should only paint the window when you receive a `WM_PAINT` message. In Delphi, that typically corresponds to the `OnPaint` event handler. And btw, here is my standard example of how to draw using the GDI in Delphi: https://stackoverflow.com/a/7224075/282848 – Andreas Rejbrand Apr 28 '20 at 17:34
  • wow, it was actually just the += operator that caused this issue, thanks! – TRINIOX Apr 28 '20 at 17:35

1 Answers1

1

Remove the call to Randomize. When placed in a loop it will reinitialize the pseudo random number generator based on the system time, which may not have changed since the previous call.

If you are to call Randomize call it once at startup.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • it was actually just the += operator that caused the issue I was having, I already removed the randomize call in the for loop – TRINIOX Apr 28 '20 at 18:06
  • The code in the question contains a call to Randomize inside the loop. I'm not able to see your screen. – David Heffernan Apr 28 '20 at 18:34
  • I know, but the guy that anwsered before you already pointed that out, thanks anyways for trying to help! – TRINIOX Apr 28 '20 at 20:19
  • That was a comment. This is an answer. Might be worth learning a bit about how answers work, how they are accepted etc. The += 1 should work fine in fpc. I'd regard Inc as idiomatic in Pascal however. – David Heffernan Apr 28 '20 at 21:46