2006. november 6., hétfő

How to use Randomize so that the same value is not chosen more than once (2)


Would you mind to make me a random procedure to change the background of my program in an interval of 15 seconds?


The best would be to store the names in an array:

  CaImgs: array[0..9] of string = ('image1.jpg', 'image2.jpg', ...);

This way, on start-up, you can check that the images are there. Then, if you merely want a random image from the array, you do:

myFileName = CaImgs[random(10)];

This means that you have one chance out of ten of repeating the same image - no visible change. If you want to show always different images, but in random order, then you need a shuffle function (see above). To shuffle your array of filenames (despite being declared a constant, it's actually a var), you do this:

procedure shuffleImages;
  a: array[0..high(CaImgs)] of integer;
  j: integer;
  s: string;
  for j := low(a) to high(a) do
    a[j] := j;
  shuffle(a, 0);
  for j := low(a) to high(a) do
    s := CaImgs[j];
    CaImgs[j] := CaImgs[a[j]];
    CaImgs[a[j]] := s;

You do this once at application start. This way, the 10 images will show in random order (but the order will repeat throughout the current run).

In both cases (random of shuffle), you should call Randomize just once, at the start of the application.

Nincsenek megjegyzések:

Megjegyzés küldése