Your attempt to limit the recursion depth contains an error.
You draw each of the three inner triangles and increment count , then call DrawTriangle again to draw the triangles in those triangles. Each call increments the count again, which means that the counter does not reflect the depth of the recursion, but simply how many times DrawTriangle . As a result of setting the limit of 10, you will find that 10 sets of triangles were displayed in your results.
Instead of increasing count to track the recursion depth, you should decrease n for each call to n = 0 .
To make this intention clearer, you can use a nested procedure in which an external call takes the maximum number of recursion levels specified with an internal, nested procedure that performs the actual recursion, indicating the number of remaining levels and decreasing this number for the recursive calls itself:
procedure DrawTriangle(aCanvas: TCanvas;x,y,size : extended; maxLevels: integer); procedure Draw(x,y,size: extended; levelsLeft: integer); var h : extended; w : extended; i : integer; x1,x2,x3,y1,y2,y3 : extended; begin w := size; h := size; x1 := x; y1 := y; //1st - left aCanvas.MoveTo(Round(x1),Round(y1)); aCanvas.LineTo(Round(x1+w*2),Round(y1)); aCanvas.LineTo(Round(x1+w),Round(y1-h)); aCanvas.LineTo(Round(x1),Round(y1)); //2nd - right x2 := x1+w*2; y2 := y1; aCanvas.MoveTo(Round(x2),Round(y2)); aCanvas.LineTo(Round(x2+w*2),Round(y2)); aCanvas.LineTo(Round(x2+w),Round(y2-h)); aCanvas.LineTo(Round(x2),Round(y2)); //3rd - top x3 := x2-w; y3 := y2-h; aCanvas.MoveTo(Round(x3),Round(y3)); aCanvas.LineTo(Round(x3+w*2),Round(y3)); aCanvas.LineTo(Round(x3+w),Round(y3-h)); aCanvas.LineTo(Round(x3),Round(y3)); //Run itself if (levelsLeft > 0) then begin Draw(x1, y1, size/2, levelsLeft - 1); Draw(x2, y2, size/2, levelsLeft - 1); Draw(x3, y3, size/2, levelsLeft - 1); end; end; begin if Assigned(aCanvas) then Draw(x, y, size, maxLevels); end;
It also allows testing the preconditions more clearly, in which case it is currently limited to guaranteeing that the canvas has been specified, but may also include normalizing or checking other parameters that may be required before starting the recursive call.
Since the original parameters remain in the scope for the nested procedure, this also means that you can limit the parameters in the calls to the recursive procedure only to those that actually change with each call. (I updated the code in my answer to include this).
By the way, a try..except , which simply raises any caught exceptions, is exactly equivalent to the absence of a try..except block, so I removed it from this implementation.
You can also consider adding an additional condition to stop the recursion if the size value reaches certain lows (where the inner triangles are fuzzy, for example, size <2 ).