2006. november 6., hétfő

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


Problem/Question/Abstract:

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

Answer:

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

const
  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;
var
  a: array[0..high(CaImgs)] of integer;
  j: integer;
  s: string;
begin
  for j := low(a) to high(a) do
    a[j] := j;
  shuffle(a, 0);
  for j := low(a) to high(a) do
  begin
    s := CaImgs[j];
    CaImgs[j] := CaImgs[a[j]];
    CaImgs[a[j]] := s;
  end;
end;

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