generated from CoderDojoTrento/turtle-pyscript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathturtleps.py
1580 lines (1218 loc) · 48.4 KB
/
turtleps.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# ************ ATTENZIONE! ********************
# ************ _NON_ SCRIVERE IN QUESTO FILE !! ********************
#
from pyodide.ffi.wrappers import add_event_listener
import uuid
"""
Aug 2024:
TURTLE MODULE TAKEN FROM transcrypt (apache licence)
https://github.com/TranscryptOrg/Transcrypt/blob/master/transcrypt/modules/turtle/__init__.py
NOTE: YOU DON'T NEED TRANSCRIPT, WE EXECUTE IT IN PYSCRIPT
"""
# not importing anything from turtle as it's disabled in pyodide
class TurtleGraphicsError(Exception):
"""Some TurtleGraphics Error
"""
pass
class Vec2D(tuple):
"""A 2 dimensional vector class, used as a helper class
for implementing turtle graphics.
May be useful for turtle graphics programs also.
Derived from tuple, so a vector is a tuple!
Provides (for a, b vectors, k number):
a+b vector addition
a-b vector subtraction
a*b inner product
k*a and a*k multiplication with scalar
|a| absolute value of a
a.rotate(angle) rotation
"""
def __new__(cls, x, y):
return tuple.__new__(cls, (x, y))
def __add__(self, other):
return Vec2D(self[0]+other[0], self[1]+other[1])
def __mul__(self, other):
if isinstance(other, Vec2D):
return self[0]*other[0]+self[1]*other[1]
return Vec2D(self[0]*other, self[1]*other)
def __rmul__(self, other):
if isinstance(other, int) or isinstance(other, float):
return Vec2D(self[0]*other, self[1]*other)
return NotImplemented
def __sub__(self, other):
return Vec2D(self[0]-other[0], self[1]-other[1])
def __neg__(self):
return Vec2D(-self[0], -self[1])
def __abs__(self):
return math.hypot(*self)
def rotate(self, angle):
"""rotate self counterclockwise by angle
"""
perp = Vec2D(-self[1], self[0])
angle = math.radians(angle)
c, s = math.cos(angle), math.sin(angle)
return Vec2D(self[0]*c+perp[0]*s, self[1]*c+perp[1]*s)
def __getnewargs__(self):
return (self[0], self[1])
def __repr__(self):
return "(%.2f,%.2f)" % self
def _parse_color_args(*args):
if len(args) == 1:
if isinstance(args[0], tuple):
svg_color = f"rgb({','.join([str(a) for a in args[0]])})"
elif isinstance(args[0], str):
svg_color = args[0]
else:
raise TurtleGraphicsError(f"Unrecognized color format: {args[0]}")
elif len(args) == 3:
svg_color = f"rgb({','.join([str(a) for a in args])})"
else:
raise TurtleGraphicsError(f"Unrecognized color format: {args}")
return svg_color
from js import (
document,
window
)
#__pragma__ ('skip')
#document = Math = setInterval = clearInterval = 0
#__pragma__ ('noskip')
import math
_debugging = False
#_debugging = True
#_tracing = True
_tracing = False
def _debug(*args):
if _debugging:
print("DEBUG:",*args)
def _trace(*args):
if _tracing:
print("TRACE:",*args)
def _info(*args):
print("INFO:", *args)
def _warn(*args):
print("WARN:", *args)
#def abs (vec2D):
# return Math.sqrt (vec2D [0] * vec2D [0] + vec2D [1] * vec2D [1])
_CFG = {"width" : 400, # 0.5, # Screen
"height" : 400, # 0.75,
"canvwidth" : 400,
"canvheight": 300,
"leftright": None,
"topbottom": None,
"mode": "standard", # TurtleScreen
"colormode": 1.0,
"delay": 10,
"undobuffersize": 1000, # RawTurtle
"shape": "classic",
"pencolor" : "black",
"fillcolor" : "black",
"resizemode" : "noresize", # CDTN: why? I would expect "user"
"visible" : True,
"language": "english", # docstrings
"exampleturtle": "turtle",
"examplescreen": "screen",
"title": "Python Turtle Graphics",
"using_IDLE": False
}
_ns = 'http://www.w3.org/2000/svg'
_svg = document.createElementNS (_ns, 'svg')
_svg.style.setProperty('border-style','solid')
_svg.style.setProperty('border-color','lightgrey')
_defs = document.createElementNS (_ns, 'defs')
_defs.setAttributeNS(None, 'id', 'defs')
_svg.appendChild(_defs)
# so we can at least define z-order of turtles
_svg_sprites = document.createElementNS (_ns, 'g')
_svg_sprites.setAttribute('class', 'sprites')
_svg_painting = document.createElementNS (_ns, 'g')
_svg_painting.setAttribute('class', 'painting')
_svg.appendChild(_svg_painting)
_svg.appendChild(_svg_sprites)
_defaultElement = document.getElementById ('__turtlegraph__')
if not _defaultElement:
_defaultElement = document.body
_defaultElement.appendChild (_svg)
""" CDTN: The _svg container
"""
class Shape(object):
"""Data structure modeling shapes.
attribute _type is one of "polygon", "image", "compound"
attribute _data is - depending on _type a poygon-tuple,
an image or a list constructed using the addcomponent method.
CDTN: doesn't seem really useful, in the original CPython implementation doesn't
have public attributes nor methods to retrieve stuff.
original _data che be in many forms, from concrete bitmap images to tuples
Decision: will store in ._data nothing
will store in .svg an unlinked svg element
"""
def __init__(self, type_, data=None):
self._type = type_
if type_ == "polygon":
if isinstance(data, list):
data = tuple(data)
"""
<polygon points="100,100 150,25 150,75 200,0" fill="none" stroke="black" />
"""
poly = document.createElementNS(_ns, 'polygon')
points_str = ' '.join([','.join([str(el) for el in t]) for t in data])
poly.setAttributeNS(None, 'points', points_str)
self.svg = poly
# leaving default fill...
elif type_ == "image":
if not data:
raise ValueError("CDTN: Missing image data!")
img = document.createElementNS(_ns, 'image')
#img.setAttributeNS(None, 'x', 0)
#img.setAttributeNS(None, 'y', 0)
#img.setAttributeNS(None, 'width', 20)
#img.setAttributeNS(None, 'height', 20)
#img.setAttributeNS(None, 'xlink:href', name) # doesn't like it
img.setAttributeNS(None, 'href', data)
self.svg = img
#CDTN commented, expect svg node
#if isinstance(data, str):
#if data.lower().endswith(".gif") and os.path.isfile(data):
# data = TurtleScreen._image(data)
# else data assumed to be PhotoImage # CDTN ??
elif type_ == "compound":
#data = [] CDTN
self.svg = document.createElementNS(_ns, 'g') # group
else:
raise TurtleGraphicsError("There is no shape type %s" % type_)
def get_svg_image_size(self):
"""
"""
if self._type != "image":
raise CDTNException("Other types are currently not supported")
_debug(f"{window.getComputedStyle(self.svg).getPropertyValue('width')=}") # '50.3px'
_debug(f"{window.getComputedStyle(self.svg).getPropertyValue('height')=}") # '50.5px'
cs = window.getComputedStyle(self.svg)
return(float(cs.getPropertyValue('width')[:-2]), float(cs.getPropertyValue('height')[:-2]))
#_debug(f"{self.svg_shape.getBBox()=}")
#_debug(f"{self.svg_shape.getBBox()["width"]=}") # wtf TypeError: 'pyodide.ffi.JsProxy' object is not subscriptable
#_debug(f"{self.svg_shape.getBBox()[2]=}") # no
#_debug(f'{self.svg_shape.getBBox().getProperty("width")=}') # no
#_debug(f'{self.svg_shape.getBBox().getAttribute("width")=}') # no
def addcomponent(self, poly, fill, outline=None):
"""Add component to a shape of type compound.
Arguments: poly is a polygon, i. e. a tuple of number pairs.
fill is the fillcolor of the component,
outline is the outline color of the component.
call (for a Shapeobject namend s):
-- s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue")
Example:
>>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
>>> s = Shape("compound")
>>> s.addcomponent(poly, "red", "blue")
>>> # .. add more components and then use register_shape()
"""
if self._type != "compound":
raise TurtleGraphicsError("Cannot add component to %s Shape"
% self._type)
if outline is None:
outline = fill
poly = document.createElementNS(_ns, 'polygon')
points_str = ' '.join([','.join(t) for t in data])
poly.setAttributeNS(None, 'points', points_str)
if fill:
poly.setAttributeNS(None, 'fill', fill)
if outline:
poly.setAttributeNS(None, 'outline', outline)
self._data.appendChild(poly)
def Screen():
"""Return the singleton screen object.
If none exists at the moment, create a new one and return it,
else return the existing one."""
if Turtle._screen is None:
_debug("No default screen found, creating one..")
Turtle._screen = _Screen()
return Turtle._screen
class _Screen:
def __init__(self):
_debug("CDTN: Initializing screen...")
self.svg = _svg
self.svg_sprites = _svg_sprites
self.svg_painting = _svg_painting
self._bgpicname = ''
self._timer = None
self._turtles = []
self._shapes = {}
self._width = _CFG["width"]
self._height = _CFG["height"]
self._offset = [_CFG["width"]//2, _CFG["height"]//2]
#self.canvwidth = w
#self.canvheight = h
#self.xscale = self.yscale = 1.0
shapes = {
"arrow" : Shape("polygon", ((-10,0), (10,0), (0,10))),
"turtle" : Shape("polygon", ((0,16), (-2,14), (-1,10), (-4,7),
(-7,9), (-9,8), (-6,5), (-7,1), (-5,-3), (-8,-6),
(-6,-8), (-4,-5), (0,-7), (4,-5), (6,-8), (8,-6),
(5,-3), (7,1), (6,5), (9,8), (7,9), (4,7), (1,10),
(2,14))),
"circle" : Shape("polygon", ((10,0), (9.51,3.09), (8.09,5.88),
(5.88,8.09), (3.09,9.51), (0,10), (-3.09,9.51),
(-5.88,8.09), (-8.09,5.88), (-9.51,3.09), (-10,0),
(-9.51,-3.09), (-8.09,-5.88), (-5.88,-8.09),
(-3.09,-9.51), (-0.00,-10.00), (3.09,-9.51),
(5.88,-8.09), (8.09,-5.88), (9.51,-3.09))),
"square" : Shape("polygon", ((10,-10), (10,10), (-10,10),
(-10,-10))),
"triangle" : Shape("polygon", ((10,-5.77), (0,11.55),
(-10,-5.77))),
"classic": Shape("polygon", ((0,0),(-5,-9),(0,-7),(5,-9))),
#CDTN not supported "blank" : Shape("image", self._blankimage())
}
for name, shape in shapes.items():
self.register_shape(name, shape)
self._bgpics = {"nopic" : ""}
#self._mode = mode
#self._delayvalue = delay
#self._colormode = _CFG["colormode"]
#self._keys = []
self.clear()
#if sys.platform == 'darwin':
# Force Turtle window to the front on OS X. This is needed because
# the Turtle window will show behind the Terminal window when you
# start the demo from the command line.
# rootwindow = cv.winfo_toplevel()
# rootwindow.call('wm', 'attributes', '.', '-topmost', '1')
# rootwindow.call('wm', 'attributes', '.', '-topmost', '0')
def _right_size(myself=None):
self.update()
self.setup()
window.onresize = _right_size
_right_size()
self._defaultTurtle = Turtle(screen=self)
def getshapes(self):
"""Return a list of names of all currently available turtle shapes.
No argument.
Example (for a TurtleScreen instance named screen):
>>> screen.getshapes()
['arrow', 'blank', 'circle', ... , 'turtle']
"""
return sorted(self._shapes.keys())
def clear(self):
"""Delete all drawings and all turtles from the TurtleScreen.
No argument.
Reset empty TurtleScreen to its initial state: white background,
no backgroundimage, no eventbindings and tracing on.
Example (for a TurtleScreen instance named screen):
>>> screen.clear()
Note: this method is not available as function.
"""
_debug("Screen.clear()")
#self._delayvalue = _CFG["delay"]
#self._colormode = _CFG["colormode"]
#self._delete("all")
#self._bgpic = self._createimage("")
#self._bgpicname = "nopic"
#self._tracing = 1
#self._updatecounter = 0
#self._turtles = []
self.bgcolor("white")
self.svg_sprites.replaceChildren()
self.svg_painting.replaceChildren()
#for btn in 1, 2, 3:
# self.onclick(None, btn)
#self.onkeypress(None)
#for key in self._keys[:]:
# self.onkey(None, key)
# self.onkeypress(None, key)
#Turtle._pen = None
def setup(self, width=_CFG["width"], height=_CFG["height"]):
#self.svg.setAttribute('viewBox', f'200 200 {width} {height}')
self._width = width
self._height = height
self.update()
def update(self):
"""Perform a TurtleScreen update.
"""
#self._width = _defaultElement.offsetWidth
#self._height = _defaultElement.offsetHeight
self._offset = [self._width // 2, self._height // 2]
self.svg.setAttribute('width', self._width)
self.svg.setAttribute('height', self._height)
#tracing = self._tracing
#self._tracing = True
#for t in self.turtles():
# t._update_data()
# t._drawturtle()
#self._tracing = tracing
#self._update()
pass
def register_shape(self, name, shape=None):
"""Adds a turtle shape to TurtleScreen's shapelist.
Arguments:
(1) name is the name of a gif-file and shape is None.
Installs the corresponding image shape.
!! CDTN: images in our implementation do actually turn to heading orientation
(2) name is an arbitrary string and shape is a tuple
of pairs of coordinates. Installs the corresponding
polygon shape
(3) name is an arbitrary string and shape is a
(compound) Shape object. Installs the corresponding
compound shape.
To use a shape, you have to issue the command shape(shapename).
call: register_shape("turtle.gif")
--or: register_shape("tri", ((0,0), (10,10), (-10,10)))
Example (for a TurtleScreen instance named screen):
>>> screen.register_shape("triangle", ((5,-3),(0,5),(-5,-3)))
"""
_debug(f"CDTN: Registering shape: name: {name} shape:{shape}")
if name in self._shapes:
_warn(f"Screen.register_shape(): trying to register the same shape twice: {name} ")
defs = self.svg.getElementById("defs")
if shape is None:
the_shape = Shape("image", name)
elif isinstance(shape, tuple):
the_shape = Shape("polygon", shape)
else:
the_shape = shape
# else shape assumed to be Shape-instance
# TODO sanitize?
the_shape.svg.setAttributeNS(None, 'id', name)
defs.appendChild(the_shape.svg)
self._shapes[name] = the_shape
def bgpic(self, picname=None):
"""Set background image or return name of current backgroundimage.
Optional argument:
picname -- a string, name of a gif-file or "nopic".
If picname is a filename, set the corresponding image as background.
If picname is "nopic", delete backgroundimage, if present.
If picname is None, return the filename of the current backgroundimage.
Example (for a TurtleScreen instance named screen):
>>> screen.bgpic()
'nopic'
>>> screen.bgpic("landscape.gif")
>>> screen.bgpic()
'landscape.gif'
"""
if picname is None:
return self._bgpicname
self._bgpicname = picname
_debug(f"Setting background-image {picname}")
self.svg.style.setProperty('background-image', f'url({picname})')
def _window_size(self):
""" Return the width and height of the turtle window.
"""
#width = self.cv.winfo_width()
#if width <= 1: # the window isn't managed by a geometry manager
# width = self.cv['width']
#height = self.cv.winfo_height()
#if height <= 1: # the window isn't managed by a geometry manager
# height = self.cv['height']
bcr = self.svg.getBoundingClientRect()
return bcr['width'], bcr['height']
def window_width(self):
""" Return the width of the turtle window.
Example (for a TurtleScreen instance named screen):
>>> screen.window_width()
640
"""
return self._window_size()[0]
def window_height(self):
""" Return the height of the turtle window.
Example (for a TurtleScreen instance named screen):
>>> screen.window_height()
480
"""
return self._window_size()[1]
def _iscolorstring(self, color):
"""Check if the string color is a legal SVG color string.
"""
#CDTN TODO Too optimistic
return True
def tracer(self, n=None, delay=None):
"""Turns turtle animation on/off and set delay for update drawings.
Optional arguments:
n -- nonnegative integer
delay -- nonnegative integer
If n is given, only each n-th regular screen update is really performed.
(Can be used to accelerate the drawing of complex graphics.)
Second arguments sets delay value (see RawTurtle.delay())
Example (for a TurtleScreen instance named screen):
>>> screen.tracer(8, 25)
>>> dist = 2
>>> for i in range(200):
... fd(dist)
... rt(90)
... dist += 2
"""
_warn("Turtle.tracer() is currently *NOT IMPLEMENTED*")
"""
if n is None:
return self._tracing
self._tracing = int(n)
self._updatecounter = 0
if delay is not None:
self._delayvalue = int(delay)
if self._tracing:
self.update()
"""
def bgcolor(self, *args):
if len(args) == 0:
return self._bgcolor
if len(args) == 0:
return self.svg.style["background-color"]
else:
s = _parse_color_args(*args)
self.svg.style.setProperty("background-color", s)
def reset(self):
if self._timer:
clearTimeout(self._timer) # js
self.bgcolor('white')
for turtle in self._turtles:
turtle.reset()
turtle._flush()
def clear(self):
for turtle in self._turtles:
turtle.clear()
def ontimer(fun, t = 0):
global _timer
_timer = setTimeout(fun, t) # js
class Turtle:
_screen = None
def __init__(self,
screen=None,
shape=_CFG["shape"], # NOTE: this is meant to be an id
visible=_CFG["visible"]):
_debug("A new Turtle is born!")
if not screen:
screen = Turtle._screen
self.screen = screen
self.screen._turtles.append(self)
self._position = [0,0]
self._stretchfactor = (1., 1.)
self._paths = [] # TODO rename, it hosts anything drawn by the turtle
self._track = []
self._pencolor = _CFG["pencolor"]
self._fillcolor = _CFG["fillcolor"]
self._pensize = 1
self._shown = True
self._fill = False
self._heading = 0.0
self._tilt = 0
#shape_node = document.getElementById(shape)
#cloned_shape_node = shape_node.cloneNode(True)
#self.screen.svg.appendChild(cloned_shape_node)
group_node = document.createElementNS (_ns, 'g')
use_node = document.createElementNS (_ns, 'use')
group_node.setAttribute('id', f"sprite-{id(self)}")
"""
<use href="#tree" x="50" y="100" />
"""
self.svg = group_node
self.svg_shape = use_node
group_node.appendChild(use_node)
self.screen.svg_sprites.appendChild(group_node)
_debug("turtle was appended to screen.svg_sprites")
self.shape(shape)
self.reset()
_trace(f"{self._heading=}")
def _create_track(self):
_debug("Creating new _track_svg_path")
self._track = [] # Need to make track explicitly because
# _track should start with a move command
self._track.append('{} {} {}'.format(
'M',
self._position[0] + self.screen._offset[0],
self.screen._offset[1] - self._position[1])
)
tsp = document.createElementNS(_ns, 'path')
tsp.setAttribute('fill', 'none')
tsp.setAttribute('fill-rule', 'nonzero')
self.screen.svg_painting.appendChild(tsp)
self._paths.append(tsp)
self._track_svg_path = tsp
def reset(self):
self._heading = 0.0
self._tilt = 0.0
self._stretchfactor = (1., 1.)
self.down ()
self.color ('black', 'black')
self.pensize (1)
self.home() # Makes a position but needs a track to put in
self.clear() # Makes a track but needs a position to initialize it with
def clear(self):
_debug("Clearing turtle...")
for path in self._paths:
self.screen.svg_painting.removeChild(path)
self._paths = []
self._create_track()
self._moveto(self._position)
def _flush(self):
_trace('Flush:', self._track)
if len(self._track) > 1:
tsp = self._track_svg_path
ts = ' '.join (self._track)
ds = tsp.getAttribute('d')
_debug(f"{ds=}")
if ds:
ts = f"{ds} {ts}"
_debug(f"{ts=}")
tsp.setAttribute('d', ts)
tsp.setAttribute('stroke', self._pencolor if self._pencolor != None else 'none')
tsp.setAttribute('stroke-width', self._pensize)
#def done(self):
# self._flush()
def pensize(self, width=None):
if width == None:
return self._pensize
else:
self._pensize = width
def color(self, pencolor, fillcolor = None):
self.pencolor(pencolor)
if fillcolor is None:
self.fillcolor(pencolor)
else:
self.fillcolor(fillcolor)
def _colorstr(self, color):
"""Return color string corresponding to args.
Argument may be a string or a tuple of three
numbers corresponding to actual colormode,
i.e. in the range 0<=n<=colormode.
If the argument doesn't represent a color,
an error is raised.
"""
if len(color) == 1:
color = color[0]
if isinstance(color, str):
if self._iscolorstring(color) or color == "":
return color
else:
raise TurtleGraphicsError("bad color string: %s" % str(color))
try:
r, g, b = color
except (TypeError, ValueError):
raise TurtleGraphicsError("bad color arguments: %s" % str(color))
if self._colormode == 1.0:
r, g, b = [round(255.0*x) for x in (r, g, b)]
if not ((0 <= r <= 255) and (0 <= g <= 255) and (0 <= b <= 255)):
raise TurtleGraphicsError("bad color sequence: %s" % str(color))
return "#%02x%02x%02x" % (r, g, b)
def _color(self, cstr):
if not cstr.startswith("#"):
return cstr
if len(cstr) == 7:
cl = [int(cstr[i:i+2], 16) for i in (1, 3, 5)]
elif len(cstr) == 4:
cl = [16*int(cstr[h], 16) for h in cstr[1:]]
else:
raise TurtleGraphicsError("bad colorstring: %s" % cstr)
return tuple(c * self._colormode/255 for c in cl)
def pencolor(self, *args):
if len(args) == 0:
return self._pencolor
else:
s = _parse_color_args(*args)
self._pencolor = s
self.svg.style.setProperty("background-color", s)
self._create_track() # CDTN TODO hack so we can show path with segments of different colors
def fillcolor(self, *args):
if len(args) == 0:
return self._fillcolor
else:
s = _parse_color_args(*args)
self._fillcolor = s
#TODO change some svg property??
def home(self):
self._moveto(0, 0)
def position(self):
#TODO CDTN self._position should natively be a Vec2D
return Vec2D(self._position[0], self._position[1])
def pos(self):
return self.position()
def xcor(self):
return self._position[0]
def ycor(self):
return self._position[1]
def distance(self, x, y = None):
if y is None:
other = x
else:
other = [x, y]
dX = other[0] - self._position[0]
dY = other[1] - self._position[1]
return math.sqrt (dX * dX + dY * dY)
def penup(self):
self._down = False
def pendown(self):
self._down = True
def isdown(self):
return self._down
def goto(self, x, y = None):
if y is None:
self._position = x
else:
self._position = [x, y]
if self._down:
_trace("goto: self._down")
self._track.append('{} {} {}'.format(
'L' if self._down else 'M',
self._position[0] + self.screen._offset[0],
self.screen._offset[1] - self._position[1])
)
self._flush()
self._update_transform()
def _moveto(self, x, y = None):
wasdown = self.isdown()
self.up()
self.goto(x, y)
if wasdown:
self.down()
def _predict(self, length):
corrected_heading = self._heading + math.pi/2
delta = [math.sin(corrected_heading), math.cos(corrected_heading)]
return [self._position[0] + length * delta[0], self._position[1] - length * delta[1]]
def forward(self, length):
self._position = self._predict(length)
if self._down:
_trace("goto: self._down")
self._track.append('{} {} {}'.format(
'L' if self._down else 'M',
self._position[0] + self.screen._offset[0],
self.screen._offset[1] - self._position[1])
)
self._flush()
self._update_transform()
def back(self, length):
self.forward(-length)
def stamp(self):
"""Stamp a copy of the turtleshape onto the canvas and return its id.
No argument.
Stamp a copy of the turtle shape onto the canvas at the current
turtle position.
Example (for a Turtle instance named turtle):
>>> turtle.color("blue")
>>> turtle.stamp()
"""
# TODO Return a stamp_id for that stamp, which can be
# used to delete it by calling clearstamp(stamp_id).
the_id = f"stamp-{uuid.uuid4()}"
cloned = self.svg.cloneNode(True)
cloned.setAttribute("id", the_id)
self.screen.svg_painting.appendChild(cloned)
return the_id
def dot(self, radius):
"""
<circle cx="50" cy="50" r="50" />
"""
dot = document.createElementNS (_ns, 'circle')
dot.setAttribute('cx', self._position[0] + self.screen._offset[0])
dot.setAttribute('cy', self.screen._offset[1] - self._position[1])
dot.setAttribute('r', radius)
dot.setAttribute('fill', self._fillcolor)
dot.setAttribute('stroke', self._pencolor)
dot.setAttribute('stroke-width', self._pensize)
self.screen.svg_painting.appendChild(dot)
self._paths.append(dot)
def circle(self, radius):
"""
<circle cx="50" cy="50" r="50" />
"""
circle = document.createElementNS (_ns, 'circle')
circle.setAttribute('cx', self._position[0] + self.screen._offset[0])
circle.setAttribute('cy', self.screen._offset[1] - self._position[1] )
circle.setAttribute('r', radius)
circle.setAttribute('fill', 'none')
circle.setAttribute('stroke', self._pencolor)
circle.setAttribute('stroke-width', self._pensize)
self.screen.svg_painting.appendChild(circle)
self._paths.append(circle)
def heading(self):
""" Return the turtle's current heading.
No arguments.
Example (for a Turtle instance named turtle):
>>> turtle.left(67)
>>> turtle.heading()
67.0
"""
return math.degrees(self._heading)
def _update_transform(self):
""" This *seems* to work
<g transform="translate(200,200)">
<use id="sprite-11056328"
href="#img/ch-archeologist-e.gif"
transform="rotate(90.0) scale(4.0,4.0)"
transform-origin="20 30"></use>
</g>
"""
shape = self.screen._shapes[self._shape]
tilt_fix = 0
if shape._type == 'polygon':
tilt_fix = -math.pi/2 # polygons are designed pointing top, images look natural pointing right :-/
_trace(f"{tilt_fix=}")
rot = math.degrees(-self._heading - self._tilt + tilt_fix)
_trace(f"{rot=}")
scale = f"{self._stretchfactor[0]},{self._stretchfactor[1]}"
translate = f"{self._position[0] + self.screen._offset[0]},{self.screen._offset[1] - self._position[1]}"
self.svg.setAttribute('transform',f"translate({translate})")
self.svg_shape.setAttribute('transform',
f"rotate({rot}) scale({scale})")
if shape._type == "image":
size = shape.get_svg_image_size()
self.svg_shape.setAttribute('transform',
f"translate(-{size[0] // 2}, -{size[1] // 2}) rotate({rot}) scale({scale})")
self.svg_shape.setAttribute('transform-origin',f'{size[0] // 2} {size[1] // 2}');
else:
#TODO manage polygon and compound cases
pass