-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathadafruit_turtle.py
1220 lines (928 loc) · 39.4 KB
/
adafruit_turtle.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
# Based on turtle.py, a Tkinter based turtle graphics module for Python
# Version 1.1b - 4. 5. 2009
# Copyright (C) 2006 - 2010 Gregor Lingl
# email: glingl@aon.at
#
# The MIT License (MIT)
#
# Copyright (c) 2019 LadyAda and Dave Astels for Adafruit Industries
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
"""
`adafruit_turtle`
================================================================================
Turtle graphics library for CircuitPython and displayio
* Author(s): LadyAda and Dave Astels
Implementation Notes
--------------------
**Hardware:**
**Software and Dependencies:**
* Adafruit CircuitPython firmware for the supported boards:
https://github.com/adafruit/circuitpython/releases
* Adafruit's Bus Device library: https://github.com/adafruit/Adafruit_CircuitPython_BusDevice
"""
#pylint:disable=too-many-public-methods,invalid-name,too-many-instance-attributes
#pylint:disable=too-few-public-methods,too-many-lines
import gc
import math
import time
import board
import displayio
import adafruit_logging as logging
__version__ = "0.0.0-auto.0"
__repo__ = "https://github.com/adafruit/Adafruit_CircuitPython_turtle.git"
class Color(object):
"""Standard colors"""
WHITE = 0xFFFFFF
BLACK = 0x000000
RED = 0xFF0000
ORANGE = 0xFFA500
YELLOW = 0xFFFF00
GREEN = 0x00FF00
BLUE = 0x0000FF
PURPLE = 0x800080
PINK = 0xFFC0CB
colors = (WHITE, BLACK, RED, ORANGE, YELLOW, GREEN, BLUE, PURPLE, PINK)
def __init__(self):
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 __init__(self, x, y):
super(Vec2D, self).__init__((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, (float, int)):
return Vec2D(self[0] * other, self[1] * other)
return None
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 (self[0]**2 + self[1]**2)**0.5
def rotate(self, angle):
"""Rotate self counterclockwise by angle.
:param angle: how much to rotate
"""
perp = Vec2D(-self[1], self[0])
angle = angle * math.pi / 180.0
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
class turtle(object):
"""A Turtle that can be given commands to draw."""
def __init__(self, display=board.DISPLAY):
self._logger = logging.getLogger("Turtle")
self._logger.setLevel(logging.DEBUG)
self._display = display
self._w = self._display.width
self._h = self._display.height
self._x = self._w // 2
self._y = self._h // 2
self._speed = 6
self._heading = 90
self._logomode = False
self._splash = displayio.Group(max_size=3)
self._bg_bitmap = displayio.Bitmap(self._w, self._h, 1)
self._bg_palette = displayio.Palette(1)
self._bg_palette[0] = Color.BLACK
self._bg_sprite = displayio.TileGrid(self._bg_bitmap,
pixel_shader=self._bg_palette,
x=0, y=0)
self._splash.append(self._bg_sprite)
self._fg_bitmap = displayio.Bitmap(self._w, self._h, 5)
self._fg_palette = displayio.Palette(len(Color.colors) + 1)
self._fg_palette.make_transparent(0)
for i, c in enumerate(Color.colors):
self._fg_palette[i + 1] = c
self._fg_sprite = displayio.TileGrid(self._fg_bitmap,
pixel_shader=self._fg_palette,
x=0, y=0)
self._splash.append(self._fg_sprite)
self._turtle_bitmap = displayio.Bitmap(9, 9, 2)
self._turtle_palette = displayio.Palette(2)
self._turtle_palette.make_transparent(0)
self._turtle_palette[1] = Color.WHITE
for i in range(4):
self._turtle_bitmap[4 - i, i] = 1
self._turtle_bitmap[i, 4 + i] = 1
self._turtle_bitmap[4 + i, 7 - i] = 1
self._turtle_bitmap[4 + i, i] = 1
self._turtle_sprite = displayio.TileGrid(self._turtle_bitmap,
pixel_shader=self._turtle_palette,
x=-100, y=-100)
self._drawturtle()
self._splash.append(self._turtle_sprite)
self._penstate = False
self._pencolor = None
self._pensize = 1
self.pencolor(Color.WHITE)
self._display.show(self._splash)
self._display.refresh_soon()
gc.collect()
self._display.wait_for_frame()
def _drawturtle(self):
self._turtle_sprite.x = int(self._x - 4)
self._turtle_sprite.y = int(self._y - 4)
#self._logger.debug("pos (%d, %d)", self._x, self._y)
############################################################################
# Move and draw
def forward(self, distance):
"""Move the turtle forward by the specified distance, in the direction the turtle is headed.
:param distance: how far to move (integer or float)
"""
p = self.pos()
x1 = p[0] + math.sin(math.radians(self._heading)) * distance
y1 = p[1] + math.cos(math.radians(self._heading)) * distance
self.goto(x1, y1)
fd = forward
def backward(self, distance):
"""Move the turtle backward by distance, opposite to the direction the turtle is headed.
Does not change the turtle's heading.
:param distance: how far to move (integer or float)
"""
self.forward(-distance)
bk = backward
back = backward
def right(self, angle):
"""Turn turtle right by angle units. (Units are by default degrees,
but can be set via the degrees() and radians() functions.)
Angle orientation depends on the turtle mode, see mode().
:param angle: how much to rotate to the right (integer or float)
"""
self._turn(angle)
rt = right
def left(self, angle):
"""Turn turtle left by angle units. (Units are by default degrees,
but can be set via the degrees() and radians() functions.)
Angle orientation depends on the turtle mode, see mode().
:param angle: how much to rotate to the left (integer or float)
"""
self._turn(-angle)
lt = left
#pylint:disable=too-many-branches,too-many-statements
def goto(self, x1, y1=None):
"""If y1 is None, x1 must be a pair of coordinates or an (x, y) tuple
Move turtle to an absolute position. If the pen is down, draw line.
Does not change the turtle's orientation.
:param x1: a number or a pair of numbers
:param y1: a number or None
"""
if y1 is None:
y1 = x1[1]
x1 = x1[0]
x1 += self._w // 2
y1 = self._h // 2 - y1
x0 = self._x
y0 = self._y
self._logger.debug("* GoTo from (%d, %d) to (%d, %d)", x0, y0, x1, y1)
if not self.isdown():
self._x = x1 # woot, we just skip ahead
self._y = y1
self._drawturtle()
return
steep = abs(y1 - y0) > abs(x1 - x0)
rev = False
dx = x1 - x0
if steep:
x0, y0 = y0, x0
x1, y1 = y1, x1
dx = x1 - x0
if x0 > x1:
rev = True
dx = x0 - x1
dy = abs(y1 - y0)
err = dx / 2
ystep = -1
if y0 < y1:
ystep = 1
while (not rev and x0 <= x1) or (rev and x1 <= x0):
if steep:
try:
self._plot(int(y0), int(x0), self._pencolor)
# self._fg_bitmap[int(y0), int(x0)] = self._pencolor
except IndexError:
pass
self._x = y0
self._y = x0
self._drawturtle()
time.sleep(0.003)
else:
try:
self._plot(int(x0), int(y0), self._pencolor)
# self._fg_bitmap[int(x0), int(y0)] = self._pencolor
except IndexError:
pass
self._x = x0
self._y = y0
self._drawturtle()
time.sleep(0.003)
err -= dy
if err < 0:
y0 += ystep
err += dx
if rev:
x0 -= 1
else:
x0 += 1
setpos = goto
setposition = goto
def setx(self, x):
"""Set the turtle's first coordinate to x, leave second coordinate
unchanged.
:param x: new value of the turtle's x coordinate (a number)
"""
self.goto(x, self.pos()[1])
def sety(self, y):
"""Set the turtle's second coordinate to y, leave first coordinate
unchanged.
:param y: new value of the turtle's y coordinate (a number)
"""
self.goto(self.pos()[0], y)
def setheading(self, to_angle):
"""Set the orientation of the turtle to to_angle. Here are some common
directions in degrees:
standard mode | logo mode
0 - east | 0 - north
90 - north | 90 - east
180 - west | 180 - south
270 - south | 270 - west
:param to_angle: the new turtle heading
"""
self._heading = to_angle
seth = setheading
def home(self):
"""Move turtle to the origin - coordinates (0,0) - and set its heading to
its start-orientation
(which depends on the mode, see mode()).
"""
self.setheading(90)
self.goto(0, 0)
def _plot(self, x, y, c):
try:
self._fg_bitmap[int(x), int(y)] = c
# self._logger.debug('Set fg_bitmap[%d, %d] to %d', x, y, self._fg_bitmap[int(x), int(y)])
except IndexError:
pass
def _draw_disk(self, x, y, width, height, r, color, fill=True, outline=True, stroke=1):
"""Draw a filled and/or outlined circle"""
if fill:
self._helper(x+r, y+r, r, color=color, fill=True,
x_offset=width-2*r-1, y_offset=height-2*r-1)
if outline:
self._helper(x+r, y+r, r, color=color, stroke=stroke,
x_offset=width-2*r-1, y_offset=height-2*r-1)
# pylint: disable=invalid-name, too-many-locals, too-many-branches
def _helper(self, x0, y0, r, color, x_offset=0, y_offset=0,
stroke=1, corner_flags=0x0F, fill=False):
"""Draw quandrant wedges filled or outlined"""
f = 1 - r
ddF_x = 1
ddF_y = -2 * r
x = -1
y = r
while x < y:
if f >= 0:
y -= 1
ddF_y += 2
f += ddF_y
x += 1
ddF_x += 2
f += ddF_x
if fill:
for w in range(x0-y, x0+y+x_offset):
self._plot(w, y0 + x + y_offset, color)
self._plot(w, y0 - x, color)
for w in range(x0-x, x0+x+x_offset):
self._plot(w, y0 + y + y_offset, color)
self._plot(w, y0 - y, color)
else:
for line in range(stroke):
self._plot(x0 - y + line, y0 + x + y_offset, color)
self._plot(x0 - x, y0 + y + y_offset - line, color)
self._plot(x0 - y + line, y0 - x, color)
self._plot(x0 - x, y0 - y + line, color)
for line in range(stroke):
self._plot(x0 + x + x_offset, y0 + y + y_offset - line, color)
self._plot(x0 + y + x_offset - line, y0 + x + y_offset, color)
self._plot(x0 + x + x_offset, y0 - y + line, color)
self._plot(x0 + y + x_offset - line, y0 - x, color)
# pylint: enable=invalid-name, too-many-locals, too-many-branches
def circle(self, radius, extent=None, steps=None):
"""Not implemented
Draw a circle with given radius. The center is radius units left of
the turtle; extent - an angle - determines which part of the circle is
drawn. If extent is not given, draw the entire circle. If extent is not
a full circle, one endpoint of the arc is the current pen position.
Draw the arc in counterclockwise direction if radius is positive,
otherwise in clockwise direction. Finally the direction of the turtle
is changed by the amount of extent.
As the circle is approximated by an inscribed regular polygon, steps
determines the number of steps to use. If not given, it will be
calculated automatically. May be used to draw regular polygons.
:param radius: the radius of the circle
:param extent: the arc of the circle to be drawn
:param steps: how many points along the arc are computed
"""
raise NotImplementedError
#pylint:disable=keyword-arg-before-vararg
def dot(self, size=None, color=None):
"""Not implemented
Draw a circular dot with diameter size, using color.
If size is not given, the maximum of pensize+4 and
2*pensize is used.
:param size: the diameter of the dot
:param color: the color of the dot
"""
if size is None:
size = max(self._pensize + 4, self._pensize * 2)
if color is None:
color = self._pencolor
else:
color = self._color_to_pencolor(color)
self._logger.debug('dot(%d)', size)
self._draw_disk(self._x - size, self._y - size, 2 * size + 1, 2 * size + 1, size, color)
self._fg_sprite[0,0] = 0
def stamp(self):
"""Not implemented
Stamp a copy of the turtle shape onto the canvas at the current
turtle position. Return a stamp_id for that stamp, which can be used to
delete it by calling clearstamp(stamp_id).
"""
raise NotImplementedError
def clearstamp(self, stampid):
"""Not implemented
Delete stamp with given stampid.
:param stampid: the id of the stamp to be deleted
"""
raise NotImplementedError
def clearstamps(self, n=None):
"""Not implemented
Delete all or first/last n of turtle's stamps. If n is None, delete
all stamps, if n > 0 delete first n stamps, else if n < 0 delete last
n stamps.
:param n: how many stamps to delete (None means delete them all)
"""
raise NotImplementedError
def undo(self):
"""Not implemented
Undo (repeatedly) the last turtle action(s). Number of available undo
actions is determined by the size of the undobuffer.
"""
raise NotImplementedError
def speed(self, speed=None):
"""Not implemented
Set the turtle's speed to an integer value in the range 0..10. If no
argument is given, return current speed.
If input is a number greater than 10 or smaller than 0.5, speed is set
to 0. Speedstrings are mapped to speedvalues as follows:
"fastest": 0
"fast": 10
"normal": 6
"slow": 3
"slowest": 1
Speeds from 1 to 10 enforce increasingly faster animation of line
drawing and turtle turning.
Attention: speed = 0 means that no animation takes place.
forward/back makes turtle jump and likewise left/right make the
turtle turn instantly.
:param speed: the new turtle speed (0..10) or None
"""
raise NotImplementedError
############################################################################
# Tell turtle's state
def pos(self):
"""Return the turtle's current location (x,y) (as a Vec2D vector)."""
return Vec2D(self._x - self._w // 2, self._h // 2 - self._y)
position = pos
def towards(self, x1, y1=None):
"""Not implemented
Return the angle between the line from turtle position to position
specified by (x,y) or the vector. This depends on the turtle's start
orientation which depends on the mode - "standard" or "logo").
:param x: a number or a pair/vector of numbers
:param y: a number if x is a number, else None
"""
raise NotImplementedError
def xcor(self):
"""Not implemented
Return the turtle's x coordinate."""
raise NotImplementedError
def ycor(self):
"""Not implemented
Return the turtle's y coordinate."""
raise NotImplementedError
def heading(self):
"""Return the turtle's current heading (value depends on the turtle
mode, see mode()).
"""
return self._heading
def distance(self, x1, y1=None):
"""Not implemented
Return the distance from the turtle to (x,y) or the vector, in turtle
step units.
:param x: a number or a pair/vector of numbers
:param y: a number if x is a number, else None
"""
raise NotImplementedError
############################################################################
# Setting and measurement
def degrees(self, fullcircle=360):
"""Not implemented
Set angle measurement units, i.e. set number of "degrees" for a full circle.
Default value is 360 degrees.
:param fullcircle: the number of degrees in a full circle
"""
raise NotImplementedError
def radians(self):
"""Not implemented
Set the angle measurement units to radians. Equivalent to degrees(2*math.pi)."""
raise NotImplementedError
############################################################################
# Drawing state
def pendown(self):
"""Pull the pen down - drawing when moving."""
self._penstate = True
pd = pendown
down = pendown
def penup(self):
"""Pull the pen up - no drawing when moving."""
self._penstate = False
pu = penup
up = penup
def pensize(self, width=None):
"""Not implemented
Set the line thickness to width or return it. If resizemode is set to
"auto" and turtleshape is a polygon, that polygon is drawn with the same
line thickness. If no argument is given, the current pensize is returned.
:param width: - a positive number
"""
if width is not None:
self._pensize = width
return self._pensize
width = pensize
def pen(self, pen=None, **pendict):
"""Not implemented
Not implemented
Return or set the pen's attributes in a "pen-dictionary" with
the following key/value pairs:
"shown": True/False
"pendown": True/False
"pencolor": color-string or color-tuple
"fillcolor": color-string or color-tuple
"pensize": positive number
"speed": number in range 0..10
"resizemode": "auto" or "user" or "noresize"
"stretchfactor": (positive number, positive number)
"outline": positive number
"tilt": number
This dictionary can be used as argument for a subsequent call to pen()
to restore the former pen-state. Moreover one or more of these
attributes can be provided as keyword-arguments. This can be used to
set several pen attributes in one statement.
:param pen: a dictionary with some or all of the above listed keys
:param pendict: ne or more keyword-arguments with the above listed keys
as keywords
"""
raise NotImplementedError
def isdown(self):
"""Return True if pen is down, False if it's up."""
return self._penstate
############################################################################
# Color control
def _color_to_pencolor(self, c):
return 1 + Color.colors.index(c)
def color(self, *args):
"""Not implemented
Return or set pencolor and fillcolor.
Several input formats are allowed. They use 0 to 3 arguments as follows:
color()
Return the current pencolor and the current fillcolor as a pair of
color specification strings or tuples as returned by pencolor() and
fillcolor().
color(colorstring), color((r, g, b)), color(r, g, b)
Inputs as in pencolor(), set both, fillcolor and pencolor, to the
given value.
color(colorstring1, colorstring2), color((r1, g1, b1), (r2, g2, b2))
Equivalent to pencolor(colorstring1) and fillcolor(colorstring2)
and analogously if the other input format is used.
If turtleshape is a polygon, outline and interior of that polygon is
drawn with the newly set colors.
"""
raise NotImplementedError
def pencolor(self, c=None):
"""
Return or set the pencolor.
Four input formats are allowed:
pencolor()
Return the current pencolor as color specification string or as a
tuple (see example). May be used as input to another color/
pencolor/fillcolor call.
pencolor(colorstring)
Set pencolor to colorstring, which is a Tk color specification
string, such as "red", "yellow", or "#33cc8c".
pencolor((r, g, b))
Set pencolor to the RGB color represented by the tuple of r, g, and
b. Each of r, g, and b must be in the range 0..colormode, where
colormode is either 1.0 or 255 (see colormode()).
pencolor(r, g, b)
Set pencolor to the RGB color represented by r, g, and b. Each of r,
g, and b must be in the range 0..colormode.
If turtleshape is a polygon, the outline of that polygon is drawn with
the newly set pencolor.
"""
if c is None:
return Color.colors[self._pencolor - 1]
if not c in Color.colors:
raise RuntimeError("Color must be one of the 'Color' class items")
self._pencolor = 1 + Color.colors.index(c)
return c
def fillcolor(self, c=None):
"""Not implemented
Return or set the fillcolor.
Four input formats are allowed:
fillcolor()
Return the current fillcolor as color specification string, possibly
in tuple format (see example). May be used as input to another
color/pencolor/fillcolor call.
fillcolor(colorstring)
Set fillcolor to colorstring, which is a Tk color specification
string, such as "red", "yellow", or "#33cc8c".
fillcolor((r, g, b))
Set fillcolor to the RGB color represented by the tuple of r, g, and
b. Each of r, g, and b must be in the range 0..colormode, where
colormode is either 1.0 or 255 (see colormode()).
fillcolor(r, g, b)
Set fillcolor to the RGB color represented by r, g, and b. Each of
r, g, and b must be in the range 0..colormode.
If turtleshape is a polygon, the interior of that polygon is drawn with
the newly set fillcolor.
"""
raise NotImplementedError
############################################################################
# Filling
def filling(self):
"""Not implemented
Return fillstate (True if filling, False else)."""
raise NotImplementedError
def begin_fill(self):
"""Not implemented
To be called just before drawing a shape to be filled."""
raise NotImplementedError
def end_fill(self):
"""Not implemented
Fill the shape drawn after the last call to begin_fill()."""
raise NotImplementedError
############################################################################
# More drawing control
def reset(self):
"""Not implemented
Delete the turtle's drawings from the screen, re-center the turtle
and set variables to the default values."""
raise NotImplementedError
def clear(self):
"""Delete the turtle's drawings from the screen. Do not move turtle.
State and position of the turtle as well as drawings of other turtles
are not affected.
"""
for w in range(self._w):
for h in range(self._h):
self._fg_bitmap[w, h] = 0
for i, c in enumerate(Color.colors):
self._fg_palette[i + 1] = c ^ 0xFFFFFF
self._display.refresh_soon()
for i, c in enumerate(Color.colors):
self._fg_palette[i + 1] = c
self._display.refresh_soon()
time.sleep(0.1)
def write(self, arg, move=False, align="left", font=("Arial", 8, "normal")):
"""Not implemented
Write text - the string representation of arg - at the current turtle
position according to align ("left", "center" or "right") and with the
given font. If move is true, the pen is moved to the bottom-right corner
of the text. By default, move is False.
:param arg: object to be written to the TurtleScreen
:param move": True/False
:param align: one of the strings "left", "center" or "right"
:param font: a triple (fontname, fontsize, fonttype)
"""
raise NotImplementedError
############################################################################
# Visibility
def showturtle(self):
"""Not implemented
Make the turtle visible."""
raise NotImplementedError
st = showturtle
def hideturtle(self):
"""Not implemented
Make the turtle invisible."""
raise NotImplementedError
ht = hideturtle
def isvisible(self):
"""Not implemented
Return True if the Turtle is shown, False if it's hidden."""
raise NotImplementedError
############################################################################
# Appearance
def shape(self, name=None):
"""Not implemented
Set turtle shape to shape with given name or, if name is not
given, return name of current shape. Shape with name must exist
in the TurtleScreen's shape dictionary. Initially there are the
following polygon shapes: "arrow", "turtle", "circle", "square",
"triangle", "classic". To learn about how to deal with shapes
see Screen method register_shape().
:param name: a string which is a valid shapename
"""
raise NotImplementedError
def resizemode(self, rmode=None):
"""Not implemented
Set resizemode to one of the values: "auto", "user",
"noresize". If rmode is not given, return current
resizemode. Different resizemodes have the following effects:
"auto": adapts the appearance of the turtle corresponding to the value
of pensize.
"user": adapts the appearance of the turtle according to the values of
stretchfactor and outlinewidth (outline), which are set by shapesize().
"noresize": no adaption of the turtle's appearance takes place.
resizemode("user") is called by shapesize() when used with arguments.
:param rmode: one of the strings "auto", "user", or "noresize"
"""
raise NotImplementedError
def shapesize(self, stretch_wid=None, stretch_len=None, outline=None):
"""Not implemented
Return or set the pen's attributes x/y-stretchfactors and/or
outline. Set resizemode to "user". If and only if resizemode is
set to "user", the turtle will be displayed stretched according
to its stretchfactors: stretch_wid is stretchfactor
perpendicular to its orientation, stretch_len is stretchfactor
in direction of its orientation, outline determines the width of
the shapes's outline.
:param stretch_wid: positive number
:param stretch_len: positive number
:param outline: positive number
"""
raise NotImplementedError
turtlesize = shapesize
def sheerfactor(self, shear=None):
"""Not implemented
Set or return the current shearfactor. Shear the turtleshape
according to the given shearfactor shear, which is the tangent
of the shear angle. Do not change the turtle's heading
(direction of movement). If shear is not given: return the
current shearfactor, i. e. the tangent of the shear angle, by
which lines parallel to the heading of the turtle are sheared.
:param shear: number (optional)
"""
raise NotImplementedError
def settiltangle(self, angle):
"""Not implemented
Rotate the turtleshape to point in the direction specified by
angle, regardless of its current tilt-angle. Do not change the
turtle's heading (direction of movement).
:param angle: a number
"""
raise NotImplementedError
def tiltangle(self, angle=None):
"""Not implemented
Set or return the current tilt-angle. If angle is given,
rotate the turtleshape to point in the direction specified by
angle, regardless of its current tilt-angle. Do not change the
turtle's heading (direction of movement). If angle is not given:
return the current tilt-angle, i. e. the angle between the
orientation of the turtleshape and the heading of the turtle
(its direction of movement).
:param angle: a number (optional)
"""
raise NotImplementedError
def tilt(self, angle):
"""Not implemented
Rotate the turtleshape by angle from its current tilt-angle,
but do not change the turtle's heading (direction of movement).
:param angle: a number
"""
raise NotImplementedError
def shapetransform(self, t11=None, t12=None, t21=None, t22=None):
"""Not implemented
Set or return the current transformation matrix of the turtle shape.
If none of the matrix elements are given, return the transformation
matrix as a tuple of 4 elements. Otherwise set the given elements and
transform the turtleshape according to the matrix consisting of first
row t11, t12 and second row t21, 22. The determinant t11 * t22 - t12 *
t21 must not be zero, otherwise an error is raised. Modify
stretchfactor, shearfactor and tiltangle according to the given matrix.
:param t11: a number (optional)
:param t12: a number (optional)
:param t21: a number (optional)
:param t12: a number (optional)
"""
raise NotImplementedError
def get_shapepoly(self):
"""Not implemented
Return the current shape polygon as tuple of coordinate
pairs. This can be used to define a new shape or components of a
compound shape.
"""
raise NotImplementedError
############################################################################
# Using events
def onclick(self, fun, btn=1, add=None):
"""Not implemented
Bind fun to mouse-click events on this turtle. If fun is
None, existing bindings are removed.
:param fun: a function with two arguments which will be called with the
coordinates of the clicked point on the canvas
:param btn: number of the mouse-button, defaults to 1 (left mouse button)