This is the first problem of the Optimal Code problem thread. For more information about the Optimal Code event, click here.
Problem description:
I have a list of 50 TImage components. They each have an image preloaded in design time. I also have a variable that holds a number between 1 and 50. I want to check the variable for the value and then display the corresponding image from the correct TImage component.
First solution:
[code=pascal]
procedure textureTile(tile :TTileInfo; tilenr: byte);
var i : byte;
name : string;
begin
case tilenr of
1: Map.Canvas.Draw(tile.x*32,tile.y*32, image1.Picture.Graphic);
2: Map.Canvas.Draw(tile.x*32,tile.y*32, image2.Picture.Graphic);
3: Map.Canvas.Draw(tile.x*32,tile.y*32, image3.Picture.Graphic);
4: Map.Canvas.Draw(tile.x*32,tile.y*32, image4.Picture.Graphic);
5: Map.Canvas.Draw(tile.x*32,tile.y*32, image5.Picture.Graphic);
6: Map.Canvas.Draw(tile.x*32,tile.y*32, image6.Picture.Graphic);
7: Map.Canvas.Draw(tile.x*32,tile.y*32, image7.Picture.Graphic);
8: Map.Canvas.Draw(tile.x*32,tile.y*32, image8.Picture.Graphic);
9: Map.Canvas.Draw(tile.x*32,tile.y*32, image9.Picture.Graphic);
10: Map.Canvas.Draw(tile.x*32,tile.y*32, image10.Picture.Graphic);
11: Map.Canvas.Draw(tile.x*32,tile.y*32, image11.Picture.Graphic);
12: Map.Canvas.Draw(tile.x*32,tile.y*32, image12.Picture.Graphic);
(..)
50: Map.Canvas.Draw(tile.x*32,tile.y*32, image50.Picture.Graphic);
end;
end;[/code]
10 lines is doable, 50 is not. There must be a better way, especially because the only thing that changes is the value and the name of the image component.
Alternative solution:
[code=pascal]procedure textureTile(tile :TTileInfo; tilenr: byte);
var i : byte;
name : string;
begin
for i := 0 to ComponentCount - 1 do
if Components[i] is TImage then
begin
name := (Components[i] as TImage).Name;
delete(name,1, length('Image'));
if strToInt(name) = tilenr then
begin
map.Canvas.Draw(tile.x*32,tile.y*32, (Components[i] as TImage).Picture.Graphic);
break;
end;
end;
end;[/code]
Looks better, but I don't like the loop, especially because this procedure is called a lot, which means that its probably slower than the first solution. Perhaps there is a better way to handle this?
Bookmarks