2024-09-30_the-python-turtle.html


001| #:name::The Python Turtle
002| #:link::https://thehardcorecoder.com/2024/09/30/the-python-turtle/
003| #:date::2024-09-30
004| #:code::
005| from turtle import *
006| 
007| def draw_star (length=200, angle=170):
008|     '''Draw multi-point star.'''
009| 
010|     # Set pen and fill colors...
011|     color('red', 'yellow')
012| 
013|     # Use filling for this shape...
014|     begin_fill()
015| 
016|     # Infinite loop (be sure to exit!)...
017|     while True:
018|         # Draw a straight line LENGTH long...
019|         forward(length)
020| 
021|         # Turn left ANGLE degrees
022|         left(angle)
023| 
024|         # If we're back where we started...
025|         if abs(pos()) < 1:
026|             # We're done, exit loop...
027|             break
028| 
029|     # Fill the shape drawn since begin_fill...
030|     end_fill()
031| 
032|     # And we're done...
033|     done()
034| 
035| draw_star()
036| 
037| #:code::
038| from random import random
039| from turtle import Screen, Turtle
040| 
041| xmin, xmax = (-2000, +2000)
042| ymin, ymax = (-2000, +2000)
043| 
044| def random_walk (steps=100, distance=100):
045|     '''Send the turtle on a random walk.'''
046|     # Get a turtle canvas...
047|     wdw = Screen()
048| 
049|     # Heading mode: east=0, angles counterclockwise...
050|     wdw.mode('standard')
051| 
052|     # Set canvas size...
053|     wdw.setworldcoordinates(xmin,ymin, xmax,ymax)
054| 
055|     # Set color mode [0-255] or [0-1.0]...
056|     wdw.colormode(255)
057| 
058|     # Get a turtle for drawing...
059|     tur = Turtle()
060| 
061|     # Using degrees (not radians)...
062|     tur.degrees()
063| 
064|     # Set speed of turtle animation...
065|     # (0-10 or fastest|fast|normal|slow|slowest)
066|     tur.speed("fastest")
067| 
068|     # Set width of drawn lines...
069|     tur.pensize(2)
070| 
071|     # Go for a (random) walk...
072|     for s in range(steps):
073|         tur.left(random()*360.0)
074|         tur.forward(dist)
075|         # Check for crossing window edge...
076|         x,y = tur.position()
077|         x0,y0 = x,y
078|         if x < xmin: x0 += (xmax - xmin)
079|         if xmax < x: x0 -= (xmax - xmin)
080|         if y < ymin: y0 += (ymax - ymin)
081|         if ymax < y: y0 -= (ymax - ymin)
082|         # Wrap around if necessary...
083|         if (x0 != x) or (y0 != y):
084|             tur.penup()
085|             tur.setposition(x0,y0)
086|             tur.pendown()
087| 
088|     # Draw a red dot at end of walk...
089|     tur.dot(10, (255,0,0))
090| 
091|     # Make the pen blue...
092|     tur.pencolor(0, 0, 255)
093|     tur.pensize(5)
094| 
095|     # Draw (blue) line back to start...
096|     tur.home()
097|     # s/a:
098|     #tur.setposition(0.0, 0.0)
099|     #tur.setheading(0)
100| 
101|     # Draw a red dot...
102|     tur.dot(10, (255,0,0))
103| 
104| random_walk(steps=1000, dist=200)
105| 
106| #:code::
107| from turtle import Screen, Turtle
108| 
109| def sierpinski_triangle (levels=6, distance=100, xmax=6400, ymax=5600):
110|     '''Draw the Sierpinski Triangle.'''
111| 
112|     def expand_string (s):
113|         '''Expand command string.'''
114|         buf = []
115|         for ch in s:
116|             # Expand X into Y+X+Y...
117|             if ch == 'X':
118|                 buf.append('Y+X+Y')
119|                 continue
120|             # Expand Y into X-Y-X...
121|             if ch == 'Y':
122|                 buf.append('X-Y-X')
123|                 continue
124|             buf.append(ch)
125|         return ''.join(buf)
126| 
127|     # Generate a drawing program LEVELS deep...
128|     program = 'X'
129|     for ix in range(levels):
130|         program = expand_string(program)
131| 
132|     # Get a Screen to draw on...
133|     wdw = Screen()
134|     wdw.title('Sierpinski Triangle')
135|     wdw.mode('standard')
136|     wdw.colormode(255)
137|     wdw.setworldcoordinates(-20,-20, xmax,ymax)
138| 
139|     # Get a Turtle for drawing...
140|     tur = Turtle()
141|     tur.degrees()
142|     tur.speed("fastest")
143|     tur.pensize(2)
144| 
145|     # Draw the Sierpinski Triangle...
146|     xlim, ylim = 0, 0
147|     for cmd in program:
148|         if cmd == '+':
149|             tur.forward(distance)
150|             tur.right(60)
151|         elif cmd == '-':
152|             tur.forward(distance)
153|             tur.left(60)
154| 
155|         # Keep track of how big the triangle gets...
156|         x,y = tur.position()
157|         if xlim < x: xlim = x
158|         if ylim < y: ylim = y
159| 
160|     tur.penup()
161|     tur.home()
162|     print(f'Maximum X: {xlim}')
163|     print(f'Maximum Y: {ylim}')
164|     print()
165| 
166| sierpinski_triangle(4, xmax=1600, ymax=1400)
167| 
168| #:code::
169| from math import fmod
170| from turtle import Screen, Turtle
171| 
172| xmin, xmax = (-1300,  +700)
173| ymin, ymax = (-0000, +2000)
174| 
175| def euler_spiral (theta, steps=1200, distance=50):
176|     '''Draw an Euler Spiral.'''
177| 
178|     # Get a Screen to draw on...
179|     wdw = Screen()
180|     wdw.title(f'Euler Spiral - {theta:.12f} - {steps:,}')
181|     wdw.mode('standard')
182|     wdw.colormode(255)
183|     wdw.setworldcoordinates(xmin,ymin, xmax,ymax)
184| 
185|     # Get a Turtle for drawing...
186|     tur = Turtle()
187|     tur.degrees()
188|     tur.speed("fastest")
189|     tur.pensize(1)
190| 
191|     # Min/max vars for edge tracking...
192|     x0,x1, y0,y1 = 0,0,0,0
193| 
194|     # Draw the spiral...
195|     for ix in range(steps):
196|         # Forward...
197|         tur.forward(distance)
198|         # Turn left...
199|         tur.left(fmod(ix*theta, 360.0))
200|         # Crude "progress bar"...
201|         if (ix % 100) == 0:
202|             print(ix)
203| 
204|         # Keep track of how big the space gets...
205|         x,y = tur.position()
206|         if x < x0: x0 = x
207|         if y < y0: y0 = y
208|         if x1 < x: x1 = x
209|         if y1 < y: y1 = y
210| 
211|     # Return the turtle to the start...
212|     tur.penup()
213|     tur.home()
214| 
215|     # Report how far the turtle went...
216|     print(f'Min/Max X: {x0}, {x1}')
217|     print(f'Min/Max Y: {y0}, {y1}')
218|     print()
219| 
220| euler_spiral(1.123456789)
221| 
222| #:code::
223| from math import sqrt
224| from turtle import Screen, Turtle
225| 
226| xmin, xmax = (-2000, +2000)
227| ymin, ymax = (-1500, +1500)
228| 
229| def do_turtle_program (program):
230|     '''Draw a given program of steps.'''
231| 
232|     # Get a Screen to draw on...
233|     wdw = Screen()
234|     wdw.setup(width=1500, height=1000, startx=0, starty=0)
235|     wdw.title(f'Turtle Test')
236|     wdw.mode('standard')
237|     wdw.colormode(255)
238|     wdw.setworldcoordinates(xmin,ymin, xmax,ymax)
239| 
240|     # Get a Turtle for drawing...
241|     tur = Turtle()
242|     tur.degrees()
243|     tur.speed("fast")
244|     tur.pensize(1)
245|     tur.pencolor(0,0,0)
246| 
247|     # Min/max vars for edge tracking...
248|     x0,x1, y0,y1 = 0,0,0,0
249| 
250|     # Draw the spiral...
251|     for cmd in program:
252|         match cmd[0]:
253|             # Draw a line, angle, distance...
254|             case 'line':
255|                 # Turn...
256|                 tur.left(cmd[1])
257|                 # Forward...
258|                 tur.forward(cmd[2])
259| 
260|             # Set the pen color...
261|             case 'color':
262|                 tur.pencolor(cmd[1])
263| 
264|             # Set the pen color...
265|             case 'width':
266|                 tur.pensize(cmd[1])
267| 
268|             # Set turtle heading to angle...
269|             case 'head':
270|                 tur.setheading(cmd[1])
271| 
272|             # Move the turtle to X, Y...
273|             case 'move':
274|                 tur.penup()
275|                 tur.goto(cmd[1], cmd[2])
276|                 tur.pendown()
277| 
278|             # Unknown command, so complain...
279|             case _:
280|                 raise RuntimeError(f'Unknown command: "{cmd[0]}"')
281| 
282|         # Keep track of how big the space gets...
283|         x,y = tur.position()
284|         if x < x0: x0 = x
285|         if y < y0: y0 = y
286|         if x1 < x: x1 = x
287|         if y1 < y: y1 = y
288| 
289|     # Return the turtle to the start...
290|     tur.penup()
291|     tur.pencolor(0,0,0)
292|     tur.home()
293| 
294|     # Report how far the turtle went...
295|     print(f'Min/Max X: {x0}, {x1}')
296|     print(f'Min/Max Y: {y0}, {y1}')
297|     print()
298| 
299| diagonal = sqrt(pow(2000,2)+pow(1500,2))
300| 
301| program = [
302|     ('move', 2000,-1500), ('color', (0,0,255)), ('width', 3),
303|     ('line', 90, 3000),
304|     ('line', 90, 4000),
305|     ('line', 90, 3000),
306|     ('line', 90, 4000),
307|     ('move', 2000, 0), ('color', (255,0,0)), ('width', 2),
308|     ('line', 143.13, diagonal), # 180-36.87
309|     ('line',  73.74, diagonal), # 2 * 36.87
310|     ('line', 106.26, diagonal), # 180 - (2 * 36.87)
311|     ('line',  73.74, diagonal),
312|     ('head', 270), ('color', (0,0xcc,0)),  ('width', 4),
313|     ('line', 0, 4000),
314| ]
315| do_turtle_program(program)
316| 
317| #:end:code::
318|