Reputation: 9
I'm using this to load a image at random from file but as soon as it gets to the last image it shows 'Cannot open file "C:\Users\Misty\Downloads\PAT\Ham.jpg" The system cannot find the file specified'
My images are names 1,2,3 etc so where does the system get ham.jpg?
procedure TfrmGame.FormCreate(Sender: TObject);
begin
arrPics[1] := 'Hen' ;
arrPics[2] := 'Van' ;
arrPics[3] := 'Pen' ;
arrPics[4] := 'Cat' ;
arrPics[5] := 'Fan' ;
arrPics[6] := 'Hut' ;
arrPics[7] := 'Cap' ;
arrPics[8] := 'Dog' ;
arrPics[9] := 'Hat' ;
arrPics[10] := 'Ham' ;
arrPath[1] := '1';
arrPath[2] := '2';
arrPath[3] := '3';
arrPath[4] := '4';
arrPath[5] := '5';
arrPath[6] := '6';
arrPath[7] := '7';
arrPath[8] := '8';
arrPath[9] := '9';
arrPath[10] := '10';
Randomize;
Counter:=Random(10);
sWord:=arrPics[Counter];
imgTest.Picture.LoadFromFile(arrPath[Counter]+'.jpg');
imgTest.Stretch := True ;
end;
procedure TfrmGame.btnNextClick(Sender: TObject);
var
Mark,RoundCounter:integer;
begin
Mark:=0;
RoundCounter:=0;
for RoundCounter:= 1 to 10 do
begin
if sWord=edtWord.Text then
begin
Inc(Mark)
end;
Randomize;
Counter:=Random(10);
sWord:=arrPics[Counter];
imgTest.Picture.LoadFromFile(arrPath[Counter]+'.jpg');
imgTest.Stretch := True ;
edtWord.Clear;
Upvotes: 0
Views: 112
Reputation: 58224
If n
is a positive integer, then random(n)
returns a random number greater than or equal to 0
and strictly less than n
. Since your array indices are 1 to 10, you need a random number in that range, but random(10)
produces a number from 0 to 9. So your Counter
may sometimes be 0
, which means you're attempting to access arrPath[0]
, which is outside of the range of that array. In this case, it is accessing the item before it in memory, which is arrPics[10]
. Do you have real-time range checking turned off in your settings? If you have it on, then Delphi will generate an exception for an array index out of range.
To get a random number from 1 to 10, use: Counter := random(10) + 1
. Or, more simply, you could use Counter := RandomRange(1, 10);
.
Upvotes: 1