I have been playing around with fractals lately, and the Cantor set is like the grandfather of fractals. It's not super interesting to look at but it's a simple rule set that I figured I could get working without too much trouble. The trick to drawing fractals lies in recursion, at first I wrote a program that attempted to use recursion by having a gosub call it's self, but I quickly hit the max gosub stack limit. I had to figure out an alternative. I did a little studying and figured that a list would be a good way to store the x & y coordinates of the current generation and use it to write a new list when calculating the next generation. It was a good learning experience for me as I learned how to copy data from one list to another, read, add, and remove data from a list. I added in variables to allow for the generations to grow/shrink in length, and also for the gap between them to grow/shrink. One problem I encountered is that because the pixels on the screen are whole numbers and the actual dimensions for the rectangles drawn are not, it can cause an imperfect render on the screen (depending on screen size and border settings). After completing the program I also was able to rotate the set to display from the top down instead of left to right, by making a few little changes. I think the next step is to add a function to also write gcode as it draws on the screen so I can plot some of these out and have a hard copy. The plotter will not have the same rendering issue that the screen has due to the greatly increased resolution.
Here is the code:
100 CLS 'CANTOR2.BAS
110 SW=PSIZE(0) 'SCREEN WIDTH
120 SH=PSIZE(1) 'AND HEIGHT
130 BOR=6 'SCREEN BORDER
150 THICKNESS=5 'INITIAL THICKNESS
160 GROW=2 'GROWTH FACTOR
170 GAP=2 'INITIAL GAP SIZE
180 GAPGROW=1.2 'GAP GROWTH FACTOR
190 GENMAX=5 'MAX NUMBER OF GENERATIONS
300 'CALCULATE SEED GENERATION
310 X1=BOR:Y1=BOR
320 X2=X1+THICKNESS:Y2=SH-BOR
330 ~A=[Y1,Y2]
390 FOR Z=0 TO GENMAX
400 GOSUB &CALCGEN 'CALCULATE NEXT GEN ~B LIST
410 GOSUB &DRAWGEN 'DRAW AND ZERO OUT ~A LIST
420 GOSUB ©LIST 'MOVE ~B LIST TO ~A LIST
430 GAP=GAP*GAPGROW
440 THICKNESS=THICKNESS*GROW
450 X1=X2+GAP
460 X2=X1+THICKNESS
470 NEXT Z
999 END
1000 &CALCGEN:
1010 X=LEN(~A)
1020 FOR I=0 TO X-1 STEP 2
1030 TEMPY1=~A(I):TEMPY4=~A(I+1)
1040 PREPEND ~B,TEMPY1
1050 TEMPY2=(((TEMPY4-TEMPY1)/3)+TEMPY1)
1060 PREPEND ~B,TEMPY2
1070 TEMPY3=(((TEMPY4-TEMPY1)/3)+TEMPY2)
1080 PREPEND ~B,TEMPY3
1090 PREPEND ~B,TEMPY4
1094 NEXT I
1095 RETURN
1100 ©LIST:
1110 X=LEN(~B)
1130 FOR I=0 TO X-1
1140 T=POPF(~B)
1150 PREPEND ~A,T
1170 NEXT I
1180 RETURN
1400 &DRAWGEN:
1410 X=LEN(~A)
1430 FOR I=0 TO X-1 STEP 2
1440 Y1=POPF(~A):Y2=POPF(~A)
1450 RECT X1,Y1,X2,Y2,255,255
1460 NEXT I
1470 RETURN