display random image

Posted by William

In Reply to assigning a random number posted by Rubin

: hey guys
: at the moment i need to learn how to assign a random number to an image, eg when i click a button the blank images will be assigned a random number which will then load the picture assigned to that number. Used for a slot machine game
: thanks

Suppose you have 3 image components on your form, named Image1, Image2 and Image3. At design time, load an image in each of them via the Object Inspector (property "Picture").

Suppose you have 5 image files in the application's directory, named slot0.jpg, slot1.jpg,... slot4.jpg.

Suppose a button "Button1" that makes the slot wheels spin. You need 3 global variables for remembering the wheel positions, say No1, No2 and No3; these are used to load one of five different images into each Image component, and afterwards for the procedure that calculates the score.

Code example:

var
  No1, No2, No3, Score, ScoreTotal: integer;
    
procedure TForm1.Button1Click(Sender: TObject);
var
  BaseName: string; 
begin
  BaseName := 'C:\SlotMachine\Slot';   // or whatever ;)
  Randomize;         // randomize the random-generator
  No1 := Random(5);  // first random number 0-4
  No2 := Random(5);  // second random number 0-4
  No3 := Random(5);  // third random number 0-4
  Image1.Picture.LoadFromFile(BaseName + IntToStr(No1) + '.jpg');
  Image2.Picture.LoadFromFile(BaseName + IntToStr(No2) + '.jpg');
  Image3.Picture.LoadFromFile(BaseName + IntToStr(No3) + '.jpg');
  DoScoring;
end;
 
procedure TForm1.DoScoring;
begin
  // Calculate score and total score...
  // Display score...
  // and so on...
end; 

Related Articles and Replies