ColabTurtlePlus 2.1.2__py3-none-any.whl → 2.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ColabTurtlePlus/Turtle.py +299 -109
- {colabturtleplus-2.1.2.dist-info → colabturtleplus-2.2.1.dist-info}/METADATA +10 -3
- colabturtleplus-2.2.1.dist-info/RECORD +7 -0
- {colabturtleplus-2.1.2.dist-info → colabturtleplus-2.2.1.dist-info}/WHEEL +1 -1
- colabturtleplus-2.1.2.dist-info/RECORD +0 -7
- {colabturtleplus-2.1.2.dist-info → colabturtleplus-2.2.1.dist-info}/licenses/LICENSE +0 -0
- {colabturtleplus-2.1.2.dist-info → colabturtleplus-2.2.1.dist-info}/top_level.txt +0 -0
ColabTurtlePlus/Turtle.py
CHANGED
|
@@ -42,6 +42,19 @@ combined using register_shape().
|
|
|
42
42
|
|
|
43
43
|
v2.1.2 September 2026
|
|
44
44
|
Fixed an issue introduced with register_shape when two or more turtles had the same shape.
|
|
45
|
+
|
|
46
|
+
v2.2 October 2026
|
|
47
|
+
Fixed some bugs related to color processing and speed.
|
|
48
|
+
Added colormode to handle RGB either in [0,1] range or [1,255] range.
|
|
49
|
+
Modified jumpto to mimic the teleport function added to the turtle module in Python 3.12
|
|
50
|
+
|
|
51
|
+
v2.2.1 November 2026
|
|
52
|
+
New function addgroupcomponent() to add an svg group to a shape compound.
|
|
53
|
+
The image (with or without the turtle(s)) can now be saved as a PNG file to the local computer using the savePNG() function.
|
|
54
|
+
Turtle shapes that are scaled differently in x and y directions are now rotated smoothly in right/left turns.
|
|
55
|
+
The function saveSVG() will now bring up a download dialog box to save the file to the local computer rather than to the
|
|
56
|
+
Colab or Jupyter sidebar file browser.
|
|
57
|
+
|
|
45
58
|
"""
|
|
46
59
|
|
|
47
60
|
DEFAULT_WINDOW_SIZE = (800, 600)
|
|
@@ -81,6 +94,7 @@ VALID_MODES = ('standard','logo','world','svg')
|
|
|
81
94
|
DEFAULT_TURTLE_SHAPE = 'classic'
|
|
82
95
|
VALID_TURTLE_SHAPES = {'turtle', 'ring', 'classic', 'arrow', 'square', 'triangle', 'circle', 'turtle2', 'blank', 'user'}
|
|
83
96
|
DEFAULT_MODE = 'standard'
|
|
97
|
+
DEFAULT_COLORMODE = 255
|
|
84
98
|
DEFAULT_ANGLE_MODE = 'degrees'
|
|
85
99
|
DEFAULT_POINTS = '-5,-4.5 0,-2.5 5,-4.5 0,4.5'
|
|
86
100
|
DEFAULT_NAME = 'classic'
|
|
@@ -123,17 +137,15 @@ TURTLE_TURTLE2_SVG_TEMPLATE = """<g id="turtle2" visibility="{visibility}" trans
|
|
|
123
137
|
TURTLE_USER_SVG_TEMPLATE = """<g id="{id}" visibility="{visibility}" transform="rotate({degrees},{rotation_x},{rotation_y}) translate({turtle_x}, {turtle_y})">
|
|
124
138
|
<polygon points="{points}" transform="skewX({sk}) scale({sx},{sy})" style="stroke:{pcolor};fill:{turtle_color};stroke-width:{pw}" />
|
|
125
139
|
</g>"""
|
|
126
|
-
|
|
127
140
|
TURTLE_COMPONENT_SVG_TEMPLATE = """<g id="user" visibility="{visibility}" transform="rotate({degrees},{rotation_x},{rotation_y}) translate({turtle_x}, {turtle_y})">
|
|
128
|
-
|
|
129
|
-
</g>"""
|
|
141
|
+
{component}</g>"""
|
|
130
142
|
|
|
131
|
-
POLY_TEMPLATE = """<polygon points="{points}" transform="skewX({sk})
|
|
132
|
-
|
|
133
|
-
ELLIPSE_TEMPLATE = """<ellipse transform="skewX({sk}) scale({sx},{sy})"
|
|
134
|
-
style="stroke:{pcolor};fill:{turtle_color};
|
|
135
|
-
|
|
136
|
-
transform="skewX({sk}) scale({sx},{sy})"
|
|
143
|
+
POLY_TEMPLATE = """<polygon points="{points}" transform="skewX({sk}) scale({sx},{sy})"
|
|
144
|
+
style="stroke:{pcolor};fill:{turtle_color};stroke-width:{pw}" />"""
|
|
145
|
+
ELLIPSE_TEMPLATE = """<ellipse transform="skewX({sk}) scale({sx},{sy})" style="stroke:{pcolor};fill:{turtle_color};stroke-width:{pw}" rx="{rx}" ry ="{ry}" cx="{cx}" cy="{cy}" />"""
|
|
146
|
+
PATH_TEMPLATE = """<path d="{path}" style="stroke:{pcolor};fill-rule:{fill_rule};fill:{turtle_color};fill-opacity:1;" transform="skewX({sk}) scale({sx},{sy})"/>"""
|
|
147
|
+
GROUP_TEMPLATE = """<g style="stroke:{pcolor};fill-rule:{fill_rule};fill:{turtle_color};fill-opacity:1;"
|
|
148
|
+
transform="skewX({sk}) scale({sx},{sy})"> {group} </g>"""
|
|
137
149
|
|
|
138
150
|
|
|
139
151
|
SPEED_TO_SEC_MAP = {0: 0, 1: 1.0, 2: 0.8, 3: 0.5, 4: 0.3, 5: 0.25, 6: 0.20, 7: 0.15, 8: 0.125, 9: 0.10, 10: 0.08, 11: 0.04, 12: 0.02, 13: 0.005}
|
|
@@ -163,6 +175,7 @@ class _Screen:
|
|
|
163
175
|
self._turtles = []
|
|
164
176
|
self.window_size = DEFAULT_WINDOW_SIZE
|
|
165
177
|
self._mode = DEFAULT_MODE
|
|
178
|
+
self._colormode = DEFAULT_COLORMODE
|
|
166
179
|
if self._mode in ['standard','logo']:
|
|
167
180
|
self.xmin,self.ymin,self.xmax,self.ymax = -self.window_size[0]/2,-self.window_size[1]/2,self.window_size[0]/2,self.window_size[1]/2
|
|
168
181
|
self.xscale = self.yscale = 1
|
|
@@ -237,7 +250,8 @@ class _Screen:
|
|
|
237
250
|
pw = turtle.outline_width,
|
|
238
251
|
rotation_x=turtle.turtle_pos[0],
|
|
239
252
|
rotation_y=turtle.turtle_pos[1],
|
|
240
|
-
id = turtle.turtle_shape
|
|
253
|
+
id = turtle.turtle_shape,
|
|
254
|
+
fill_rule=turtle.fill_rule)
|
|
241
255
|
return svg
|
|
242
256
|
|
|
243
257
|
# helper function for linking svg strings of text
|
|
@@ -275,8 +289,6 @@ class _Screen:
|
|
|
275
289
|
svg+=turtle.svg_stampsT_string
|
|
276
290
|
return svg
|
|
277
291
|
|
|
278
|
-
|
|
279
|
-
# Helper function for generating the whole svg string
|
|
280
292
|
def _generateSvgDrawing(self):
|
|
281
293
|
return SVG_TEMPLATE.format(window_width=self.window_size[0],
|
|
282
294
|
window_height=self.window_size[1],
|
|
@@ -290,18 +302,8 @@ class _Screen:
|
|
|
290
302
|
drawlines=self._svg_drawlines_string,
|
|
291
303
|
kolor=self.border_color)
|
|
292
304
|
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
Args:
|
|
297
|
-
turtle: (optional) a boolean that determines if the turtles
|
|
298
|
-
are included in the svg output
|
|
299
|
-
|
|
300
|
-
The SVG commands can be printed on screen (after the drawing is
|
|
301
|
-
completed) or saved to a file for use in a program like inkscape
|
|
302
|
-
or Adobe Illustrator, or displaying the image in a webpage.
|
|
303
|
-
"""
|
|
304
|
-
|
|
305
|
+
# Helper function for generating the entire svg string for use in showSVG, saveSVG, and savePNG
|
|
306
|
+
def _generateSvgString(self, turtle=False):
|
|
305
307
|
header = ("""<svg width="{w}" height="{h}" viewBox="0 0 {w} {h}" xmlns="http://www.w3.org/2000/svg">\n""").format(
|
|
306
308
|
w= self.window_size[0],
|
|
307
309
|
h= self.window_size[1])
|
|
@@ -315,47 +317,145 @@ class _Screen:
|
|
|
315
317
|
dots = self._generateSvgDots().replace(">",">\n")
|
|
316
318
|
turtle_svg = (self._generateTurtlesSvgDrawing() + " \n") if turtle else ""
|
|
317
319
|
output = header + stampsB + lines + image + dots + stampsT + turtle_svg + "</svg>"
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
"""Saves the image as an SVG file.
|
|
320
|
+
return(output)
|
|
321
|
+
|
|
322
|
+
def showSVG(self, turtle=False):
|
|
323
|
+
"""Shows the SVG code for the image to the screen.
|
|
323
324
|
|
|
324
325
|
Args:
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
the default name SVGimage.svg will be used.
|
|
328
|
-
turtle: an optional boolean that determines if the turtles
|
|
329
|
-
are included in the svg output saved to the file. Default is False.
|
|
326
|
+
turtle: (optional) a boolean that determines if the turtles
|
|
327
|
+
are included in the svg output
|
|
330
328
|
|
|
331
329
|
The SVG commands can be printed on screen (after the drawing is
|
|
332
|
-
completed) or saved to a file for use in a program like inkscape
|
|
333
|
-
or Adobe Illustrator, or displaying the image in a webpage.
|
|
330
|
+
completed) with showSVG, or saved to a file for use in a program like inkscape
|
|
331
|
+
or Adobe Illustrator, or displaying the image in a webpage with saveSVG.
|
|
334
332
|
"""
|
|
335
|
-
|
|
333
|
+
output = self._generateSvgString(turtle)
|
|
334
|
+
print(output)
|
|
335
|
+
|
|
336
|
+
# Download the image to the local computer as an SVG file using given filename. Set turtle=True to include turtle in svg output
|
|
337
|
+
def saveSVG(self, file="SVGimage.svg", turtle=False):
|
|
338
|
+
"""
|
|
339
|
+
|
|
340
|
+
Args:
|
|
341
|
+
file: Filename as a string. If none is given, the default
|
|
342
|
+
filename "SVGimage.svg" will be used.
|
|
343
|
+
turtle: (optional) a boolean that determines if the turtles
|
|
344
|
+
are included in the svg output
|
|
345
|
+
|
|
346
|
+
Generates the SVG drawing text string and triggers an instant
|
|
347
|
+
direct download onto the user's local computer via the browser.
|
|
348
|
+
Works seamlessly across Google Colab, JupyterLab, and JupyterLite kernels.
|
|
349
|
+
"""
|
|
350
|
+
|
|
336
351
|
if file is None:
|
|
337
352
|
file = "SVGimage.svg"
|
|
338
353
|
elif not isinstance(file, str):
|
|
339
354
|
raise ValueError("File name must be a string")
|
|
340
355
|
if not file.endswith(".svg"):
|
|
341
356
|
file += ".svg"
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
357
|
+
|
|
358
|
+
svg_string = self._generateSvgString(turtle)
|
|
359
|
+
|
|
360
|
+
# Escape backticks and fix any invalid escape sequences for safe JS template literals
|
|
361
|
+
svg_safe = svg_string.replace('`', r'\`').replace(r'\$', r'\\$')
|
|
362
|
+
|
|
363
|
+
# Build the JavaScript snippet cleanly to avoid syntax parsing color bleeding
|
|
364
|
+
js_lines = [
|
|
365
|
+
"(async () => {",
|
|
366
|
+
" try {",
|
|
367
|
+
f" const svgString = `{svg_safe}`;",
|
|
368
|
+
" const blob = new Blob([svgString], { type: 'image/svg+xml;charset=utf-8' });",
|
|
369
|
+
" const url = URL.createObjectURL(blob);",
|
|
370
|
+
" const downloadLink = document.createElement('a');",
|
|
371
|
+
" downloadLink.href = url;",
|
|
372
|
+
f" downloadLink.download = '{file}';",
|
|
373
|
+
" document.body.appendChild(downloadLink);",
|
|
374
|
+
" downloadLink.click();",
|
|
375
|
+
" document.body.removeChild(downloadLink);",
|
|
376
|
+
" URL.revokeObjectURL(url);",
|
|
377
|
+
" } catch (err) {",
|
|
378
|
+
" console.error('ColabTurtlePlus: Failed to download SVG:', err);",
|
|
379
|
+
" }",
|
|
380
|
+
"})();"
|
|
381
|
+
]
|
|
382
|
+
js_code = "\n".join(js_lines)
|
|
383
|
+
|
|
384
|
+
try:
|
|
385
|
+
# Execute directly in the browser layout thread
|
|
386
|
+
display(HTML(f"<script>{js_code}</script>"))
|
|
387
|
+
#print(f"Triggered local browser download for: {file}")
|
|
388
|
+
|
|
389
|
+
except Exception as e:
|
|
390
|
+
print(f"Error executing saveSVG: {e}")
|
|
391
|
+
|
|
392
|
+
# Download the image to the local computer as a PNG file using given filename. Set turtle=True to include turtle in svg output.
|
|
393
|
+
def savePNG(self, file="SVGimage.png", turtle=False):
|
|
394
|
+
"""
|
|
358
395
|
|
|
396
|
+
Args:
|
|
397
|
+
file: Filename as a string. If none is given, the default
|
|
398
|
+
filename "SVGimage.png" will be used.
|
|
399
|
+
turtle: (optional) a boolean that determines if the turtles
|
|
400
|
+
are included in the svg output
|
|
401
|
+
|
|
402
|
+
Converts the current SVG drawing to a PNG file entirely in the browser
|
|
403
|
+
and triggers an instant direct download onto the user's local computer.
|
|
404
|
+
Works flawlessly across Google Colab, JupyterLab, and JupyterLite kernels.
|
|
405
|
+
"""
|
|
406
|
+
if not isinstance(file, str):
|
|
407
|
+
raise ValueError("File name must be a string")
|
|
408
|
+
if not file.endswith(".png"):
|
|
409
|
+
file += ".png"
|
|
410
|
+
|
|
411
|
+
svg_string = self._generateSvgString(turtle)
|
|
412
|
+
|
|
413
|
+
# Escape quotes and clean up the string so it's safe for JavaScript template literals
|
|
414
|
+
svg_safe = svg_string.replace('`', r'\`').replace(r'\$', r'\\$')
|
|
415
|
+
|
|
416
|
+
# Build the JavaScript snippet cleanly
|
|
417
|
+
js_lines = [
|
|
418
|
+
"(async () => {",
|
|
419
|
+
" try {",
|
|
420
|
+
f" const svgString = `{svg_safe}`;",
|
|
421
|
+
" const blob = new Blob([svgString], { type: 'image/svg+xml;charset=utf-8' });",
|
|
422
|
+
" const url = URL.createObjectURL(blob);",
|
|
423
|
+
" const img = new Image();",
|
|
424
|
+
" await new Promise((resolve, reject) => {",
|
|
425
|
+
" img.onload = resolve;",
|
|
426
|
+
" img.onerror = reject;",
|
|
427
|
+
" img.src = url;",
|
|
428
|
+
" });",
|
|
429
|
+
" const canvas = document.createElement('canvas');",
|
|
430
|
+
" canvas.width = img.width || 800;",
|
|
431
|
+
" canvas.height = img.height || 600;",
|
|
432
|
+
" const ctx = canvas.getContext('2d');",
|
|
433
|
+
" ctx.drawImage(img, 0, 0);",
|
|
434
|
+
" URL.revokeObjectURL(url);",
|
|
435
|
+
" const pngDataUrl = canvas.toDataURL('image/png');",
|
|
436
|
+
" const downloadLink = document.createElement('a');",
|
|
437
|
+
" downloadLink.href = pngDataUrl;",
|
|
438
|
+
f" downloadLink.download = '{file}';",
|
|
439
|
+
" document.body.appendChild(downloadLink);",
|
|
440
|
+
" downloadLink.click();",
|
|
441
|
+
" document.body.removeChild(downloadLink);",
|
|
442
|
+
" } catch (err) {",
|
|
443
|
+
" console.error('ColabTurtlePlus: Failed to render/download PNG:', err);",
|
|
444
|
+
" }",
|
|
445
|
+
"})();"
|
|
446
|
+
]
|
|
447
|
+
js_code = "\n".join(js_lines)
|
|
448
|
+
|
|
449
|
+
try:
|
|
450
|
+
# This executes the script directly in the user's browser UI thread
|
|
451
|
+
# completely avoiding background kernel / web-worker sandboxes.
|
|
452
|
+
display(HTML(f"<script>{js_code}</script>"))
|
|
453
|
+
#print(f"Triggered local browser download for: {filename}")
|
|
454
|
+
|
|
455
|
+
except Exception as e:
|
|
456
|
+
print(f"Error executing savePNG: {e}")
|
|
457
|
+
|
|
458
|
+
# Used to make compound shapes
|
|
359
459
|
def register_shape(self, name, shape=None):
|
|
360
460
|
"""Adds a turtle shape to to the shape list.
|
|
361
461
|
|
|
@@ -366,7 +466,7 @@ class _Screen:
|
|
|
366
466
|
|
|
367
467
|
Installs the corresponding polygon shape or the corresponding compound shape.
|
|
368
468
|
If no points are given, the turtle shape will be blank.
|
|
369
|
-
Note: This version does NOT include shapes
|
|
469
|
+
Note: This version does NOT include shapes from image files.
|
|
370
470
|
"""
|
|
371
471
|
|
|
372
472
|
if not isinstance(name,str):
|
|
@@ -393,7 +493,7 @@ class _Screen:
|
|
|
393
493
|
name = name.lower()
|
|
394
494
|
VALID_TURTLE_SHAPES.add(name)
|
|
395
495
|
pointstr = " ".join(f"{x},{y}" for x, y in points)
|
|
396
|
-
shapeDict[name] = TURTLE_USER_SVG_TEMPLATE.replace("{points}",pointstr)
|
|
496
|
+
shapeDict[name] = TURTLE_USER_SVG_TEMPLATE.replace("{points}",pointstr)
|
|
397
497
|
else: #assume compound shape
|
|
398
498
|
tmp=TURTLE_COMPONENT_SVG_TEMPLATE.format(
|
|
399
499
|
component=shape._data,
|
|
@@ -500,7 +600,10 @@ class _Screen:
|
|
|
500
600
|
pcolor=turtle.pen_color,
|
|
501
601
|
pwidth=turtle.pen_width)
|
|
502
602
|
if turtle.is_filling:
|
|
503
|
-
turtle.
|
|
603
|
+
if turtle.is_pen_down:
|
|
604
|
+
turtle.svg_fill_string += """ L {x1} {y1} """.format(x1=new_pos[0],y1=new_pos[1])
|
|
605
|
+
else:
|
|
606
|
+
turtle.svg_fill_string += """ M {x1} {y1} """.format(x1=new_pos[0],y1=new_pos[1])
|
|
504
607
|
turtle.turtle_pos = new_pos
|
|
505
608
|
turtle.timeout = timeout_orig
|
|
506
609
|
if not turtle.animate: self._updateDrawing(turtle=turtle)
|
|
@@ -770,6 +873,26 @@ class _Screen:
|
|
|
770
873
|
self.xscale = self.yscale = 1
|
|
771
874
|
self.resetscreen()
|
|
772
875
|
|
|
876
|
+
# Set color mode (1 or 255). If mode is not given, current mode is returned.
|
|
877
|
+
def colormode(self, cmode=None):
|
|
878
|
+
"""Return the colormode or set it to 1.0 or 255.
|
|
879
|
+
|
|
880
|
+
Optional argument:
|
|
881
|
+
cmode -- one of the values 1.0 or 255
|
|
882
|
+
|
|
883
|
+
r, g, b values of colortriples have to be in range 0..cmode.
|
|
884
|
+
|
|
885
|
+
"""
|
|
886
|
+
if cmode is None:
|
|
887
|
+
return self._colormode
|
|
888
|
+
if cmode == 1.0:
|
|
889
|
+
self._colormode = float(cmode)
|
|
890
|
+
elif cmode == 255:
|
|
891
|
+
self._colormode = int(cmode)
|
|
892
|
+
else:
|
|
893
|
+
err = f'Colormode {cmode} is invalid. It must be 1.0 or 255.'
|
|
894
|
+
raise ValueError(err)
|
|
895
|
+
|
|
773
896
|
# Set up user-defined coordinate system using lower left and upper right corners.
|
|
774
897
|
# Screen is reset.
|
|
775
898
|
# if the xscale and yscale are not equal, the aspect ratio of the axes and the
|
|
@@ -844,33 +967,54 @@ class _Screen:
|
|
|
844
967
|
return True
|
|
845
968
|
return False
|
|
846
969
|
|
|
847
|
-
# Used to validate if a 3 tuple of integers is a valid RGB color
|
|
970
|
+
# Used to validate if a 3 tuple of integers or a 3 tuple of floats is a valid RGB color
|
|
848
971
|
def _validateColorTuple(self, color):
|
|
849
972
|
if len(color) != 3:
|
|
850
973
|
return False
|
|
851
|
-
if
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
974
|
+
if self._colormode == 255:
|
|
975
|
+
if not isinstance(color[0], int) or not isinstance(color[1], int) or not isinstance(color[2], int):
|
|
976
|
+
return False
|
|
977
|
+
if not 0 <= color[0] <= 255 or not 0 <= color[1] <= 255 or not 0 <= color[2] <= 255:
|
|
978
|
+
return False
|
|
979
|
+
return True
|
|
980
|
+
if self._colormode == 1.0:
|
|
981
|
+
if not isinstance(color[0], (float,int)) or not isinstance(color[1], (float,int)) or not isinstance(color[2], (float,int)):
|
|
982
|
+
return False
|
|
983
|
+
if not 0 <= color[0] <= 1 or not 0 <= color[1] <= 1 or not 0 <= color[2] <= 1:
|
|
984
|
+
return False
|
|
985
|
+
return True
|
|
856
986
|
|
|
857
|
-
# Helps validate color input to functions
|
|
858
|
-
def _processColor(self,color):
|
|
987
|
+
# Helps validate color input to functions
|
|
988
|
+
def _processColor(self, color):
|
|
859
989
|
if isinstance(color, str):
|
|
860
|
-
if color == "":
|
|
990
|
+
if color == "":
|
|
991
|
+
color = "none"
|
|
861
992
|
color = color.lower().strip()
|
|
862
|
-
if 'rgb' not in color:
|
|
993
|
+
if 'rgb' not in color:
|
|
994
|
+
color = color.replace(" ", "")
|
|
863
995
|
if not self._validateColorString(color):
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
996
|
+
# Use an f-string
|
|
997
|
+
err = f'Color {color} is invalid. It can be a known html color name, 3 or 6 digit hex string, or rgb string.'
|
|
998
|
+
err2 = "See https://www.w3schools.com/colors/colors_names.asp for known html color names."
|
|
999
|
+
raise ValueError(err + "\n" + err2)
|
|
1000
|
+
return color
|
|
867
1001
|
elif isinstance(color, tuple):
|
|
868
1002
|
if not self._validateColorTuple(color):
|
|
869
|
-
|
|
1003
|
+
# Use an f-string to safely convert the tuple to text
|
|
1004
|
+
endpt = self._colormode
|
|
1005
|
+
if self._colormode == 255:
|
|
1006
|
+
numtype = "integers"
|
|
1007
|
+
else:
|
|
1008
|
+
numtype = "floats"
|
|
1009
|
+
err = f'Color tuple {color} is invalid. It must be a tuple of three {numtype} in the interval [0,{endpt}]'
|
|
870
1010
|
raise ValueError(err)
|
|
871
|
-
|
|
1011
|
+
if self._colormode == 255:
|
|
1012
|
+
return 'rgb(' + str(color[0]) + ',' + str(color[1]) + ',' + str(color[2]) + ')'
|
|
1013
|
+
else:
|
|
1014
|
+
return 'rgb(' + str(int(255.0*color[0])) + ',' + str(int(255.0*color[1])) + ',' + str(int(255.0*color[2])) + ')'
|
|
872
1015
|
else:
|
|
873
|
-
|
|
1016
|
+
# Use an f-string to safely handle any unknown data type (e.g. None, int)
|
|
1017
|
+
err = f'The color parameter {color} must be a color string or a tuple'
|
|
874
1018
|
raise ValueError(err)
|
|
875
1019
|
|
|
876
1020
|
#----------------------------------------------------------------------------------------------
|
|
@@ -909,6 +1053,26 @@ class Shape(object):
|
|
|
909
1053
|
template = template.replace("{pcolor}",outline)
|
|
910
1054
|
self._data = tmp + template
|
|
911
1055
|
|
|
1056
|
+
def addgroupcomponent(self, group, fill=None, outline=None):
|
|
1057
|
+
"""Add SVG group commands to a shape of type compound.
|
|
1058
|
+
|
|
1059
|
+
Arguments: group is a group of svg commands
|
|
1060
|
+
fill is the fillcolor of the polygon,
|
|
1061
|
+
outline is the outline color of the polygon.
|
|
1062
|
+
"""
|
|
1063
|
+
|
|
1064
|
+
tmp = self._data
|
|
1065
|
+
template = GROUP_TEMPLATE.replace("{group}", group)
|
|
1066
|
+
if fill is not None:
|
|
1067
|
+
template = template.replace("{turtle_color}",fill)
|
|
1068
|
+
if outline is None:
|
|
1069
|
+
template = template.replace("{pcolor}",fill)
|
|
1070
|
+
else:
|
|
1071
|
+
template = template.replace("{pcolor}", outline)
|
|
1072
|
+
elif outline is not None:
|
|
1073
|
+
template = template.replace("{pcolor}",outline)
|
|
1074
|
+
self._data = tmp + template
|
|
1075
|
+
|
|
912
1076
|
def addellipsecomponent(self, center, radii, fill=None, outline=None):
|
|
913
1077
|
"""Add elliptical component to a shape of type compound.
|
|
914
1078
|
|
|
@@ -973,13 +1137,14 @@ class Shape(object):
|
|
|
973
1137
|
template = template.replace("{pcolor}",outline)
|
|
974
1138
|
self._data = tmp + template + "\n"
|
|
975
1139
|
|
|
1140
|
+
addComponent = addcomponent
|
|
976
1141
|
addEllipseComponet = addellipsecomponent
|
|
977
1142
|
addPathComponent = addpathcomponent
|
|
1143
|
+
addGroupComponent = addgroupcomponent
|
|
978
1144
|
#-------------------------------------------------------------
|
|
979
1145
|
|
|
980
1146
|
#----------------------------------------------------------------------------------------------
|
|
981
|
-
|
|
982
|
-
|
|
1147
|
+
|
|
983
1148
|
class RawTurtle:
|
|
984
1149
|
|
|
985
1150
|
def __init__(self, window=None):
|
|
@@ -1095,30 +1260,27 @@ class RawTurtle:
|
|
|
1095
1260
|
raise ValueError('Degrees must be a number.')
|
|
1096
1261
|
timeout_orig = self.timeout
|
|
1097
1262
|
deg = angle*self.angle_conv
|
|
1263
|
+
template = self.shapeDict[self.turtle_shape]
|
|
1098
1264
|
if self.turtle_speed == 0 or not self.animate:
|
|
1099
1265
|
self.turtle_degree = (self.turtle_degree + deg) % 360
|
|
1100
1266
|
self.screen._updateDrawing(turtle=self)
|
|
1101
|
-
elif self.turtle_shape != 'ring'
|
|
1267
|
+
elif self.turtle_shape != 'ring':
|
|
1102
1268
|
stretchfactor_orig = self.stretchfactor
|
|
1103
|
-
template = self.shapeDict[self.turtle_shape]
|
|
1104
|
-
tmp = """<animateTransform
|
|
1105
|
-
type="scale"
|
|
1106
|
-
from="{sx} {sy}" to="{sx} {sy}"
|
|
1107
|
-
begin="0s" dur="0.01s"
|
|
1108
|
-
repeatCount="1"
|
|
1109
|
-
additive="sum"
|
|
1110
|
-
fill="freeze"
|
|
1111
|
-
/><animateTransform attributeName="transform"
|
|
1269
|
+
template = self.shapeDict[self.turtle_shape]
|
|
1270
|
+
tmp = """<animateTransform attributeName="transform"
|
|
1112
1271
|
type="rotate"
|
|
1113
1272
|
from="0 0 0" to ="{extent} 0 0"
|
|
1114
|
-
begin="
|
|
1273
|
+
begin="0s" dur="{t}s"
|
|
1115
1274
|
repeatCount="1"
|
|
1116
1275
|
additive="sum"
|
|
1117
1276
|
fill="freeze"
|
|
1118
1277
|
/></g>""".format(extent=deg, t=self.timeout*abs(deg)/90, sx=self.stretchfactor[0], sy=self.stretchfactor[1])
|
|
1119
|
-
|
|
1278
|
+
|
|
1279
|
+
# Split from the right at most 1 time
|
|
1280
|
+
parts = template.rsplit("</g>", 1)
|
|
1281
|
+
# Join the pieces back together with tmp string replacing the last </g>
|
|
1282
|
+
newtemplate = tmp.join(parts)
|
|
1120
1283
|
self.shapeDict.update({self.turtle_shape:newtemplate})
|
|
1121
|
-
self.stretchfactor = 1,1
|
|
1122
1284
|
self.timeout = self.timeout*abs(deg)/90+0.001
|
|
1123
1285
|
self.screen._updateDrawing(self)
|
|
1124
1286
|
self.turtle_degree = (self.turtle_degree + deg) % 360
|
|
@@ -1126,7 +1288,7 @@ class RawTurtle:
|
|
|
1126
1288
|
self.shapeDict.update({self.turtle_shape:template})
|
|
1127
1289
|
self.stretchfactor = stretchfactor_orig
|
|
1128
1290
|
self.timeout = timeout_orig
|
|
1129
|
-
else: #_turtle_shape == 'ring'
|
|
1291
|
+
else: #_turtle_shape == 'ring'
|
|
1130
1292
|
turtle_degree_orig = self.turtle_degree
|
|
1131
1293
|
s = 1 if angle > 0 else -1
|
|
1132
1294
|
while s*deg > 0:
|
|
@@ -1380,26 +1542,52 @@ class RawTurtle:
|
|
|
1380
1542
|
setposition = goto # alias
|
|
1381
1543
|
|
|
1382
1544
|
# jump to a point without drawing or animation
|
|
1383
|
-
def jumpto(self,x,y=None):
|
|
1384
|
-
"""
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1545
|
+
def jumpto(self, x=None, y=None, fill_gap: bool = False) -> None:
|
|
1546
|
+
"""Instantly move turtle to an absolute position.
|
|
1547
|
+
|
|
1548
|
+
Arguments:
|
|
1549
|
+
x -- a number or None
|
|
1550
|
+
y -- a number None
|
|
1551
|
+
fill_gap -- a boolean This argument must be specified by name.
|
|
1552
|
+
|
|
1553
|
+
call: teleport(x, y) # two coordinates
|
|
1554
|
+
--or: teleport(x) # jump to to x position, keeping y as is
|
|
1555
|
+
--or: teleport(y=y) # jump to to y position, keeping x as is
|
|
1556
|
+
--or: teleport(x, y, fill_gap=True)
|
|
1557
|
+
# jump but fill the gap in between
|
|
1558
|
+
|
|
1559
|
+
Move turtle to an absolute position. Unlike goto(x, y), a line will not
|
|
1560
|
+
be drawn. The turtle's orientation does not change. If currently
|
|
1561
|
+
filling, the regions(s) jumped from will be filled after leaving,
|
|
1562
|
+
and filling will begin again after jumping. This can be disabled
|
|
1563
|
+
with fill_gap=True which will do all filling upon the end_fill(). Because the
|
|
1564
|
+
filling is done via SVG commands, this might be different than with Python's teleport
|
|
1565
|
+
function.
|
|
1391
1566
|
"""
|
|
1392
1567
|
if isinstance(x, tuple) and y is None:
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1568
|
+
if len(x) != 2:
|
|
1569
|
+
raise ValueError('The tuple argument must be of length 2.')
|
|
1570
|
+
y = x[1]
|
|
1571
|
+
x = x[0]
|
|
1572
|
+
pendown = self.isdown()
|
|
1573
|
+
was_filling = self.filling()
|
|
1574
|
+
# if pendown:
|
|
1575
|
+
# self.pen(pendown=False)
|
|
1576
|
+
if was_filling and not fill_gap:
|
|
1577
|
+
self.end_fill()
|
|
1578
|
+
if pendown:
|
|
1579
|
+
self.pen(pendown=False)
|
|
1580
|
+
new_x = x if x is not None else self.getx()
|
|
1581
|
+
new_y = y if y is not None else self.gety()
|
|
1397
1582
|
animate_temp = self.animate
|
|
1398
1583
|
self.penup()
|
|
1399
1584
|
self.animationOff()
|
|
1400
|
-
self.goto(
|
|
1585
|
+
self.goto(new_x,new_y)
|
|
1401
1586
|
self.animate = animate_temp
|
|
1402
|
-
self.pendown
|
|
1587
|
+
self.pen(pendown=pendown)
|
|
1588
|
+
if was_filling and not fill_gap:
|
|
1589
|
+
self.begin_fill()
|
|
1590
|
+
teleport = jumpto #alias
|
|
1403
1591
|
|
|
1404
1592
|
# Move the turtle to a designated 'x' x-coordinate, y-coordinate stays the same
|
|
1405
1593
|
def setx(self, x):
|
|
@@ -1538,7 +1726,8 @@ class RawTurtle:
|
|
|
1538
1726
|
return self.turtle_speed
|
|
1539
1727
|
speeds = {'fastest':13, 'fast':10, 'normal':5, 'slow':3, 'slowest':1}
|
|
1540
1728
|
if speed in speeds:
|
|
1541
|
-
self.turtle_speed = speeds[speed]
|
|
1729
|
+
#self.turtle_speed = speeds[speed]
|
|
1730
|
+
speed = speeds[speed]
|
|
1542
1731
|
elif not isinstance(speed,(int,float)):
|
|
1543
1732
|
raise ValueError("speed should be a number between 0 and 13")
|
|
1544
1733
|
self.turtle_speed = speed
|
|
@@ -2335,7 +2524,7 @@ class RawTurtle:
|
|
|
2335
2524
|
ColabTurtle version. Use 'turtle2' for the polygonal turtle shape form
|
|
2336
2525
|
turtle.py. The circle shape from the original ColabTurtle was renamed 'ring'.
|
|
2337
2526
|
|
|
2338
|
-
Use register_shape (alias addshape) to create
|
|
2527
|
+
Use register_shape (alias addshape) to create other polygonal or compound shapes with a chosen name.
|
|
2339
2528
|
"""
|
|
2340
2529
|
|
|
2341
2530
|
if name is None:
|
|
@@ -2584,15 +2773,16 @@ def getcolor(n):
|
|
|
2584
2773
|
raise ValueError("color index must be an integer between 0 and 139")
|
|
2585
2774
|
n = int(round(n))
|
|
2586
2775
|
if (n < 0) or (n > 139):
|
|
2587
|
-
raise
|
|
2776
|
+
raise ValueError("color index must be an integer between 0 and 139")
|
|
2588
2777
|
return VALID_COLORS[n]
|
|
2589
2778
|
|
|
2590
2779
|
|
|
2591
|
-
_tg_screen_functions = ['addshape', 'bgcolor', 'clearscreen', 'drawline', 'hideborder',
|
|
2592
|
-
'initializescreen','initializeTurtle', 'showSVG', 'saveSVG',
|
|
2780
|
+
_tg_screen_functions = ['addshape', 'bgcolor', 'clearscreen', 'colormode', 'drawline', 'hideborder',
|
|
2781
|
+
'initializescreen','initializeTurtle', 'showSVG', 'saveSVG', 'savePNG' , 'line', 'mode', 'register_shape', 'resetscreen', 'setup',
|
|
2593
2782
|
'setworldcoordinates', 'showborder', 'turtles', 'window_width', 'window_height' ]
|
|
2594
2783
|
|
|
2595
|
-
_tg_shape_functions = ['addcomponent', 'addellipsecomponent', 'addpathcomponent'
|
|
2784
|
+
_tg_shape_functions = ['addcomponent', 'addellipsecomponent', 'addpathcomponent', 'addgroupcomponent',
|
|
2785
|
+
'addComponent', 'addEllipseComponent', 'addPathComponent', 'addGroupComponent']
|
|
2596
2786
|
|
|
2597
2787
|
_tg_turtle_functions = ['animationOff', 'animationOn', 'bk', 'back', 'backward', 'begin_fill',
|
|
2598
2788
|
'circle', 'clear', 'clearstamp', 'clearstamps', 'color', 'degrees', 'delay', 'distance', 'done',
|
|
@@ -2601,7 +2791,7 @@ _tg_turtle_functions = ['animationOff', 'animationOn', 'bk', 'back', 'backward',
|
|
|
2601
2791
|
'isvisible', 'jumpto', 'left', 'lt', 'pd', 'pen', 'pencolor', 'pensize', 'pendown', 'penup', 'pos',
|
|
2602
2792
|
'position', 'pu', 'radians', 'regularPolygon', 'reset', 'right', 'rt', 'setheading', 'seth',
|
|
2603
2793
|
'setpos', 'setposition', 'settiltangle', 'setx','sety', 'shape', 'shapesize', 'shearfactor',
|
|
2604
|
-
'showturtle', 'speed', 'st', 'stamp', 'tilt', 'tiltangle', 'turtlesize', 'towards', 'up', 'update',
|
|
2794
|
+
'showturtle', 'speed', 'st', 'stamp', 'teleport', 'tilt', 'tiltangle', 'turtlesize', 'towards', 'up', 'update',
|
|
2605
2795
|
'width', 'write', 'xcor', 'ycor' ]
|
|
2606
2796
|
|
|
2607
2797
|
def _getmethparlist(ob):
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: ColabTurtlePlus
|
|
3
|
-
Version: 2.1
|
|
3
|
+
Version: 2.2.1
|
|
4
4
|
Summary: An HTML based Turtle implementation with classes for Google Colab and Jupyter Labs
|
|
5
5
|
Home-page: https://github.com/mathriddle/ColabTurtlePlus
|
|
6
6
|
Author: Larry Riddle
|
|
@@ -41,6 +41,15 @@ Sept. 2026: Version 2.1.1 allows use of addcomponent() to add a polygon to a com
|
|
|
41
41
|
|
|
42
42
|
Sept. 2026: Version 2.1.2. Bug fix when multiple turtles have the same shape.
|
|
43
43
|
|
|
44
|
+
Oct. 2026: Version 2.2.0. Added colormode and modified jumpto to mimic teleport from Python's turtle module.
|
|
45
|
+
|
|
46
|
+
Nov. 2026: Version 2.2.1.
|
|
47
|
+
New function addgroupcomponent() to add an svg group to a shape compound.
|
|
48
|
+
The image (with or without the turtle(s)) can now be saved as a PNG file to the local computer using the savePNG() function.
|
|
49
|
+
Turtle shapes that are scaled differently in x and y directions are now rotated smoothly in right/left turns.
|
|
50
|
+
The function saveSVG() will now bring up a download dialog box to save the file to the local computer rather than to the
|
|
51
|
+
Colab or Jupyter sidebar file browser.
|
|
52
|
+
|
|
44
53
|
Installation
|
|
45
54
|
----
|
|
46
55
|
Create an empty code cell and type:
|
|
@@ -49,8 +58,6 @@ Create an empty code cell and type:
|
|
|
49
58
|
|
|
50
59
|
Run the code cell to install the library.
|
|
51
60
|
|
|
52
|
-
**Note:** The previous non-class version of ColabTurtlePlus can be installed using !pip install ColabTurtlePlus==1.5.
|
|
53
|
-
|
|
54
61
|
Usage
|
|
55
62
|
----
|
|
56
63
|
In a code cell, import the module using
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
ColabTurtlePlus/Turtle.py,sha256=lRn2YfrYczjHfNDTU7Mdsw7hnppcVKTd6r6EUoUlZ70,127853
|
|
2
|
+
ColabTurtlePlus/__init__.py,sha256=H4DUZY1qO5lAvSUORBOSTudzIkEy82VH7wqQfzfr308,120
|
|
3
|
+
colabturtleplus-2.2.1.dist-info/licenses/LICENSE,sha256=LkS7k6XvOjkN_euuN6CV4vTHjEIhDuAkjM-lNz5e-KE,1069
|
|
4
|
+
colabturtleplus-2.2.1.dist-info/METADATA,sha256=9oE35w6Vkfhm2Rj_ZVzBn_X8agWLDXCAndKA_o_A2RE,11911
|
|
5
|
+
colabturtleplus-2.2.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
6
|
+
colabturtleplus-2.2.1.dist-info/top_level.txt,sha256=H3fhP1ddouEUeAF7kXK2QbPBMzN7fDCLKSP8G00JcgA,16
|
|
7
|
+
colabturtleplus-2.2.1.dist-info/RECORD,,
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
ColabTurtlePlus/Turtle.py,sha256=qxMw9kWHyODNw1iMqd0mRPd6T_xMYocMtZ_goj6ySbo,118940
|
|
2
|
-
ColabTurtlePlus/__init__.py,sha256=H4DUZY1qO5lAvSUORBOSTudzIkEy82VH7wqQfzfr308,120
|
|
3
|
-
colabturtleplus-2.1.2.dist-info/licenses/LICENSE,sha256=LkS7k6XvOjkN_euuN6CV4vTHjEIhDuAkjM-lNz5e-KE,1069
|
|
4
|
-
colabturtleplus-2.1.2.dist-info/METADATA,sha256=l-YcsdYKRy4wZ0JLpHs0yDq4-7FicWWZgjiIfNC-HSg,11425
|
|
5
|
-
colabturtleplus-2.1.2.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
6
|
-
colabturtleplus-2.1.2.dist-info/top_level.txt,sha256=H3fhP1ddouEUeAF7kXK2QbPBMzN7fDCLKSP8G00JcgA,16
|
|
7
|
-
colabturtleplus-2.1.2.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|