ipycc.turtle

   1from contextlib import contextmanager
   2import math
   3import time
   4from ipycanvas import hold_canvas
   5from .sketch import Sketch
   6from ._colors import named_colors
   7
   8
   9class Vec2D(tuple):
  10    """A 2 dimensional vector class, used as a helper class
  11    for implementing turtle graphics.
  12    May be useful for turtle graphics programs also.
  13    Derived from tuple, so a vector is a tuple!
  14
  15    Provides (for `a`, `b` vectors, `k` number):
  16    -  `a+b` vector addition
  17    - `a-b` vector subtraction
  18    - `a*b` inner product
  19    - `k*a` and `a*k` multiplication with scalar
  20    - `|a|` absolute value of `a`
  21    - `a.rotate(angle)` rotation
  22    """
  23
  24    def __new__(cls, x, y):
  25        return tuple.__new__(cls, (x, y))
  26
  27    def __add__(self, other):
  28        return Vec2D(self[0] + other[0], self[1] + other[1])
  29
  30    def __mul__(self, other):
  31        if isinstance(other, Vec2D):
  32            return self[0] * other[0] + self[1] * other[1]
  33        return Vec2D(self[0] * other, self[1] * other)
  34
  35    def __rmul__(self, other):
  36        if isinstance(other, int) or isinstance(other, float):
  37            return Vec2D(self[0] * other, self[1] * other)
  38        return NotImplemented
  39
  40    def __sub__(self, other):
  41        return Vec2D(self[0] - other[0], self[1] - other[1])
  42
  43    def __neg__(self):
  44        return Vec2D(-self[0], -self[1])
  45
  46    def __abs__(self):
  47        return math.hypot(*self)
  48
  49    def rotate(self, angle: int | float):
  50        """Returns a vector with the same magnitude that is rotated
  51        counterclockwise by a given angle.
  52
  53        Argument: `angle` -- a number
  54
  55        **Example**
  56        ```python
  57        from ipycc.turtle import Vec2D
  58
  59        v1 = Vec2D(1, 0)
  60        v2 = v1.rotate(90)
  61        print(v1) # (1.00,0.00)
  62        print(v2) # (0.00,1.00)
  63        ```
  64        """
  65        perp = Vec2D(-self[1], self[0])
  66        angle = math.radians(angle)
  67        c, s = math.cos(angle), math.sin(angle)
  68        return Vec2D(self[0] * c + perp[0] * s, self[1] * c + perp[1] * s)
  69
  70    def __getnewargs__(self):
  71        return (self[0], self[1])
  72
  73    def __repr__(self):
  74        return "(%.2f,%.2f)" % self
  75
  76
  77class TurtleGraphicsError(Exception):
  78    """Some TurtleGraphics Error.
  79    """
  80
  81
  82# Shape vertices.
  83_turtle_shapes = {
  84    "arrow" : ((-10, 0), (10, 0), (0, 10)),
  85    "turtle" : ((0, 16), (-2, 14), (-1, 10), (-4, 7),
  86                (-7, 9), (-9, 8), (-6, 5), (-7, 1), (-5, -3), (-8, -6),
  87                (-6,-8), (-4, -5), (0, -7), (4, -5), (6, -8), (8, -6),
  88                (5, -3), (7, 1), (6, 5), (9, 8), (7, 9), (4, 7), (1, 10),
  89                (2, 14)),
  90    "circle" : ((10, 0), (9.51, 3.09), (8.09, 5.88),
  91                (5.88, 8.09), (3.09, 9.51), (0, 10), (-3.09, 9.51),
  92                (-5.88, 8.09), (-8.09, 5.88), (-9.51, 3.09), (-10, 0),
  93                (-9.51, -3.09), (-8.09, -5.88), (-5.88, -8.09),
  94                (-3.09, -9.51), (-0.00, -10.00), (3.09, -9.51),
  95                (5.88, -8.09), (8.09, -5.88), (9.51, -3.09)),
  96    "square" : ((10, -10), (10, 10), (-10, 10),
  97                (-10, -10)),
  98    "triangle" : ((10, -5.77), (0, 11.55),
  99                (-10, -5.77)),
 100    "classic": ((0, 0),(-5, -9),(0, -7),(5, -9)),
 101}
 102
 103
 104# Default screen configuration.
 105_screen_width = 400
 106_screen_height = 400
 107
 108
 109class _Screen:
 110    """Provide the basic graphics functionality.
 111    """
 112    def __init__(self,
 113                 width: int | float =_screen_width,
 114                 height: int | float =_screen_height):
 115        self.width = width
 116        self.height = height
 117        self._sketch = Sketch(self.width, self.height)
 118        self._sketch_manager = self._sketch.canvas._canvas_manager
 119        self._colormode = 1.0
 120        self._bgcolor = "white"
 121        self._sketch.background(self._bgcolor)
 122        self._turtles = []
 123        self._delayvalue = 10
 124        self._tracing = 1
 125        self._updatecounter = 0
 126        self.xscale = self.yscale = 1.0
 127    
 128    def _iscolorstring(self, color) -> bool:
 129        """Check if the string color is a legal Tkinter color string.
 130        """
 131        return color in named_colors
 132
 133    def _colorstr(self, color: str | tuple[int | float]) -> str:
 134        """Return color string corresponding to args.
 135
 136        Argument may be a string or a tuple of three
 137        numbers corresponding to actual colormode,
 138        i.e. in the range 0<=n<=colormode.
 139
 140        If the argument doesn't represent a color,
 141        an error is raised.
 142        """
 143        if len(color) == 1:
 144            color = color[0]
 145        if isinstance(color, str):
 146            if self._iscolorstring(color) or color == "":
 147                return named_colors[color]
 148            else:
 149                raise TurtleGraphicsError("bad color string: %s" % str(color))
 150        try:
 151            r, g, b = color
 152        except (TypeError, ValueError):
 153            raise TurtleGraphicsError("bad color arguments: %s" % str(color))
 154        if self._colormode == 1.0:
 155            r, g, b = [round(255.0 * x) for x in (r, g, b)]
 156        if not ((0 <= r <= 255) and (0 <= g <= 255) and (0 <= b <= 255)):
 157            raise TurtleGraphicsError("bad color sequence: %s" % str(color))
 158        return "#%02x%02x%02x" % (r, g, b)
 159
 160    def _color(self, cstr) -> str | tuple:
 161        if not cstr.startswith("#"):
 162            return cstr
 163        if len(cstr) == 7:
 164            cl = [int(cstr[i:i + 2], 16) for i in (1, 3, 5)]
 165        elif len(cstr) == 4:
 166            cl = [16 * int(cstr[h], 16) for h in cstr[1:]]
 167        else:
 168            raise TurtleGraphicsError("bad colorstring: %s" % cstr)
 169        return tuple(c * self._colormode / 255 for c in cl)
 170
 171    def add_turtle(self, t):
 172        """Adds a turtle to be drawn."""
 173        if t not in self._turtles:
 174            self._turtles.append(t)
 175    
 176    def _incrementudc(self):
 177        """Increment update counter."""
 178        if self._tracing > 0:
 179            self._updatecounter += 1
 180            self._updatecounter %= self._tracing
 181
 182    def _update(self):
 183        """Redraws the screen."""
 184        if self._tracing == 0:
 185            return
 186        self._incrementudc()
 187        if self._updatecounter > 0:
 188            self._sketch_manager._caching = True
 189        if self._updatecounter == 0 and self._tracing > 0:
 190            with hold_canvas():
 191                self._sketch.background(self._bgcolor)
 192                for t in self._turtles:
 193                    self._sketch.canvas.save()
 194                    self._sketch.scale(1, -1)
 195                    self._sketch.translate(0, -self.height)
 196                    self._sketch.image(t._pen, 0, 0)
 197                    self._sketch.reset_matrix()
 198                    self._sketch.canvas.restore()
 199                for t in self._turtles: 
 200                    if t.isvisible():
 201                        self._sketch.canvas.save()
 202                        self._sketch.scale(1, -1)
 203                        self._sketch.translate(0, -self.height)
 204                        x, y = t._to_screen_coords(t._position)
 205                        self._sketch.translate(x, y)
 206                        angle = math.radians(t.heading() + t.tiltangle()) - math.pi / 2
 207                        self._sketch.rotate(angle)
 208                        self._sketch.stroke(t._pencolor)
 209                        self._sketch.stroke_weight(t._outlinewidth)
 210                        self._sketch.fill(t._fillcolor)
 211                        self._sketch.begin_shape()
 212                        shape = _turtle_shapes[t._shape]
 213                        sx, sy = t._stretchfactor
 214                        for v in shape:
 215                            self._sketch.vertex(sx * v[0], sy * v[1])
 216                        self._sketch.end_shape()
 217                        self._sketch.reset_matrix()
 218                        self._sketch.canvas.restore()
 219            self._sketch_manager._caching = False
 220            self._sketch_manager.flush()
 221
 222    def _delay(self, ms: int | float):
 223        """Delays animation for a given number of milliseconds."""
 224        time.sleep(ms * 0.001)
 225    
 226    def replace(self):
 227        """Copy the screen and reassign its turtles."""
 228        screen = _Screen(self.width, self.height)
 229        screen._bgcolor = self._bgcolor
 230        screen._sketch.background(self._bgcolor)
 231        screen._turtles = self._turtles
 232        screen._delayvalue = self._delayvalue
 233        screen._tracing = self._tracing
 234        screen._updatecounter = self._updatecounter
 235        screen.xscale = self.xscale
 236        screen.yscale = self.yscale
 237        return screen
 238
 239    def show(self):
 240        """Display the screen's drawing canvas."""
 241        self._update()
 242        self._sketch.show()
 243
 244
 245# Screen singleton.
 246_SCREEN = _Screen()
 247
 248
 249def setup(width: int | float, height: int | float):
 250    """Sets the size of the screen.
 251
 252    Arguments:
 253    - `width` -- a number
 254    - `height` -- a number
 255
 256    The first two arguments, `width` and `height`, set the width of the
 257    drawing screen in pixels.
 258
 259    Calling `setup()` will resize the screen and all turtles will be reset.
 260
 261    **Example**
 262    ```python
 263    from ipycc.turtle import Turtle, showscreen, setup
 264
 265    # Show the screen.
 266    showscreen()
 267
 268    # Set the screen to half size.
 269    setup(200, 200)
 270
 271    # Create a turtle.
 272    t = Turtle()
 273    ```
 274    """
 275    global _SCREEN
 276    new_screen = _Screen(width, height)
 277    new_screen._turtles = _SCREEN._turtles
 278    for t in new_screen._turtles:
 279        t._pen = Sketch(width, height)
 280        t.reset()
 281    _SCREEN = new_screen
 282
 283
 284def showscreen():
 285    """Shows the screen to which turtles are drawing.
 286
 287    Calling `showscreen()` displays the drawing screen beneath the
 288    code cell in which it's called.
 289
 290    **Example**
 291    ```python
 292    from ipycc.turtle import Turtle, showscreen
 293
 294    # Show the screen.
 295    showscreen()
 296
 297    # Create a turtle and move it.
 298    t = Turtle()
 299    t.forward(100)
 300
 301    # Create a turtle and move it.
 302    t2 = Turtle()
 303    for i in range(4):
 304        t2.forward(50)
 305        t2.left(90)
 306    ```
 307    """
 308    global _SCREEN
 309    # Copy the screen and reassign its turtles.
 310    new_screen = _SCREEN.replace()
 311    _SCREEN = new_screen
 312    # Show the screen.
 313    _SCREEN.show()
 314
 315
 316def tracer(n: int = None, delay: int = None) -> int:
 317    """Turns turtle animation on/off and set delay for updating drawings.
 318
 319    Optional arguments:
 320    - `n` -- a nonnegative integer
 321    - `delay` -- a nonnegative integer
 322    
 323    If no argument is passed, the current rate of screen updates is returned. The
 324    default value is 1.
 325
 326    If `n` is given, only each n-th regular screen update is really performed.
 327    This feature can be used to accelerate the drawing of complex graphics.
 328
 329    If `delay` is given, it sets the screen's delay value.
 330    
 331    **Example**
 332    ```python
 333    from ipycc.turtle import Turtle, showscreen, tracer
 334
 335    # Show the screen.
 336    showscreen()
 337
 338    # Create a turtle.
 339    t = Turtle()
 340
 341    # Draw every 8th frame with a delay of 25 ms.
 342    tracer(8, 25)
 343    dist = 2
 344    for i in range(200):
 345        fd(dist)
 346        rt(90)
 347        dist += 2
 348    ```
 349    """
 350    if n is None:
 351        return _SCREEN._tracing
 352    _SCREEN._tracing = int(n)
 353    _SCREEN._updatecounter = 0
 354    if delay is not None:
 355        _SCREEN._delayvalue = int(delay)
 356    if _SCREEN._tracing:
 357        _SCREEN._update()
 358
 359
 360def delay(delay: int = None) -> int:
 361    """ Return or set the drawing delay in milliseconds.
 362
 363    Optional argument:
 364    `delay` -- positive integer
 365
 366    **Example**
 367    ```python
 368    from ipycc.turtle import delay
 369
 370    delay(15)
 371    print(delay()) # 15
 372    ```
 373    """
 374    if delay is None:
 375        return _SCREEN._delayvalue
 376    _SCREEN._delayvalue = int(delay)
 377
 378
 379@contextmanager
 380def no_animation():
 381    """Temporarily turn off auto-updating the screen.
 382
 383    This is useful for drawing complex shapes where even the fastest setting
 384    is too slow. Once this context manager is exited, the drawing will
 385    be displayed.
 386
 387    **Example**
 388    ```python
 389    from ipycc.turtle import Turtle, showscreen, no_animation
 390
 391    # Show the screen.
 392    showscreen()
 393
 394    # Create a turtle.
 395    t = Turtle()
 396
 397    # Draw a circle without animation.
 398    with no_animation():
 399        for i in range(360):
 400            t.forward(1)
 401            t.left(1)
 402    ```
 403    """
 404    t = tracer()
 405    try:
 406        tracer(0)
 407        yield
 408    finally:
 409        tracer(t)
 410
 411
 412def clearscreen():
 413    """Delete all drawings and all turtles from the screen.
 414    
 415    Resets the now empty screen to its initial state with a white background.
 416
 417    **Example**
 418    ```python
 419    from ipycc.turtle import Turtle, showscreen, clearscreen
 420
 421    # Show the screen.
 422    showscreen()
 423
 424    # Create a turtle.
 425    t = Turtle()
 426
 427    # Move the turtle forward.
 428    t.forward(100)
 429    
 430    # Clear the screen.
 431    clearscreen()
 432    ```
 433    """
 434    for t in _SCREEN._turtles:
 435        t.clear()
 436        t.hideturtle()
 437    _SCREEN._turtles = []
 438    _SCREEN._sketch.background("white")
 439
 440
 441def resetscreen():
 442    """Reset all turtles on the screen to their initial state.
 443
 444    Calling `resetscreen()` resets all turtles on the screen.
 445
 446    **Example**
 447    ```python
 448    from ipycc.turtle import Turtle, showscreen, resetscreen
 449
 450    # Show the screen.
 451    showscreen()
 452
 453    # Create a turtle.
 454    t = Turtle()
 455
 456    # Move the turtle forward.
 457    t.forward(100)
 458    
 459    # Reset the screen.
 460    resetscreen()
 461    ```
 462    """
 463    for t in _SCREEN._turtles:
 464        t.reset()
 465
 466
 467def colormode(cmode: int | float = None) -> None | int | float:
 468    """Return the colormode or set it to 1.0 or 255.
 469
 470    Optional argument:
 471    `cmode` -- one of the values 1.0 or 255
 472
 473    r, g, b values of colortriples have to be in range `0..cmode`.
 474
 475    **Example**
 476    ```python
 477    from ipycc.turtle import Turtle, showscreen
 478
 479    # Show the screen.
 480    showscreen()
 481
 482    # Create a turtle.
 483    t = Turtle()
 484
 485    # Print the turtle's default color mode.
 486    print(t.colormode()) # 1.0
 487    # Change the turtle's color mode and change its color.
 488    t.colormode(255)
 489    t.color(240, 160, 80)
 490    ```
 491    """
 492    if cmode is None:
 493        return _SCREEN._colormode
 494    if cmode == 1.0:
 495        _SCREEN._colormode = float(cmode)
 496    elif cmode == 255:
 497        _SCREEN._colormode = int(cmode)
 498
 499
 500def bgcolor(*args) -> None | str:
 501    """Set or return background color of the turtle's screen.
 502
 503    Arguments:
 504    Four input formats are allowed:
 505        - `bgcolor()`
 506        Return the current background as color specification string,
 507        possibly in hex-number format (see example).
 508        May be used as input to another color/pencolor/fillcolor call.
 509        - `bgcolor(colorstring)`
 510        a [Tk color specification string](https://www.tcl-lang.org/man/tcl8.4/TkCmd/colors.htm),
 511        such as `"red"` or `"yellow"`
 512        - `bgcolor((r, g, b))`
 513        *a tuple* of `r`, `g`, and `b`, which represent, an RGB color,
 514        and each of `r`, `g`, and `b` are in the range `0..colormode`,
 515        where `colormode` is either 1.0 or 255
 516        - `bgcolor(r, g, b)`
 517        `r`, `g`, and `b` represent an RGB color, and each of `r`, `g`,
 518        and `b` are in the range `0..colormode`
 519
 520    **Example**
 521    ```python
 522    from ipycc.turtle import showscreen, bgcolor
 523
 524    # Show the screen.
 525    showscreen()
 526
 527    # Set the screen's background color and print it.
 528    bgcolor("orange")
 529    print(bgcolor()) # 'orange'
 530    ```
 531    """
 532    if args:
 533        _SCREEN._bgcolor = _SCREEN._colorstr(args)
 534        _SCREEN._update()
 535    else:
 536        return _SCREEN._bgcolor
 537
 538
 539class Turtle:
 540    """A class to describe a virtual turtle robot drawing on a screen."""
 541
 542    def __init__(self):
 543        self._pen = Sketch(_SCREEN.width, _SCREEN.height)
 544        _SCREEN.add_turtle(self)
 545        self.reset()
 546
 547    def _to_screen_coords(self, v: Vec2D) -> Vec2D:
 548        x = _SCREEN.width * 0.5 + v[0]
 549        y = _SCREEN.height * 0.5 + v[1]
 550        return Vec2D(x, y)
 551
 552    # ========================================
 553    #              Turtle Motion
 554    # ========================================
 555
 556    def _update(self):
 557        """Perform a Turtle-data update.
 558        """
 559        if _SCREEN._tracing == 0:
 560            return
 561        _SCREEN._update()
 562        _SCREEN._delay(_SCREEN._delayvalue)
 563
 564    def _go(self, distance: int | float):
 565        """Move turtle forward by specified distance"""
 566        ende = self._position + self._orient * distance
 567        self._goto(ende)
 568
 569    def _goto(self, end: Vec2D):
 570        """Move the pen to the point end, thereby drawing a line
 571        if pen is down. All other methods for turtle movement depend
 572        on this one.
 573        """
 574        start = self._position
 575        if self._speed and _SCREEN._tracing == 1:
 576            diff = end - start
 577            diffsq = (diff[0] * _SCREEN.xscale)**2 + (diff[1] * _SCREEN.yscale)**2
 578            nhops = 1 + int((diffsq**0.5) / (3 * (1.1**self._speed) * self._speed))
 579            delta = diff * (1.0 / nhops)
 580            for n in range(1, nhops + 1):
 581                self._position = start + delta * n
 582                if self._drawing:
 583                    x1, y1 = self._to_screen_coords(start)
 584                    x2, y2 = self._to_screen_coords(self._position)
 585                    self._pen.line(x1, y1, x2, y2)
 586                self._update()
 587        else:
 588            x1, y1 = self._to_screen_coords(start)
 589            x2, y2 = self._to_screen_coords(end)
 590            if self._drawing:
 591                self._pen.line(x1, y1, x2, y2)
 592        if isinstance(self._fillpath, list):
 593            self._fillpath.append(end)
 594        self._position = end
 595        self._update()
 596
 597    def forward(self, distance: int | float):
 598        """Move the turtle forward by the specified distance.
 599
 600        Aliases: `forward` | `fd`
 601
 602        Argument:
 603        `distance` -- a number (integer or float)
 604
 605        Move the turtle forward by the specified `distance`, in the direction
 606        the turtle is headed.
 607
 608        **Example**
 609        ```python
 610        from ipycc.turtle import Turtle, showscreen
 611
 612        # Show the screen.
 613        showscreen()
 614
 615        # Create a turtle.
 616        t = Turtle()
 617
 618        print(t.position()) # (0.00, 0.00)
 619        t.forward(25)
 620        print(t.position()) # (25.00,0.00)
 621        t.forward(-75)
 622        print(t.position()) # (-50.00,0.00)
 623        ```
 624        """
 625        self._go(distance)
 626
 627    fd = forward
 628
 629    def backward(self, distance: int | float):
 630        """Move the turtle backward by distance.
 631
 632        Aliases: `back` | `backward` | `bk`
 633
 634        Argument:
 635        `distance` -- a number
 636
 637        Move the turtle backward by `distance`, opposite to the direction the
 638        turtle is headed. Do not change the turtle's heading.
 639
 640        **Example**
 641        ```python
 642        from ipycc.turtle import Turtle, showscreen
 643
 644        # Show the screen.
 645        showscreen()
 646
 647        # Create a turtle.
 648        t = Turtle()
 649
 650        # Print the turtle's position before and after moving.
 651        print(t.position()) # (0.00, 0.00)
 652        t.backward(30)
 653        print(t.position()) # (-30.00, 0.00)
 654        ```
 655        """
 656        self._go(-distance)
 657
 658    back = backward
 659    bk = backward
 660
 661    def _rotate(self, angle: int | float):
 662        """Turn turtle counterclockwise by specified angle if angle > 0."""
 663        self._orient = self._orient.rotate(angle)
 664        self._update()
 665
 666    def right(self, angle: int | float):
 667        """Turn turtle right by angle units.
 668
 669        Aliases: `right` | `rt`
 670
 671        Argument:
 672        `angle` -- a number (integer or float)
 673
 674        Turn turtle right by `angle` units. (Units are by default degrees,
 675        but can be set via the `degrees()` and `radians()` methods.)
 676        Angle orientation depends on mode. (See this.)
 677
 678        **Example**
 679        ```python
 680        from ipycc.turtle import Turtle, showscreen
 681
 682        # Show the screen.
 683        showscreen()
 684
 685        # Create a turtle.
 686        t = Turtle()
 687
 688        # Print the turtle's heading before and after turning.
 689        print(t.heading()) # 22.0
 690        t.right(45)
 691        print(t.heading()) # 337.0
 692        ```
 693        """
 694        self._rotate(-angle)
 695
 696    rt = right
 697
 698    def left(self, angle: int | float):
 699        """Turn turtle left by angle units.
 700
 701        Aliases: `left` | `lt`
 702
 703        Argument:
 704        `angle` -- a number (integer or float)
 705
 706        Turn turtle left by `angle` units. (Units are by default degrees,
 707        but can be set via the `degrees()` and `radians()` methods.)
 708        Angle orientation depends on mode.
 709
 710        **Example**
 711        ```python
 712        from ipycc.turtle import Turtle, showscreen
 713
 714        # Show the screen.
 715        showscreen()
 716
 717        # Create a turtle.
 718        t = Turtle()
 719
 720        # Print the turtle's heading before and after turning.
 721        print(t.heading()) # 22.0
 722        t.left(45)
 723        print(t.heading()) # 67.0
 724        ```
 725        """
 726        self._rotate(angle)
 727
 728    lt = left
 729
 730    def goto(self, x: int | float | tuple | Vec2D, y: int | float = None):
 731        """Move turtle to an absolute position.
 732
 733        Aliases: `setpos` | `setposition` | `goto`:
 734
 735        Arguments:
 736        - `x` -- a number or vector
 737        - `y` -- a number (optional)
 738
 739        Move turtle to an absolute position. If the pen is down,
 740        a line will be drawn. The turtle's orientation does not change.
 741
 742        **Example**
 743        ```python
 744        from ipycc.turtle import Turtle, showscreen
 745
 746        # Show the screen.
 747        showscreen()
 748
 749        # Create a turtle.
 750        t = Turtle()
 751
 752        # Print the turtle's position before and after moving.
 753        print(t.pos()) # (0.00, 0.00)
 754        t.goto(60, 30)
 755        print(t.pos()) # (60.00, 30.00)
 756        ```
 757        """
 758        if y is None:
 759            self._goto(Vec2D(*x))
 760        else:
 761            self._goto(Vec2D(x, y))
 762
 763    setpos = goto
 764    setposition = goto
 765
 766    def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None:
 767        """Instantly move turtle to an absolute position.
 768
 769        Arguments:
 770        - `x` -- a number      or     `None`
 771        - `y` -- a number             `None`
 772        - `fill_gap` -- a boolean     This argument must be specified by name.
 773
 774        Move turtle to an absolute position. Unlike `goto(x, y)`, a line will not
 775        be drawn. The turtle's orientation does not change. If currently
 776        filling, the polygon(s) teleported from will be filled after leaving,
 777        and filling will begin again after teleporting. This can be disabled
 778        with `fill_gap=True`, which makes the imaginary line traveled during
 779        teleporting act as a fill barrier like in `goto(x, y)`.
 780
 781        **Example**
 782        ```python
 783        from ipycc.turtle import Turtle, showscreen
 784
 785        # Show the screen.
 786        showscreen()
 787
 788        # Create a turtle.
 789        t = Turtle()
 790
 791        tp = t.pos()
 792        print(tp)      # (0.00,0.00)
 793        t.teleport(60)
 794        print(t.pos()) # (60.00,0.00)
 795        t.teleport(y=10)
 796        print(t.pos()) # (60.00,10.00)
 797        t.teleport(20, 30)
 798        print(t.pos()) # (20.00,30.00)
 799        ```
 800        """
 801        pendown = self.isdown()
 802        was_filling = self.filling()
 803        if pendown:
 804            self.penup()
 805        if was_filling and not fill_gap:
 806            self.end_fill()
 807        new_x = x if x is not None else self._position[0]
 808        new_y = y if y is not None else self._position[1]
 809        self._position = Vec2D(new_x, new_y)
 810        if pendown:
 811            self.pendown()
 812        if was_filling and not fill_gap:
 813            self.begin_fill()
 814        self._update()
 815
 816    def setx(self, x: int | float):
 817        """Set the turtle's first coordinate to `x`.
 818
 819        Argument:
 820        `x` -- a number (integer or float)
 821
 822        Set the turtle's first coordinate to `x`, leave second coordinate
 823        unchanged.
 824
 825        **Example**
 826        ```python
 827        from ipycc.turtle import Turtle, showscreen
 828
 829        # Show the screen.
 830        showscreen()
 831
 832        # Create a turtle.
 833        t = Turtle()
 834
 835        # Print the turtle's position before and after moving.
 836        print(t.position()) # (0.00, 240.00)
 837        t.setx(10)
 838        print(t.position()) # (10.00, 240.00)
 839        ```
 840        """
 841        self._goto(Vec2D(x, self._position[1]))
 842
 843    def sety(self, y: int | float):
 844        """Set the turtle's second coordinate to `y`.
 845
 846        Argument:
 847        `y` -- a number (integer or float)
 848
 849        Set the turtle's first coordinate to `x`, second coordinate remains
 850        unchanged.
 851
 852        **Example**
 853        ```python
 854        from ipycc.turtle import Turtle, showscreen
 855
 856        # Show the screen.
 857        showscreen()
 858
 859        # Create a turtle.
 860        t = Turtle()
 861
 862        # Print the turtle's position before and after moving.
 863        print(t.position()) # (0.00, 40.00)
 864        t.sety(-10)
 865        print(t.position()) # (0.00, -10.00)
 866        ```
 867        """
 868        self._goto(Vec2D(self._position[0], y))
 869
 870    def setheading(self, to_angle: int | float):
 871        """Set the orientation of the turtle to `to_angle`.
 872
 873        Aliases:  `setheading` | `seth`
 874
 875        Argument:
 876        `to_angle` -- a number (integer or float)
 877
 878        Set the orientation of the turtle to `to_angle`.
 879        Here are some common directions in degrees:
 880        - 0 - east
 881        - 90 - north
 882        - 180 - west
 883        - 270 - south
 884
 885        **Example**
 886        ```python
 887        from ipycc.turtle import Turtle, showscreen
 888
 889        # Show the screen.
 890        showscreen()
 891
 892        # Create a turtle.
 893        t = Turtle()
 894
 895        # Set the turtle's heading and print it.
 896        t.setheading(90)
 897        print(t.heading()) # 90
 898        ```
 899        """
 900        angle = (to_angle - self.heading()) * self._angleOrient
 901        full = self._fullcircle
 902        half = full / 2.0
 903        angle = (angle + half) % full - half
 904        self._rotate(angle)
 905
 906    seth = setheading
 907
 908    def home(self):
 909        """Move turtle to the origin - coordinates `(0,0)`.
 910
 911        No arguments.
 912
 913        Move turtle to the origin and reset its heading to 0.
 914
 915        **Example**
 916        ```python
 917        from ipycc.turtle import Turtle, showscreen
 918
 919        # Show the screen.
 920        showscreen()
 921
 922        # Create a turtle.
 923        t = Turtle()
 924
 925        # Move the turtle forward, then move it back home.
 926        t.forward(100)
 927        t.home()
 928        ```
 929        """
 930        self.goto(0, 0)
 931        self.setheading(0)
 932
 933    def dot(self, size: int = None, *color: str | tuple[int | float]):
 934        """Draw a dot with diameter size, using color.
 935
 936        Optional arguments:
 937        - `size` -- an integer >= 1 (if given)
 938        - `color` -- a colorstring or a numeric color tuple
 939
 940        Draw a circular dot with diameter size, using `color`.
 941        If `size` is not given, the maximum of `pensize+4` and `2*pensize` is
 942        used.
 943
 944        **Example**
 945        ```python
 946        from ipycc.turtle import Turtle, showscreen
 947
 948        # Show the screen.
 949        showscreen()
 950
 951        # Create a turtle.
 952        t = Turtle()
 953
 954        # Draw dots.
 955        t.dot()
 956        t.forward(50)
 957        t.dot(20, "blue")
 958        t.forward(50)
 959        ```
 960        """
 961        if not color:
 962            if isinstance(size, (str, tuple)):
 963                color = _SCREEN._colorstr(size)
 964                size = self._pensize + max(self._pensize, 4)
 965            else:
 966                color = self._pencolor
 967                if not size:
 968                    size = self._pensize + max(self._pensize, 4)
 969        else:
 970            if size is None:
 971                size = self._pensize + max(self._pensize, 4)
 972            color = _SCREEN._colorstr(color)
 973        self._pen.canvas.save()
 974        self._pen.no_stroke()
 975        self._pen.fill(color)
 976        x, y = self._to_screen_coords(self._position)
 977        self._pen.circle(x, y, size)
 978        self._pen.canvas.restore()
 979        self._update()
 980
 981    def stamp(self):
 982        """Stamp a copy of the turtleshape onto the canvas.
 983
 984        No argument.
 985
 986        Stamp a copy of the turtle shape onto the canvas at the current
 987        turtle position.
 988
 989        **Example**
 990        ```python
 991        from ipycc.turtle import Turtle, showscreen
 992
 993        # Show the screen.
 994        showscreen()
 995
 996        # Create a turtle.
 997        t = Turtle()
 998
 999        # Draw a stamp and move.
1000        t.color("blue")
1001        t.stamp()
1002        t.forward(50)
1003        ```
1004        """
1005        self._pen.canvas.save()
1006        x, y = self._to_screen_coords(self._position)
1007        self._pen.translate(x, y)
1008        angle = math.radians(self.heading()) - math.pi / 2
1009        self._pen.rotate(angle)
1010        self._pen.stroke(self._pencolor)
1011        self._pen.stroke_weight(self._outlinewidth)
1012        self._pen.fill(self._fillcolor)
1013        self._pen.begin_shape()
1014        shape = _turtle_shapes[self._shape]
1015        for v in shape:
1016            sx, sy = self._stretchfactor
1017            self._pen.vertex(sx * v[0], sy * v[1])
1018        self._pen.end_shape()
1019        self._pen.reset_matrix()
1020        self._pen.canvas.restore()
1021        self._update()
1022
1023    def speed(self, speed: int | float | str = None) -> None | int:
1024        """Return or set the turtle's speed.
1025
1026        Optional argument:
1027        `speed` -- an integer in the range `0..10` or a `speedstring`
1028        (see below)
1029
1030        Set the turtle's speed to an integer value in the range `0..10`.
1031        If no argument is given: return current speed.
1032
1033        If input is a number greater than 10 or smaller than 0.5,
1034        speed is set to 0.
1035        Speedstrings  are mapped to speedvalues in the following way:
1036        - `'fastest'` :  0
1037        - `'fast'`    :  10
1038        - `'normal'`  :  6
1039        - `'slow'`    :  3
1040        - `'slowest'` :  1
1041        speeds from 1 to 10 enforce increasingly faster animation of
1042        line drawing and turtle turning.
1043
1044        Attention:
1045        `speed = 0` : *no* animation takes place. forward/back makes turtle jump
1046        and likewise left/right make the turtle turn instantly.
1047
1048        **Example**
1049        ```python
1050        from ipycc.turtle import Turtle, showscreen
1051
1052        # Show the screen.
1053        showscreen()
1054
1055        # Create a turtle.
1056        t = Turtle()
1057
1058        # Set the turtle's speed.
1059        t.speed(3)
1060        ```
1061        """
1062        speeds = {"fastest": 0, "fast": 10, "normal": 6, "slow": 3, "slowest": 1}
1063        if speed is None:
1064            return self._speed
1065        if speed in speeds:
1066            speed = speeds[speed]
1067        elif 0.5 < speed < 10.5:
1068            speed = int(round(speed))
1069        else:
1070            speed = 0
1071        self._speed = speed
1072
1073    def position(self) -> Vec2D:
1074        """Return the turtle's current location `(x,y)`, as a `Vec2D`.
1075
1076        Aliases: `pos` | `position`
1077
1078        No arguments.
1079
1080        **Example**
1081        ```python
1082        from ipycc.turtle import Turtle, showscreen
1083
1084        # Show the screen.
1085        showscreen()
1086
1087        # Create a turtle.
1088        t = Turtle()
1089
1090        # Print the turtle's position.
1091        print(t.pos()) # (0.00, 0.00)
1092        ```
1093        """
1094        return self._position
1095
1096    pos = position
1097
1098    def towards(self, x: int | float | tuple | Vec2D, y: int | float = None) -> float:
1099        """Return the angle of the line from the turtle's position to `(x,y)`.
1100
1101        Arguments:
1102        - `x` -- a number   or  a pair/vector of numbers   or   a turtle instance
1103        - `y` -- a number (optional)
1104
1105        Return the angle, between the line from turtle-position to position
1106        specified by `x`, `y` and the turtle's start orientation.
1107
1108        **Example**
1109        ```python
1110        from ipycc.turtle import Turtle, showscreen, Vec2D
1111
1112        # Show the screen.
1113        showscreen()
1114
1115        # Create a turtle.
1116        t = Turtle()
1117
1118        # Print the turtle's position and heading.
1119        print(t.pos()) # (10.00, 10.00)
1120        print(t.towards(0, 0)) # 225.0
1121        print(t.towards((0, 0))) # 225.0
1122        v = Vec2D(0, 0)
1123        print(t.towards(v)) # 225.0
1124        ```
1125        """
1126        if y is not None:
1127            pos = Vec2D(x, y)
1128        if isinstance(x, Vec2D):
1129            pos = x
1130        elif isinstance(x, tuple):
1131            pos = Vec2D(*x)
1132        elif isinstance(x, Turtle):
1133            pos = x._position
1134        x, y = pos - self._position
1135        result = round(math.degrees(math.atan2(y, x)), 10) % 360.0
1136        result /= self._degreesPerAU
1137        return (self._angleOffset + self._angleOrient * result) % self._fullcircle
1138
1139    def xcor(self) -> float:
1140        """Return the turtle's x coordinate.
1141
1142        No arguments.
1143
1144        **Example**
1145        ```python
1146        from ipycc.turtle import Turtle, showscreen
1147
1148        # Show the screen.
1149        showscreen()
1150
1151        # Create a turtle.
1152        t = Turtle()
1153
1154        # Move the turtle and print its x-coordinate.
1155        t.left(60)
1156        t.forward(100)
1157        print(tutrtle.xcor()) # 50.0
1158        ```
1159        """
1160        return self._position[0]
1161
1162    def ycor(self) -> float:
1163        """Return the turtle's y coordinate.
1164
1165        No arguments.
1166
1167        **Example**
1168        ```python
1169        from ipycc.turtle import Turtle, showscreen
1170
1171        # Show the screen.
1172        showscreen()
1173
1174        # Create a turtle.
1175        t = Turtle()
1176
1177        # Move the turtle and print its y-coordinate.
1178        t.left(60)
1179        t.forward(100)
1180        print(t.ycor()) # 86.6025403784
1181        ```
1182        """
1183        return self._position[1]
1184
1185    def heading(self) -> float:
1186        """Return the turtle's current heading.
1187
1188        No arguments.
1189
1190        **Example**
1191        ```python
1192        from ipycc.turtle import Turtle, showscreen
1193
1194        # Show the screen.
1195        showscreen()
1196
1197        # Create a turtle.
1198        t = Turtle()
1199
1200        # Turn the turtle and print its heading.
1201        t.left(67)
1202        print(t.heading()) # 67.0
1203        ```
1204        """
1205        x, y = self._orient
1206        result = round(math.degrees(math.atan2(y, x)), 10) % 360.0
1207        result /= self._degreesPerAU
1208        return (self._angleOffset + self._angleOrient*result) % self._fullcircle
1209
1210    def distance(self, x, y: int | float = None) -> float:
1211        """Return the distance from the turtle to `(x,y)` in turtle step units.
1212
1213        Arguments:
1214        - `x` -- a number or a pair/vector of numbers or a `Turtle` instance
1215        - `y` -- a number (optional)
1216
1217        **Example**
1218        ```python
1219        from ipycc.turtle import Turtle, showscreen
1220
1221        # Show the screen.
1222        showscreen()
1223
1224        # Create a turtle.
1225        t = Turtle()
1226
1227        # Print the turtle's position and distance to a point.
1228        print(t.pos()) # (0.00, 0.00)
1229        print(t.distance(30, 40)) # 50.0
1230
1231        # Create another turtle.
1232        t2 = Turtle()
1233
1234        # Move the second turtle and print its distance from
1235        # the first turtle.
1236        t2.forward(77)
1237        print(t.distance(t2)) # 77.0
1238        ```
1239        """
1240        if y is not None:
1241            pos = Vec2D(x, y)
1242        if isinstance(x, Vec2D):
1243            pos = x
1244        elif isinstance(x, tuple):
1245            pos = Vec2D(*x)
1246        elif isinstance(x, Turtle):
1247            pos = x._position
1248        return abs(pos - self._position)
1249
1250    def _setDegreesPerAU(self, fullcircle):
1251        """Helper function for degrees() and radians()"""
1252        self._fullcircle = fullcircle
1253        self._degreesPerAU = 360/fullcircle
1254        self._angleOffset = 0
1255
1256    def degrees(self, fullcircle: int | float = 360.0):
1257        """Set angle measurement units to degrees.
1258
1259        Optional argument:
1260        `fullcircle` -  a number
1261
1262        Set angle measurement units, i. e. set number
1263        of 'degrees' for a full circle. Default value is
1264        360 degrees.
1265
1266        **Example**
1267        ```python
1268        from ipycc.turtle import Turtle, showscreen
1269
1270        # Show the screen.
1271        showscreen()
1272
1273        # Create a turtle.
1274        t = Turtle()
1275
1276        # Turn the turtle and print its heading.
1277        t.left(90)
1278        print(t.heading()) # 90
1279
1280        # Change angle measurement unit to grad (also known as gon,
1281        # grade, or gradian and equals 1/100-th of the right angle.)
1282        t.degrees(400.0)
1283        print(t.heading()) # 100
1284        ```
1285        """
1286        self._setDegreesPerAU(fullcircle)
1287
1288    def radians(self):
1289        """Set the angle measurement units to radians.
1290
1291        No arguments.
1292
1293        **Example**
1294        ```python
1295        from ipycc.turtle import Turtle, showscreen
1296
1297        # Show the screen.
1298        showscreen()
1299
1300        # Create a turtle.
1301        t = Turtle()
1302
1303        # Print the turtle's heading in degrees and radians.
1304        print(t.heading()) # 90
1305        t.radians()
1306        print(t.heading()) # 1.5707963267948966
1307        ```
1308        """
1309        self._setDegreesPerAU(math.tau)
1310
1311    # ========================================
1312    #               Pen Control
1313    # ========================================
1314
1315    def pendown(self):
1316        """Pull the pen down -- drawing when moving.
1317
1318        Aliases: `pendown` | `pd` | `down`
1319
1320        No argument.
1321
1322        **Example**
1323        ```python
1324        from ipycc.turtle import Turtle, showscreen
1325
1326        # Show the screen.
1327        showscreen()
1328
1329        # Create a turtle.
1330        t = Turtle()
1331
1332        # Put the turtle's pen down and move.
1333        t.pendown()
1334        t.forward(100)
1335        ```
1336        """
1337        self._drawing = True
1338
1339    pd = pendown
1340    down = pendown
1341
1342    def penup(self):
1343        """Pull the pen up -- no drawing when moving.
1344
1345        Aliases: `penup` | `pu` | `up`
1346
1347        No argument
1348
1349        **Example**
1350        ```python
1351        from ipycc.turtle import Turtle, showscreen
1352
1353        # Show the screen.
1354        showscreen()
1355
1356        # Create a turtle.
1357        t = Turtle()
1358
1359        # Pick the turtle's pen up and move.
1360        t.penup()
1361        t.forward(100)
1362        ```
1363        """
1364        self._drawing = False
1365
1366    pu = penup
1367    up = penup
1368
1369    def pensize(self, width: int | float = None) -> None | float:
1370        """Set or return the line thickness.
1371
1372        Aliases:  `pensize` | `width`
1373
1374        Argument:
1375        `width` -- positive number
1376
1377        Set the line thickness to `width` or return it. If no argument is
1378        given, current pensize is returned.
1379
1380        **Example**
1381        ```python
1382        from ipycc.turtle import Turtle, showscreen
1383
1384        # Show the screen.
1385        showscreen()
1386
1387        # Create a turtle.
1388        t = Turtle()
1389
1390        # Print the turtle's pen size and move.
1391        print(t.pensize()) # 1
1392        t.forward(50)
1393
1394        # Change the turtle's pen size and move.
1395        t.pensize(10)   # from here on lines of width 10 are drawn
1396        t.forward(50)
1397        ```
1398        """
1399        if width is None:
1400            return self._pensize
1401        self._pensize = width
1402        self._pen.stroke_weight(self._pensize)
1403
1404    width = pensize
1405
1406    def isdown(self) -> bool:
1407        """Return `True` if pen is down, `False` if it's up.
1408
1409        No argument.
1410
1411        **Example**
1412        ```python
1413        from ipycc.turtle import Turtle, showscreen
1414
1415        # Show the screen.
1416        showscreen()
1417
1418        # Create a turtle.
1419        t = Turtle()
1420
1421        # Pick the turtle's pen up and print its state.
1422        t.penup()
1423        print(t.isdown()) # False
1424        # Put the turtle's pen down and print its state.
1425        t.pendown()
1426        print(t.isdown()) # True
1427        ```
1428        """
1429        return self._drawing
1430
1431    def color(self, *args) -> None | str | tuple:
1432        """Return or set the pencolor and fillcolor.
1433
1434        Arguments:
1435        Several input formats are allowed.
1436        They use 0, 1, 2, or 3 arguments as follows:
1437
1438        - `color()` returns the current pencolor and the current fillcolor
1439        as a pair of color specification strings.
1440        - `color(colorstring)`, `color((r,g,b))`, `color(r,g,b)` sets both
1441        `fillcolor()` and `pencolor()` to the given value.
1442        - `color(colorstring1, colorstring2)`, `color((r1,g1,b1), (r2,g2,b2))`
1443        sets `pencolor(colorstring1)` and `fillcolor(colorstring2)` or
1444        `pencolor((r1,g1,b1))` and `fillcolor((r2,g2,b2))`.
1445
1446        If turtleshape is a polygon, outline and interior of that polygon
1447        is drawn with the newly set colors.
1448
1449        For more info see: `pencolor()`, `fillcolor()`
1450
1451        **Example**
1452        ```python
1453        from ipycc.turtle import Turtle, showscreen
1454
1455        # Show the screen.
1456        showscreen()
1457
1458        # Create a turtle.
1459        t = Turtle()
1460
1461        # Set the turtle's pen and fill color, then print them.
1462        t.color('red', 'green')
1463        print(t.color()) # ('red', 'green')
1464        # Change the color mode.
1465        t.colormode(255)
1466        # Set the turtle's pen and fill color, then print them.
1467        t.color((40, 80, 120), (160, 200, 240))
1468        print(t.color()) # ('#285078', '#a0c8f0')
1469        ```
1470        """
1471        if args:
1472            l = len(args)
1473            if l == 1:
1474                pcolor = fcolor = args[0]
1475            elif l == 2:
1476                pcolor, fcolor = args
1477            elif l == 3:
1478                pcolor = fcolor = args
1479            pcolor = _SCREEN._colorstr(pcolor)
1480            fcolor = _SCREEN._colorstr(fcolor)
1481            self._pencolor = pcolor
1482            self._pen.stroke(self._pencolor)
1483            self._pen.stroke_weight(self._pensize)
1484            self._fillcolor = fcolor
1485            self._pen.fill(self._fillcolor)
1486            self._update()
1487        else:
1488            return _SCREEN._color(self._pencolor), _SCREEN._color(self._fillcolor)
1489
1490    def pencolor(self, *args) -> None | str | tuple:
1491        """ Return or set the pencolor.
1492
1493        Arguments:
1494        Four input formats are allowed:
1495          - `pencolor()`
1496            Return the current pencolor as color specification string,
1497            possibly in hex-number format (see example).
1498            May be used as input to another color/pencolor/fillcolor call.
1499          - `pencolor(colorstring)`
1500            a [Tk color specification string](https://www.tcl-lang.org/man/tcl8.4/TkCmd/colors.htm),
1501            such as `"red"` or `"yellow"`
1502          - `pencolor((r, g, b))`
1503            *a tuple* of `r`, `g`, and `b`, which represent, an RGB color,
1504            and each of `r`, `g`, and `b` are in the range `0..colormode`,
1505            where `colormode` is either 1.0 or 255
1506          - `pencolor(r, g, b)`
1507            `r`, `g`, and `b` represent an RGB color, and each of `r`, `g`,
1508            and `b` are in the range `0..colormode`
1509
1510        If turtleshape is a polygon, the outline of that polygon is drawn
1511        with the newly set pencolor.
1512
1513        **Example**
1514        ```python
1515        from ipycc.turtle import Turtle, showscreen
1516
1517        # Show the screen.
1518        showscreen()
1519
1520        # Create a turtle.
1521        t = Turtle()
1522
1523        # Set the turtle's pen color to brown, then print it.
1524        t.pencolor('brown')
1525        print(t.pencolor()) # 'brown'
1526        # Set the turtle's pen color using a tuple, then print it.
1527        tup = (0.2, 0.8, 0.55)
1528        t.pencolor(tup)
1529        print(t.pencolor()) # '#33cc8c'
1530        ```
1531        """
1532        if args:
1533            color = _SCREEN._colorstr(args)
1534            if color == self._pencolor:
1535                return
1536            self._pencolor = color
1537            self._pen.stroke(self._pencolor)
1538            self._pen.stroke_weight(self._pensize)
1539            self._update()
1540        else:
1541            return _SCREEN._color(self._pencolor)
1542
1543    def fillcolor(self, *args) -> None | str | tuple:
1544        """Return or set the fillcolor.
1545
1546        Arguments:
1547        Four input formats are allowed:
1548          - `fillcolor()`
1549            Return the current fillcolor as color specification string,
1550            possibly in hex-number format (see example).
1551            May be used as input to another color/pencolor/fillcolor call.
1552          - `fillcolor(colorstring)`
1553            a [Tk color specification string](https://www.tcl-lang.org/man/tcl8.4/TkCmd/colors.htm),
1554            such as `"red"` or `"yellow"`
1555          - `fillcolor((r, g, b))`
1556            *a tuple* of `r`, `g`, and `b`, which represent, an RGB color,
1557            and each of `r`, `g`, and `b` are in the range `0..colormode`,
1558            where `colormode` is either 1.0 or 255
1559          - `fillcolor(r, g, b)`
1560            `r`, `g`, and `b` represent an RGB color, and each of `r`, `g`, and `b`
1561            are in the range `0..colormode`
1562
1563        If turtleshape is a polygon, the interior of that polygon is drawn
1564        with the newly set fillcolor.
1565
1566        **Example**
1567        ```python
1568        from ipycc.turtle import Turtle, showscreen
1569
1570        # Show the screen.
1571        showscreen()
1572
1573        # Create a turtle.
1574        t = Turtle()
1575
1576        # Set the turtle's fill color to violet.
1577        t.fillcolor('violet')
1578        # Set the turtle's fill color to its pen color.
1579        col = t.pencolor()
1580        t.fillcolor(col)
1581        # Set the turtle's fill color using RGB values.
1582        t.fillcolor(0, 0.5, 0)
1583        ```
1584        """
1585        if args:
1586            color = _SCREEN._colorstr(args)
1587            if color == self._fillcolor:
1588                return
1589            self._fillcolor = color
1590            self._pen.fill(self._fillcolor)
1591            self._update()
1592        else:
1593            return _SCREEN._color(self._fillcolor)
1594
1595    def filling(self) -> bool:
1596        """Return fillstate (`True` if filling, `False` otherwise).
1597
1598        No argument.
1599
1600        **Example**
1601        ```python
1602        from ipycc.turtle import Turtle, showscreen
1603
1604        # Show the screen.
1605        showscreen()
1606
1607        # Create a turtle.
1608        t = Turtle()
1609
1610        # Begin filling.
1611        t.begin_fill()
1612        # Change the turtle's pen size if it is filling.
1613        if t.filling():
1614            t.pensize(5)
1615        else:
1616            t.pensize(3)
1617        ```
1618        """
1619        return isinstance(self._fillpath, list)
1620
1621    @contextmanager
1622    def fill(self):
1623        """A context manager for filling a shape.
1624
1625        No argument.
1626
1627        Implicitly ensures the code block is wrapped with
1628        `begin_fill()` and `end_fill()`.
1629
1630        **Example**
1631        ```python
1632        from ipycc.turtle import Turtle, showscreen
1633
1634        # Show the screen.
1635        showscreen()
1636
1637        # Create a turtle.
1638        t = Turtle()
1639        t.color("black", "red")
1640
1641        # Fill.
1642        with t.fill():
1643            t.circle(60)
1644        ```
1645        """
1646        self.begin_fill()
1647        try:
1648            yield
1649        finally:
1650            self.end_fill()
1651
1652    def begin_fill(self):
1653        """Called just before drawing a shape to be filled.
1654
1655        No argument.
1656
1657        **Example**
1658        ```python
1659        from ipycc.turtle import Turtle, showscreen
1660
1661        # Show the screen.
1662        showscreen()
1663
1664        # Create a turtle.
1665        t = Turtle()
1666
1667        # Set the turtle's pen and fill colors.
1668        t.color("black", "red")
1669
1670        # Begin filling.
1671        t.begin_fill()
1672        t.circle(60)
1673        # Stop filling.
1674        t.end_fill()
1675        ```
1676        """
1677        self._fillpath = [self._position]
1678
1679    def end_fill(self):
1680        """Fill the shape drawn after the call `begin_fill()`.
1681
1682        No argument.
1683
1684        **Example**
1685        ```python
1686        from ipycc.turtle import Turtle, showscreen
1687
1688        # Show the screen.
1689        showscreen()
1690
1691        # Create a turtle.
1692        t = Turtle()
1693
1694        # Set the turtle's pen and fill color.
1695        t.color("black", "red")
1696    
1697        # Begin filling.
1698        t.begin_fill()
1699        t.circle(60)
1700        # Stop filling.
1701        t.end_fill()
1702        ```
1703        """
1704        if self.filling():
1705            if len(self._fillpath) > 2:
1706                self._pen.begin_shape()
1707                for v in self._fillpath:
1708                    x, y = self._to_screen_coords(v)
1709                    self._pen.vertex(x, y)
1710                self._pen.end_shape()
1711            self._fillpath = None
1712            self._update()
1713
1714    @contextmanager
1715    def poly(self):
1716        """A context manager for recording the vertices of a polygon.
1717
1718        No argument.
1719
1720        Implicitly ensures that the code block is wrapped with
1721        `begin_poly()` and `end_poly()`
1722
1723        **Example**
1724        ```python
1725        from ipycc.turtle import Turtle, showscreen
1726
1727        # Show the screen.
1728        showscreen()
1729
1730        # Create a turtle.
1731        t = Turtle()
1732
1733        # Set the turtle's pen and fill color.
1734        t.color("black", "red")
1735
1736        # Begin filling.
1737        t.begin_fill()
1738
1739        # Create a polygon.
1740        with t.poly():
1741            for i in range(4):
1742                t.forward(50)
1743                t.left(90)
1744        
1745        # Stop filling.
1746        t.end_fill()
1747        ```
1748        """
1749        self.begin_poly()
1750        try:
1751            yield
1752        finally:
1753            self.end_poly()
1754
1755    def begin_poly(self):
1756        """Start recording the vertices of a polygon.
1757
1758        No argument.
1759
1760        Start recording the vertices of a polygon. Current turtle position
1761        is first point of polygon.
1762
1763        **Example**
1764        ```python
1765        from ipycc.turtle import Turtle, showscreen
1766
1767        # Show the screen.
1768        showscreen()
1769
1770        # Create a turtle.
1771        t = Turtle()
1772
1773        # Set the turtle's pen and fill color.
1774        t.color("black", "red")
1775
1776        # Begin filling.
1777        t.begin_fill()
1778
1779        # Begin creating a polygon.
1780        t.begin_poly()
1781        for i in range(4):
1782            t.forward(50)
1783            t.left(90)
1784
1785        # Stop creating a polygon.
1786        t.end_poly()
1787
1788        # Stop filling.
1789        t.end_fill()
1790        ```
1791        """
1792        self._poly = [self._position]
1793        self._creatingPoly = True
1794
1795    def end_poly(self):
1796        """Stop recording the vertices of a polygon.
1797
1798        No argument.
1799
1800        Stop recording the vertices of a polygon. Current turtle position is
1801        last point of polygon. This will be connected with the first point.
1802
1803        **Example**
1804        ```python
1805        from ipycc.turtle import Turtle, showscreen
1806
1807        # Show the screen.
1808        showscreen()
1809
1810        # Create a turtle.
1811        t = Turtle()
1812
1813        # Set the turtle's pen and fill color.
1814        t.color("black", "red")
1815    
1816        # Begin filling.
1817        t.begin_fill()
1818    
1819        # Begin creating a polygon.
1820        t.begin_poly()
1821        for i in range(4):
1822            t.forward(50)
1823            t.left(90)
1824
1825        # Stop creating a polygon.
1826        t.end_poly()
1827
1828        # Stop filling.
1829        t.end_fill()
1830        ```
1831        """
1832        self._creatingPoly = False
1833
1834    def circle(
1835        self, radius: int | float, extent: int | float = None, steps: int = None
1836    ):
1837        """Draw a circle with given radius.
1838
1839        Arguments:
1840        - `radius` -- a number
1841        - `extent` (optional) -- a number
1842        - `steps` (optional) -- an integer
1843
1844        Draw a circle with given radius. The center is `radius` units left
1845        of the turtle; `extent` - an angle - determines which part of the
1846        circle is drawn. If `extent` is not given, draw the entire circle.
1847        If `extent` is not a full circle, one endpoint of the arc is the
1848        current pen position. Draw the arc in counterclockwise direction
1849        if `radius` is positive, otherwise in clockwise direction. Finally
1850        the direction of the turtle is changed by the amount of extent.
1851
1852        As the circle is approximated by an inscribed regular polygon,
1853        `steps` determines the number of steps to use. If not given,
1854        it will be calculated automatically. May be used to draw regular
1855        polygons.
1856
1857        **Example**
1858        ```python
1859        from ipycc.turtle import Turtle, showscreen
1860
1861        # Show the screen.
1862        showscreen()
1863
1864        # Create a turtle.
1865        t = Turtle()
1866
1867        t.circle(50)
1868        t.circle(120, 180)  # semicircle
1869        ```
1870        """
1871        speed = self.speed()
1872        if extent is None:
1873            extent = self._fullcircle
1874        if steps is None:
1875            frac = abs(extent) / self._fullcircle
1876            steps = 1+int(min(11+abs(radius)/6.0, 59.0)*frac)
1877        w = 1.0 * extent / steps
1878        w2 = 0.5 * w
1879        l = 2.0 * radius * math.sin(math.radians(w2)*self._degreesPerAU)
1880        if radius < 0:
1881            l, w, w2 = -l, -w, -w2
1882        tr = tracer()
1883        dl = delay()
1884        if speed == 0:
1885            tracer(0, 0)
1886        else:
1887            self.speed(0)
1888        self._rotate(w2)
1889        for i in range(steps):
1890            self.speed(speed)
1891            self._go(l)
1892            self.speed(0)
1893            self._rotate(w)
1894        self._rotate(-w2)
1895        if speed == 0:
1896            tracer(tr, dl)
1897        self.speed(speed)
1898
1899    def reset(self):
1900        """Return the turtle to its initial state and clear its drawings from
1901        the screen.
1902
1903        No arguments.
1904
1905        **Example**
1906        ```python
1907        from ipycc.turtle import Turtle, showscreen
1908
1909        # Show the screen.
1910        showscreen()
1911
1912        # Create a turtle.
1913        t = Turtle()
1914
1915        # Move the turtle forward.
1916        t.forward(50)
1917
1918        # Reset the turtle.
1919        t.reset()
1920        ```
1921        """
1922        self._drawing = True
1923        self._pencolor = "black"
1924        self._pensize = 1
1925        self._pen.stroke(self._pencolor)
1926        self._pen.stroke_weight(self._pensize)
1927        self._speed = 3
1928        self._shown = True
1929        self._fillcolor = "black"
1930        self._is_filling = False
1931        self._poly = []
1932        self._fillpath = None
1933        self._pen.no_fill()
1934        self._creatingPoly = False
1935        self._position = Vec2D(0, 0)
1936        self._shape = "classic"
1937        self._stretchfactor = (1.0, 1.0)
1938        self._shearfactor = 0.0
1939        self._tilt = 0.0
1940        self._outlinewidth = 1
1941        self._orient = Vec2D(1, 0)
1942        self._angleOrient = 1.0
1943        self.degrees()
1944        self.clear()
1945        self.home()
1946
1947    def clear(self):
1948        """Delete the turtle's drawings from the screen. Do not move turtle.
1949
1950        No arguments.
1951
1952        Delete the turtle's drawings from the screen. Do not move turtle.
1953        State and position of the turtle as well as drawings of other
1954        turtles are not affected.
1955
1956        **Example**
1957        ```python
1958        from ipycc.turtle import Turtle, showscreen
1959
1960        # Show the screen.
1961        showscreen()
1962
1963        # Create a turtle.
1964        t = Turtle()
1965
1966        # Move the turtle forward.
1967        t.forward(50)
1968
1969        # Clear the turtle's drawings.
1970        t.clear()
1971        ```
1972        """
1973        self._pen.clear()
1974        self._update()
1975
1976    def _write(self, txt: str, align: str, fontname: str, fontsize: int | float, fonttype: str):
1977        """Performs the writing for write()
1978        """
1979        self._pen.canvas.save()
1980        self._pen.scale(1, -1)
1981        self._pen.translate(0, -self._pen.height)
1982        x, y = self._to_screen_coords(self._position)
1983        self._pen.fill(self._pencolor)
1984        self._pen.no_stroke()
1985        self._pen.text_align(align)
1986        self._pen.text_font(fontname)
1987        self._pen.text_size(fontsize)
1988        self._pen.text_style(fonttype)
1989        self._pen.text(txt, x, self._pen.height - y)
1990        self._pen.canvas.restore()
1991        self._update()
1992
1993    def write(self, arg, align: str = "left", font: tuple = ("Arial", 8, "normal")):
1994        """Write text at the current turtle position.
1995
1996        Arguments:
1997        - `arg` -- info, which is to be written to the screen
1998        - `align` (optional) -- one of the strings `"left"`, `"center"` or
1999        `"right"`
2000        - `font` (optional) -- a triple (fontname, fontsize, fonttype)
2001
2002        Write text - the string representation of `arg` - at the current
2003        turtle position according to align (`"left"`, `"center"` or `"right"`)
2004        and with the given font.
2005
2006        **Example**
2007        ```python
2008        from ipycc.turtle import Turtle, showscreen
2009
2010        # Show the screen.
2011        showscreen()
2012
2013        # Create a turtle.
2014        t = Turtle()
2015
2016        # Write messages to the screen.
2017        t.write('Home = ', align="center")
2018        t.write((0, 0))
2019        ```
2020        """
2021        fontname, fontsize, fonttype = font
2022        if not align.lower() in (Sketch.LEFT, Sketch.CENTER, Sketch.RIGHT):
2023            raise TurtleGraphicsError('Invalid text alignment. Must be "left", "center", or "right".')
2024        if not isinstance(fontsize, (int, float)):
2025            raise TurtleGraphicsError('Font size must be a number.')
2026        if not fonttype in (Sketch.NORMAL, Sketch.ITALIC, Sketch.BOLD, Sketch.BOLDITALIC):
2027            raise TurtleGraphicsError('Invalid font type. Must be "normal", "italic", "bold", or "bolditalic".')
2028        self._write(str(arg), align.lower(), fontname, fontsize, fonttype)
2029
2030    # ========================================
2031    #             Turtle State
2032    # ========================================
2033
2034    def showturtle(self):
2035        """Make the turtle visible.
2036
2037        Aliases:  `showturtle` | `st`
2038
2039        **Example**
2040        ```python
2041        from ipycc.turtle import Turtle, showscreen
2042
2043        # Show the screen.
2044        showscreen()
2045
2046        # Create a turtle.
2047        t = Turtle()
2048
2049        # Hide the turtle.
2050        t.hideturtle()
2051
2052        # Show the turtle.
2053        t.showturtle()
2054        ```
2055        """
2056        self._shown = True
2057        self._update()
2058
2059    st = showturtle
2060
2061    def hideturtle(self):
2062        """Make the turtle invisible.
2063
2064        Aliases:  `hideturtle` | `ht`
2065
2066        **Example**
2067        ```python
2068        from ipycc.turtle import Turtle, showscreen
2069
2070        # Show the screen.
2071        showscreen()
2072
2073        # Create a turtle.
2074        t = Turtle()
2075
2076        # Hide the turtle.
2077        t.hideturtle()
2078
2079        # Show the turtle.
2080        t.showturtle()
2081        ```
2082        """
2083        self._shown = False
2084        self._update()
2085
2086    ht = hideturtle
2087
2088    def isvisible(self) -> bool:
2089        """Return `True` if the turtle is shown, `False` if it's hidden.
2090
2091        **Example**
2092        ```python
2093        from ipycc.turtle import Turtle, showscreen
2094
2095        # Show the screen.
2096        showscreen()
2097
2098        # Create a turtle.
2099        t = Turtle()
2100
2101        # Hide the turtle and print whether it is visible.
2102        t.hideturtle()
2103        print(t.isvisible()) # False
2104        # Show the turtle and print whether it is visible.
2105        t.showturtle()
2106        print(t.isvisible()) # True
2107        ```
2108        """
2109        return self._shown
2110
2111    def shape(self, name: str = None) -> None | str:
2112        """Set turtle shape to shape with given name / return current shapename.
2113
2114        Optional argument:
2115        `name` -- a string, which is a valid shapename
2116
2117        Set turtle shape to shape with given `name` or, if `name` is not given,
2118        return name of current shape.
2119        Valid shapenames are:
2120        - `"arrow"`
2121        - `"turtle"`
2122        - `"circle"`
2123        - `"square"`
2124        - `"triangle"`
2125        - `"classic"`
2126
2127        ```python
2128        from ipycc.turtle import Turtle, showscreen
2129
2130        # Show the screen.
2131        showscreen()
2132
2133        # Create a turtle.
2134        t = Turtle()
2135
2136        # Print the turtle's default shape.
2137        print(t.shape()) # 'arrow'
2138
2139        # Change the turtle's shape and print it.
2140        t.shape("turtle")
2141        print(t.shape()) # 'turtle'
2142        ```
2143        """
2144        if name is None:
2145            return self._shape
2146        if not name in _turtle_shapes:
2147            raise NameError("There is no shape named %s" % name)
2148        self._shape = name
2149        self._update()
2150
2151    def shapesize(
2152        self, stretch_wid: int | float = None, stretch_len: int | float = None
2153    ) -> float:
2154        """Set/return turtle's stretchfactors/outline. Set resizemode to "user".
2155
2156        Optional arguments:
2157        - `stretch_wid` : positive number
2158        - `stretch_len` : positive number
2159        - `outline`  : positive number
2160
2161        Return or set the pen's attributes x/y-stretchfactors and/or outline.
2162        The turtle will be displayed stretched according to its stretchfactors:
2163        - `stretch_wid` is stretchfactor perpendicular to orientation.
2164        - `stretch_len` is stretchfactor in direction of the turtle's orientation.
2165        - `outline` determines the width of the shapes's outline.
2166
2167        ```python
2168        from ipycc.turtle import Turtle, showscreen
2169
2170        # Show the screen.
2171        showscreen()
2172
2173        # Create a turtle.
2174        t = Turtle()
2175
2176        # Change the turtle's shape size.
2177        t.shapesize(5, 5, 12)
2178        t.shapesize(outline=8)
2179        ```
2180        """
2181        if stretch_wid is stretch_len is None:
2182            return self._stretchfactor
2183        if stretch_wid == 0 or stretch_len == 0:
2184            raise TurtleGraphicsError("stretch_wid/stretch_len must not be zero")
2185        if stretch_wid is not None:
2186            if stretch_len is None:
2187                self._stretchfactor = stretch_wid, stretch_wid
2188            else:
2189                self._stretchfactor = stretch_wid, stretch_len
2190        elif stretch_len is not None:
2191            self._stretchfactor = self._stretchfactor[0], stretch_len
2192        else:
2193            self._stretchfactor = self._stretchfactor
2194        self._update()
2195
2196    def shearfactor(self, shear: int | float = None) -> None | float:
2197        """Set or return the current shearfactor.
2198
2199        Optional argument: `shear` -- number, tangent of the shear angle
2200
2201        Shear the turtleshape according to the given shearfactor `shear`,
2202        which is the tangent of the shear angle. Doesn't change the
2203        turtle's heading (direction of movement).
2204        If `shear` is not given: return the current shearfactor, i. e. the
2205        tangent of the shear angle, by which lines parallel to the
2206        heading of the turtle are sheared.
2207
2208        ```python
2209        from ipycc.turtle import Turtle, showscreen
2210
2211        # Show the screen.
2212        showscreen()
2213
2214        # Create a turtle.
2215        t = Turtle()
2216
2217        # Set the turtle's shape and size.
2218        t.shape("circle")
2219        t.shapesize(5, 2)
2220
2221        # Set the turtle's shear factor and print it.
2222        t.shearfactor(0.5)
2223        print(t.shearfactor()) # 0.5
2224        ```
2225        """
2226        if shear is None:
2227            return self._shearfactor
2228        self._shearfactor = shear
2229
2230    def tiltangle(self, angle: int | float = None) -> None | float:
2231        """Set or return the current tilt-angle.
2232
2233        Optional argument: `angle` -- number
2234
2235        Rotate the turtleshape to point in the direction specified by `angle`,
2236        regardless of its current tilt-angle. Doesn't change the turtle's
2237        heading (direction of movement).
2238        If `angle` is not given: return the current tilt-angle, i. e. the angle
2239        between the orientation of the turtleshape and the heading of the
2240        turtle (its direction of movement).
2241
2242        **Example**
2243        ```python
2244        from ipycc.turtle import Turtle, showscreen
2245
2246        # Show the screen.
2247        showscreen()
2248
2249        # Create a turtle.
2250        t = Turtle()
2251
2252        # Set the turtle's shape and size.
2253        t.shape("circle")
2254        t.shapesize(5, 2)
2255
2256        # Print the turtle's tilt angle.
2257        print(t.tiltangle()) # 0.0
2258
2259        # Tilt the turtle and print the angle.
2260        t.tiltangle(45)
2261        print(t.tiltangle()) # 45.0
2262
2263        # Stamp the turtle's shape.
2264        t.stamp()
2265        
2266        # Move the turtle forward.
2267        t.forward(50)
2268    
2269        #  Tilt the turtle back to its original angle and print it.
2270        t.tiltangle(-45)
2271        print(t.tiltangle()) # 315.0
2272    
2273        # Stamp the turtle's shape and move forward.
2274        t.stamp()
2275        t.forward(50)
2276        ```
2277        """
2278        if angle is None:
2279            tilt = -math.degrees(self._tilt) * self._angleOrient
2280            return (tilt / self._degreesPerAU) % self._fullcircle
2281        else:
2282            tilt = -angle * self._degreesPerAU * self._angleOrient
2283            tilt = math.radians(tilt) % math.tau
2284            self._tilt = tilt
2285
2286    def tilt(self, angle: int | float):
2287        """Rotate the turtleshape by angle.
2288
2289        Argument:
2290        `angle` -- a number
2291
2292        Rotate the turtleshape by `angle` from its current tilt-angle,
2293        but don't change the turtle's heading (direction of movement).
2294
2295        **Example**
2296        ```python
2297        from ipycc.turtle import Turtle, showscreen
2298
2299        # Show the screen.
2300        showscreen()
2301
2302        # Create a turtle.
2303        t = Turtle()
2304
2305        # Set the turtle's shape and size.
2306        t.shape("circle")
2307        t.shapesize(5, 2)
2308    
2309        # Tilt the turtle and move forward.
2310        t.tilt(30)
2311        t.forward(50)
2312
2313        # Tilt the turtle again and move forward.
2314        t.tilt(30)
2315        t.forward(50)
2316        ```
2317        """
2318        self.tiltangle(angle + self.tiltangle())
2319
2320
2321__all__ = ["Turtle", "Vec2D", "setup", "showscreen", "tracer", "delay", "no_animation", "clearscreen", "resetscreen", "colormode", "bgcolor"]
class Turtle:
 540class Turtle:
 541    """A class to describe a virtual turtle robot drawing on a screen."""
 542
 543    def __init__(self):
 544        self._pen = Sketch(_SCREEN.width, _SCREEN.height)
 545        _SCREEN.add_turtle(self)
 546        self.reset()
 547
 548    def _to_screen_coords(self, v: Vec2D) -> Vec2D:
 549        x = _SCREEN.width * 0.5 + v[0]
 550        y = _SCREEN.height * 0.5 + v[1]
 551        return Vec2D(x, y)
 552
 553    # ========================================
 554    #              Turtle Motion
 555    # ========================================
 556
 557    def _update(self):
 558        """Perform a Turtle-data update.
 559        """
 560        if _SCREEN._tracing == 0:
 561            return
 562        _SCREEN._update()
 563        _SCREEN._delay(_SCREEN._delayvalue)
 564
 565    def _go(self, distance: int | float):
 566        """Move turtle forward by specified distance"""
 567        ende = self._position + self._orient * distance
 568        self._goto(ende)
 569
 570    def _goto(self, end: Vec2D):
 571        """Move the pen to the point end, thereby drawing a line
 572        if pen is down. All other methods for turtle movement depend
 573        on this one.
 574        """
 575        start = self._position
 576        if self._speed and _SCREEN._tracing == 1:
 577            diff = end - start
 578            diffsq = (diff[0] * _SCREEN.xscale)**2 + (diff[1] * _SCREEN.yscale)**2
 579            nhops = 1 + int((diffsq**0.5) / (3 * (1.1**self._speed) * self._speed))
 580            delta = diff * (1.0 / nhops)
 581            for n in range(1, nhops + 1):
 582                self._position = start + delta * n
 583                if self._drawing:
 584                    x1, y1 = self._to_screen_coords(start)
 585                    x2, y2 = self._to_screen_coords(self._position)
 586                    self._pen.line(x1, y1, x2, y2)
 587                self._update()
 588        else:
 589            x1, y1 = self._to_screen_coords(start)
 590            x2, y2 = self._to_screen_coords(end)
 591            if self._drawing:
 592                self._pen.line(x1, y1, x2, y2)
 593        if isinstance(self._fillpath, list):
 594            self._fillpath.append(end)
 595        self._position = end
 596        self._update()
 597
 598    def forward(self, distance: int | float):
 599        """Move the turtle forward by the specified distance.
 600
 601        Aliases: `forward` | `fd`
 602
 603        Argument:
 604        `distance` -- a number (integer or float)
 605
 606        Move the turtle forward by the specified `distance`, in the direction
 607        the turtle is headed.
 608
 609        **Example**
 610        ```python
 611        from ipycc.turtle import Turtle, showscreen
 612
 613        # Show the screen.
 614        showscreen()
 615
 616        # Create a turtle.
 617        t = Turtle()
 618
 619        print(t.position()) # (0.00, 0.00)
 620        t.forward(25)
 621        print(t.position()) # (25.00,0.00)
 622        t.forward(-75)
 623        print(t.position()) # (-50.00,0.00)
 624        ```
 625        """
 626        self._go(distance)
 627
 628    fd = forward
 629
 630    def backward(self, distance: int | float):
 631        """Move the turtle backward by distance.
 632
 633        Aliases: `back` | `backward` | `bk`
 634
 635        Argument:
 636        `distance` -- a number
 637
 638        Move the turtle backward by `distance`, opposite to the direction the
 639        turtle is headed. Do not change the turtle's heading.
 640
 641        **Example**
 642        ```python
 643        from ipycc.turtle import Turtle, showscreen
 644
 645        # Show the screen.
 646        showscreen()
 647
 648        # Create a turtle.
 649        t = Turtle()
 650
 651        # Print the turtle's position before and after moving.
 652        print(t.position()) # (0.00, 0.00)
 653        t.backward(30)
 654        print(t.position()) # (-30.00, 0.00)
 655        ```
 656        """
 657        self._go(-distance)
 658
 659    back = backward
 660    bk = backward
 661
 662    def _rotate(self, angle: int | float):
 663        """Turn turtle counterclockwise by specified angle if angle > 0."""
 664        self._orient = self._orient.rotate(angle)
 665        self._update()
 666
 667    def right(self, angle: int | float):
 668        """Turn turtle right by angle units.
 669
 670        Aliases: `right` | `rt`
 671
 672        Argument:
 673        `angle` -- a number (integer or float)
 674
 675        Turn turtle right by `angle` units. (Units are by default degrees,
 676        but can be set via the `degrees()` and `radians()` methods.)
 677        Angle orientation depends on mode. (See this.)
 678
 679        **Example**
 680        ```python
 681        from ipycc.turtle import Turtle, showscreen
 682
 683        # Show the screen.
 684        showscreen()
 685
 686        # Create a turtle.
 687        t = Turtle()
 688
 689        # Print the turtle's heading before and after turning.
 690        print(t.heading()) # 22.0
 691        t.right(45)
 692        print(t.heading()) # 337.0
 693        ```
 694        """
 695        self._rotate(-angle)
 696
 697    rt = right
 698
 699    def left(self, angle: int | float):
 700        """Turn turtle left by angle units.
 701
 702        Aliases: `left` | `lt`
 703
 704        Argument:
 705        `angle` -- a number (integer or float)
 706
 707        Turn turtle left by `angle` units. (Units are by default degrees,
 708        but can be set via the `degrees()` and `radians()` methods.)
 709        Angle orientation depends on mode.
 710
 711        **Example**
 712        ```python
 713        from ipycc.turtle import Turtle, showscreen
 714
 715        # Show the screen.
 716        showscreen()
 717
 718        # Create a turtle.
 719        t = Turtle()
 720
 721        # Print the turtle's heading before and after turning.
 722        print(t.heading()) # 22.0
 723        t.left(45)
 724        print(t.heading()) # 67.0
 725        ```
 726        """
 727        self._rotate(angle)
 728
 729    lt = left
 730
 731    def goto(self, x: int | float | tuple | Vec2D, y: int | float = None):
 732        """Move turtle to an absolute position.
 733
 734        Aliases: `setpos` | `setposition` | `goto`:
 735
 736        Arguments:
 737        - `x` -- a number or vector
 738        - `y` -- a number (optional)
 739
 740        Move turtle to an absolute position. If the pen is down,
 741        a line will be drawn. The turtle's orientation does not change.
 742
 743        **Example**
 744        ```python
 745        from ipycc.turtle import Turtle, showscreen
 746
 747        # Show the screen.
 748        showscreen()
 749
 750        # Create a turtle.
 751        t = Turtle()
 752
 753        # Print the turtle's position before and after moving.
 754        print(t.pos()) # (0.00, 0.00)
 755        t.goto(60, 30)
 756        print(t.pos()) # (60.00, 30.00)
 757        ```
 758        """
 759        if y is None:
 760            self._goto(Vec2D(*x))
 761        else:
 762            self._goto(Vec2D(x, y))
 763
 764    setpos = goto
 765    setposition = goto
 766
 767    def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None:
 768        """Instantly move turtle to an absolute position.
 769
 770        Arguments:
 771        - `x` -- a number      or     `None`
 772        - `y` -- a number             `None`
 773        - `fill_gap` -- a boolean     This argument must be specified by name.
 774
 775        Move turtle to an absolute position. Unlike `goto(x, y)`, a line will not
 776        be drawn. The turtle's orientation does not change. If currently
 777        filling, the polygon(s) teleported from will be filled after leaving,
 778        and filling will begin again after teleporting. This can be disabled
 779        with `fill_gap=True`, which makes the imaginary line traveled during
 780        teleporting act as a fill barrier like in `goto(x, y)`.
 781
 782        **Example**
 783        ```python
 784        from ipycc.turtle import Turtle, showscreen
 785
 786        # Show the screen.
 787        showscreen()
 788
 789        # Create a turtle.
 790        t = Turtle()
 791
 792        tp = t.pos()
 793        print(tp)      # (0.00,0.00)
 794        t.teleport(60)
 795        print(t.pos()) # (60.00,0.00)
 796        t.teleport(y=10)
 797        print(t.pos()) # (60.00,10.00)
 798        t.teleport(20, 30)
 799        print(t.pos()) # (20.00,30.00)
 800        ```
 801        """
 802        pendown = self.isdown()
 803        was_filling = self.filling()
 804        if pendown:
 805            self.penup()
 806        if was_filling and not fill_gap:
 807            self.end_fill()
 808        new_x = x if x is not None else self._position[0]
 809        new_y = y if y is not None else self._position[1]
 810        self._position = Vec2D(new_x, new_y)
 811        if pendown:
 812            self.pendown()
 813        if was_filling and not fill_gap:
 814            self.begin_fill()
 815        self._update()
 816
 817    def setx(self, x: int | float):
 818        """Set the turtle's first coordinate to `x`.
 819
 820        Argument:
 821        `x` -- a number (integer or float)
 822
 823        Set the turtle's first coordinate to `x`, leave second coordinate
 824        unchanged.
 825
 826        **Example**
 827        ```python
 828        from ipycc.turtle import Turtle, showscreen
 829
 830        # Show the screen.
 831        showscreen()
 832
 833        # Create a turtle.
 834        t = Turtle()
 835
 836        # Print the turtle's position before and after moving.
 837        print(t.position()) # (0.00, 240.00)
 838        t.setx(10)
 839        print(t.position()) # (10.00, 240.00)
 840        ```
 841        """
 842        self._goto(Vec2D(x, self._position[1]))
 843
 844    def sety(self, y: int | float):
 845        """Set the turtle's second coordinate to `y`.
 846
 847        Argument:
 848        `y` -- a number (integer or float)
 849
 850        Set the turtle's first coordinate to `x`, second coordinate remains
 851        unchanged.
 852
 853        **Example**
 854        ```python
 855        from ipycc.turtle import Turtle, showscreen
 856
 857        # Show the screen.
 858        showscreen()
 859
 860        # Create a turtle.
 861        t = Turtle()
 862
 863        # Print the turtle's position before and after moving.
 864        print(t.position()) # (0.00, 40.00)
 865        t.sety(-10)
 866        print(t.position()) # (0.00, -10.00)
 867        ```
 868        """
 869        self._goto(Vec2D(self._position[0], y))
 870
 871    def setheading(self, to_angle: int | float):
 872        """Set the orientation of the turtle to `to_angle`.
 873
 874        Aliases:  `setheading` | `seth`
 875
 876        Argument:
 877        `to_angle` -- a number (integer or float)
 878
 879        Set the orientation of the turtle to `to_angle`.
 880        Here are some common directions in degrees:
 881        - 0 - east
 882        - 90 - north
 883        - 180 - west
 884        - 270 - south
 885
 886        **Example**
 887        ```python
 888        from ipycc.turtle import Turtle, showscreen
 889
 890        # Show the screen.
 891        showscreen()
 892
 893        # Create a turtle.
 894        t = Turtle()
 895
 896        # Set the turtle's heading and print it.
 897        t.setheading(90)
 898        print(t.heading()) # 90
 899        ```
 900        """
 901        angle = (to_angle - self.heading()) * self._angleOrient
 902        full = self._fullcircle
 903        half = full / 2.0
 904        angle = (angle + half) % full - half
 905        self._rotate(angle)
 906
 907    seth = setheading
 908
 909    def home(self):
 910        """Move turtle to the origin - coordinates `(0,0)`.
 911
 912        No arguments.
 913
 914        Move turtle to the origin and reset its heading to 0.
 915
 916        **Example**
 917        ```python
 918        from ipycc.turtle import Turtle, showscreen
 919
 920        # Show the screen.
 921        showscreen()
 922
 923        # Create a turtle.
 924        t = Turtle()
 925
 926        # Move the turtle forward, then move it back home.
 927        t.forward(100)
 928        t.home()
 929        ```
 930        """
 931        self.goto(0, 0)
 932        self.setheading(0)
 933
 934    def dot(self, size: int = None, *color: str | tuple[int | float]):
 935        """Draw a dot with diameter size, using color.
 936
 937        Optional arguments:
 938        - `size` -- an integer >= 1 (if given)
 939        - `color` -- a colorstring or a numeric color tuple
 940
 941        Draw a circular dot with diameter size, using `color`.
 942        If `size` is not given, the maximum of `pensize+4` and `2*pensize` is
 943        used.
 944
 945        **Example**
 946        ```python
 947        from ipycc.turtle import Turtle, showscreen
 948
 949        # Show the screen.
 950        showscreen()
 951
 952        # Create a turtle.
 953        t = Turtle()
 954
 955        # Draw dots.
 956        t.dot()
 957        t.forward(50)
 958        t.dot(20, "blue")
 959        t.forward(50)
 960        ```
 961        """
 962        if not color:
 963            if isinstance(size, (str, tuple)):
 964                color = _SCREEN._colorstr(size)
 965                size = self._pensize + max(self._pensize, 4)
 966            else:
 967                color = self._pencolor
 968                if not size:
 969                    size = self._pensize + max(self._pensize, 4)
 970        else:
 971            if size is None:
 972                size = self._pensize + max(self._pensize, 4)
 973            color = _SCREEN._colorstr(color)
 974        self._pen.canvas.save()
 975        self._pen.no_stroke()
 976        self._pen.fill(color)
 977        x, y = self._to_screen_coords(self._position)
 978        self._pen.circle(x, y, size)
 979        self._pen.canvas.restore()
 980        self._update()
 981
 982    def stamp(self):
 983        """Stamp a copy of the turtleshape onto the canvas.
 984
 985        No argument.
 986
 987        Stamp a copy of the turtle shape onto the canvas at the current
 988        turtle position.
 989
 990        **Example**
 991        ```python
 992        from ipycc.turtle import Turtle, showscreen
 993
 994        # Show the screen.
 995        showscreen()
 996
 997        # Create a turtle.
 998        t = Turtle()
 999
1000        # Draw a stamp and move.
1001        t.color("blue")
1002        t.stamp()
1003        t.forward(50)
1004        ```
1005        """
1006        self._pen.canvas.save()
1007        x, y = self._to_screen_coords(self._position)
1008        self._pen.translate(x, y)
1009        angle = math.radians(self.heading()) - math.pi / 2
1010        self._pen.rotate(angle)
1011        self._pen.stroke(self._pencolor)
1012        self._pen.stroke_weight(self._outlinewidth)
1013        self._pen.fill(self._fillcolor)
1014        self._pen.begin_shape()
1015        shape = _turtle_shapes[self._shape]
1016        for v in shape:
1017            sx, sy = self._stretchfactor
1018            self._pen.vertex(sx * v[0], sy * v[1])
1019        self._pen.end_shape()
1020        self._pen.reset_matrix()
1021        self._pen.canvas.restore()
1022        self._update()
1023
1024    def speed(self, speed: int | float | str = None) -> None | int:
1025        """Return or set the turtle's speed.
1026
1027        Optional argument:
1028        `speed` -- an integer in the range `0..10` or a `speedstring`
1029        (see below)
1030
1031        Set the turtle's speed to an integer value in the range `0..10`.
1032        If no argument is given: return current speed.
1033
1034        If input is a number greater than 10 or smaller than 0.5,
1035        speed is set to 0.
1036        Speedstrings  are mapped to speedvalues in the following way:
1037        - `'fastest'` :  0
1038        - `'fast'`    :  10
1039        - `'normal'`  :  6
1040        - `'slow'`    :  3
1041        - `'slowest'` :  1
1042        speeds from 1 to 10 enforce increasingly faster animation of
1043        line drawing and turtle turning.
1044
1045        Attention:
1046        `speed = 0` : *no* animation takes place. forward/back makes turtle jump
1047        and likewise left/right make the turtle turn instantly.
1048
1049        **Example**
1050        ```python
1051        from ipycc.turtle import Turtle, showscreen
1052
1053        # Show the screen.
1054        showscreen()
1055
1056        # Create a turtle.
1057        t = Turtle()
1058
1059        # Set the turtle's speed.
1060        t.speed(3)
1061        ```
1062        """
1063        speeds = {"fastest": 0, "fast": 10, "normal": 6, "slow": 3, "slowest": 1}
1064        if speed is None:
1065            return self._speed
1066        if speed in speeds:
1067            speed = speeds[speed]
1068        elif 0.5 < speed < 10.5:
1069            speed = int(round(speed))
1070        else:
1071            speed = 0
1072        self._speed = speed
1073
1074    def position(self) -> Vec2D:
1075        """Return the turtle's current location `(x,y)`, as a `Vec2D`.
1076
1077        Aliases: `pos` | `position`
1078
1079        No arguments.
1080
1081        **Example**
1082        ```python
1083        from ipycc.turtle import Turtle, showscreen
1084
1085        # Show the screen.
1086        showscreen()
1087
1088        # Create a turtle.
1089        t = Turtle()
1090
1091        # Print the turtle's position.
1092        print(t.pos()) # (0.00, 0.00)
1093        ```
1094        """
1095        return self._position
1096
1097    pos = position
1098
1099    def towards(self, x: int | float | tuple | Vec2D, y: int | float = None) -> float:
1100        """Return the angle of the line from the turtle's position to `(x,y)`.
1101
1102        Arguments:
1103        - `x` -- a number   or  a pair/vector of numbers   or   a turtle instance
1104        - `y` -- a number (optional)
1105
1106        Return the angle, between the line from turtle-position to position
1107        specified by `x`, `y` and the turtle's start orientation.
1108
1109        **Example**
1110        ```python
1111        from ipycc.turtle import Turtle, showscreen, Vec2D
1112
1113        # Show the screen.
1114        showscreen()
1115
1116        # Create a turtle.
1117        t = Turtle()
1118
1119        # Print the turtle's position and heading.
1120        print(t.pos()) # (10.00, 10.00)
1121        print(t.towards(0, 0)) # 225.0
1122        print(t.towards((0, 0))) # 225.0
1123        v = Vec2D(0, 0)
1124        print(t.towards(v)) # 225.0
1125        ```
1126        """
1127        if y is not None:
1128            pos = Vec2D(x, y)
1129        if isinstance(x, Vec2D):
1130            pos = x
1131        elif isinstance(x, tuple):
1132            pos = Vec2D(*x)
1133        elif isinstance(x, Turtle):
1134            pos = x._position
1135        x, y = pos - self._position
1136        result = round(math.degrees(math.atan2(y, x)), 10) % 360.0
1137        result /= self._degreesPerAU
1138        return (self._angleOffset + self._angleOrient * result) % self._fullcircle
1139
1140    def xcor(self) -> float:
1141        """Return the turtle's x coordinate.
1142
1143        No arguments.
1144
1145        **Example**
1146        ```python
1147        from ipycc.turtle import Turtle, showscreen
1148
1149        # Show the screen.
1150        showscreen()
1151
1152        # Create a turtle.
1153        t = Turtle()
1154
1155        # Move the turtle and print its x-coordinate.
1156        t.left(60)
1157        t.forward(100)
1158        print(tutrtle.xcor()) # 50.0
1159        ```
1160        """
1161        return self._position[0]
1162
1163    def ycor(self) -> float:
1164        """Return the turtle's y coordinate.
1165
1166        No arguments.
1167
1168        **Example**
1169        ```python
1170        from ipycc.turtle import Turtle, showscreen
1171
1172        # Show the screen.
1173        showscreen()
1174
1175        # Create a turtle.
1176        t = Turtle()
1177
1178        # Move the turtle and print its y-coordinate.
1179        t.left(60)
1180        t.forward(100)
1181        print(t.ycor()) # 86.6025403784
1182        ```
1183        """
1184        return self._position[1]
1185
1186    def heading(self) -> float:
1187        """Return the turtle's current heading.
1188
1189        No arguments.
1190
1191        **Example**
1192        ```python
1193        from ipycc.turtle import Turtle, showscreen
1194
1195        # Show the screen.
1196        showscreen()
1197
1198        # Create a turtle.
1199        t = Turtle()
1200
1201        # Turn the turtle and print its heading.
1202        t.left(67)
1203        print(t.heading()) # 67.0
1204        ```
1205        """
1206        x, y = self._orient
1207        result = round(math.degrees(math.atan2(y, x)), 10) % 360.0
1208        result /= self._degreesPerAU
1209        return (self._angleOffset + self._angleOrient*result) % self._fullcircle
1210
1211    def distance(self, x, y: int | float = None) -> float:
1212        """Return the distance from the turtle to `(x,y)` in turtle step units.
1213
1214        Arguments:
1215        - `x` -- a number or a pair/vector of numbers or a `Turtle` instance
1216        - `y` -- a number (optional)
1217
1218        **Example**
1219        ```python
1220        from ipycc.turtle import Turtle, showscreen
1221
1222        # Show the screen.
1223        showscreen()
1224
1225        # Create a turtle.
1226        t = Turtle()
1227
1228        # Print the turtle's position and distance to a point.
1229        print(t.pos()) # (0.00, 0.00)
1230        print(t.distance(30, 40)) # 50.0
1231
1232        # Create another turtle.
1233        t2 = Turtle()
1234
1235        # Move the second turtle and print its distance from
1236        # the first turtle.
1237        t2.forward(77)
1238        print(t.distance(t2)) # 77.0
1239        ```
1240        """
1241        if y is not None:
1242            pos = Vec2D(x, y)
1243        if isinstance(x, Vec2D):
1244            pos = x
1245        elif isinstance(x, tuple):
1246            pos = Vec2D(*x)
1247        elif isinstance(x, Turtle):
1248            pos = x._position
1249        return abs(pos - self._position)
1250
1251    def _setDegreesPerAU(self, fullcircle):
1252        """Helper function for degrees() and radians()"""
1253        self._fullcircle = fullcircle
1254        self._degreesPerAU = 360/fullcircle
1255        self._angleOffset = 0
1256
1257    def degrees(self, fullcircle: int | float = 360.0):
1258        """Set angle measurement units to degrees.
1259
1260        Optional argument:
1261        `fullcircle` -  a number
1262
1263        Set angle measurement units, i. e. set number
1264        of 'degrees' for a full circle. Default value is
1265        360 degrees.
1266
1267        **Example**
1268        ```python
1269        from ipycc.turtle import Turtle, showscreen
1270
1271        # Show the screen.
1272        showscreen()
1273
1274        # Create a turtle.
1275        t = Turtle()
1276
1277        # Turn the turtle and print its heading.
1278        t.left(90)
1279        print(t.heading()) # 90
1280
1281        # Change angle measurement unit to grad (also known as gon,
1282        # grade, or gradian and equals 1/100-th of the right angle.)
1283        t.degrees(400.0)
1284        print(t.heading()) # 100
1285        ```
1286        """
1287        self._setDegreesPerAU(fullcircle)
1288
1289    def radians(self):
1290        """Set the angle measurement units to radians.
1291
1292        No arguments.
1293
1294        **Example**
1295        ```python
1296        from ipycc.turtle import Turtle, showscreen
1297
1298        # Show the screen.
1299        showscreen()
1300
1301        # Create a turtle.
1302        t = Turtle()
1303
1304        # Print the turtle's heading in degrees and radians.
1305        print(t.heading()) # 90
1306        t.radians()
1307        print(t.heading()) # 1.5707963267948966
1308        ```
1309        """
1310        self._setDegreesPerAU(math.tau)
1311
1312    # ========================================
1313    #               Pen Control
1314    # ========================================
1315
1316    def pendown(self):
1317        """Pull the pen down -- drawing when moving.
1318
1319        Aliases: `pendown` | `pd` | `down`
1320
1321        No argument.
1322
1323        **Example**
1324        ```python
1325        from ipycc.turtle import Turtle, showscreen
1326
1327        # Show the screen.
1328        showscreen()
1329
1330        # Create a turtle.
1331        t = Turtle()
1332
1333        # Put the turtle's pen down and move.
1334        t.pendown()
1335        t.forward(100)
1336        ```
1337        """
1338        self._drawing = True
1339
1340    pd = pendown
1341    down = pendown
1342
1343    def penup(self):
1344        """Pull the pen up -- no drawing when moving.
1345
1346        Aliases: `penup` | `pu` | `up`
1347
1348        No argument
1349
1350        **Example**
1351        ```python
1352        from ipycc.turtle import Turtle, showscreen
1353
1354        # Show the screen.
1355        showscreen()
1356
1357        # Create a turtle.
1358        t = Turtle()
1359
1360        # Pick the turtle's pen up and move.
1361        t.penup()
1362        t.forward(100)
1363        ```
1364        """
1365        self._drawing = False
1366
1367    pu = penup
1368    up = penup
1369
1370    def pensize(self, width: int | float = None) -> None | float:
1371        """Set or return the line thickness.
1372
1373        Aliases:  `pensize` | `width`
1374
1375        Argument:
1376        `width` -- positive number
1377
1378        Set the line thickness to `width` or return it. If no argument is
1379        given, current pensize is returned.
1380
1381        **Example**
1382        ```python
1383        from ipycc.turtle import Turtle, showscreen
1384
1385        # Show the screen.
1386        showscreen()
1387
1388        # Create a turtle.
1389        t = Turtle()
1390
1391        # Print the turtle's pen size and move.
1392        print(t.pensize()) # 1
1393        t.forward(50)
1394
1395        # Change the turtle's pen size and move.
1396        t.pensize(10)   # from here on lines of width 10 are drawn
1397        t.forward(50)
1398        ```
1399        """
1400        if width is None:
1401            return self._pensize
1402        self._pensize = width
1403        self._pen.stroke_weight(self._pensize)
1404
1405    width = pensize
1406
1407    def isdown(self) -> bool:
1408        """Return `True` if pen is down, `False` if it's up.
1409
1410        No argument.
1411
1412        **Example**
1413        ```python
1414        from ipycc.turtle import Turtle, showscreen
1415
1416        # Show the screen.
1417        showscreen()
1418
1419        # Create a turtle.
1420        t = Turtle()
1421
1422        # Pick the turtle's pen up and print its state.
1423        t.penup()
1424        print(t.isdown()) # False
1425        # Put the turtle's pen down and print its state.
1426        t.pendown()
1427        print(t.isdown()) # True
1428        ```
1429        """
1430        return self._drawing
1431
1432    def color(self, *args) -> None | str | tuple:
1433        """Return or set the pencolor and fillcolor.
1434
1435        Arguments:
1436        Several input formats are allowed.
1437        They use 0, 1, 2, or 3 arguments as follows:
1438
1439        - `color()` returns the current pencolor and the current fillcolor
1440        as a pair of color specification strings.
1441        - `color(colorstring)`, `color((r,g,b))`, `color(r,g,b)` sets both
1442        `fillcolor()` and `pencolor()` to the given value.
1443        - `color(colorstring1, colorstring2)`, `color((r1,g1,b1), (r2,g2,b2))`
1444        sets `pencolor(colorstring1)` and `fillcolor(colorstring2)` or
1445        `pencolor((r1,g1,b1))` and `fillcolor((r2,g2,b2))`.
1446
1447        If turtleshape is a polygon, outline and interior of that polygon
1448        is drawn with the newly set colors.
1449
1450        For more info see: `pencolor()`, `fillcolor()`
1451
1452        **Example**
1453        ```python
1454        from ipycc.turtle import Turtle, showscreen
1455
1456        # Show the screen.
1457        showscreen()
1458
1459        # Create a turtle.
1460        t = Turtle()
1461
1462        # Set the turtle's pen and fill color, then print them.
1463        t.color('red', 'green')
1464        print(t.color()) # ('red', 'green')
1465        # Change the color mode.
1466        t.colormode(255)
1467        # Set the turtle's pen and fill color, then print them.
1468        t.color((40, 80, 120), (160, 200, 240))
1469        print(t.color()) # ('#285078', '#a0c8f0')
1470        ```
1471        """
1472        if args:
1473            l = len(args)
1474            if l == 1:
1475                pcolor = fcolor = args[0]
1476            elif l == 2:
1477                pcolor, fcolor = args
1478            elif l == 3:
1479                pcolor = fcolor = args
1480            pcolor = _SCREEN._colorstr(pcolor)
1481            fcolor = _SCREEN._colorstr(fcolor)
1482            self._pencolor = pcolor
1483            self._pen.stroke(self._pencolor)
1484            self._pen.stroke_weight(self._pensize)
1485            self._fillcolor = fcolor
1486            self._pen.fill(self._fillcolor)
1487            self._update()
1488        else:
1489            return _SCREEN._color(self._pencolor), _SCREEN._color(self._fillcolor)
1490
1491    def pencolor(self, *args) -> None | str | tuple:
1492        """ Return or set the pencolor.
1493
1494        Arguments:
1495        Four input formats are allowed:
1496          - `pencolor()`
1497            Return the current pencolor as color specification string,
1498            possibly in hex-number format (see example).
1499            May be used as input to another color/pencolor/fillcolor call.
1500          - `pencolor(colorstring)`
1501            a [Tk color specification string](https://www.tcl-lang.org/man/tcl8.4/TkCmd/colors.htm),
1502            such as `"red"` or `"yellow"`
1503          - `pencolor((r, g, b))`
1504            *a tuple* of `r`, `g`, and `b`, which represent, an RGB color,
1505            and each of `r`, `g`, and `b` are in the range `0..colormode`,
1506            where `colormode` is either 1.0 or 255
1507          - `pencolor(r, g, b)`
1508            `r`, `g`, and `b` represent an RGB color, and each of `r`, `g`,
1509            and `b` are in the range `0..colormode`
1510
1511        If turtleshape is a polygon, the outline of that polygon is drawn
1512        with the newly set pencolor.
1513
1514        **Example**
1515        ```python
1516        from ipycc.turtle import Turtle, showscreen
1517
1518        # Show the screen.
1519        showscreen()
1520
1521        # Create a turtle.
1522        t = Turtle()
1523
1524        # Set the turtle's pen color to brown, then print it.
1525        t.pencolor('brown')
1526        print(t.pencolor()) # 'brown'
1527        # Set the turtle's pen color using a tuple, then print it.
1528        tup = (0.2, 0.8, 0.55)
1529        t.pencolor(tup)
1530        print(t.pencolor()) # '#33cc8c'
1531        ```
1532        """
1533        if args:
1534            color = _SCREEN._colorstr(args)
1535            if color == self._pencolor:
1536                return
1537            self._pencolor = color
1538            self._pen.stroke(self._pencolor)
1539            self._pen.stroke_weight(self._pensize)
1540            self._update()
1541        else:
1542            return _SCREEN._color(self._pencolor)
1543
1544    def fillcolor(self, *args) -> None | str | tuple:
1545        """Return or set the fillcolor.
1546
1547        Arguments:
1548        Four input formats are allowed:
1549          - `fillcolor()`
1550            Return the current fillcolor as color specification string,
1551            possibly in hex-number format (see example).
1552            May be used as input to another color/pencolor/fillcolor call.
1553          - `fillcolor(colorstring)`
1554            a [Tk color specification string](https://www.tcl-lang.org/man/tcl8.4/TkCmd/colors.htm),
1555            such as `"red"` or `"yellow"`
1556          - `fillcolor((r, g, b))`
1557            *a tuple* of `r`, `g`, and `b`, which represent, an RGB color,
1558            and each of `r`, `g`, and `b` are in the range `0..colormode`,
1559            where `colormode` is either 1.0 or 255
1560          - `fillcolor(r, g, b)`
1561            `r`, `g`, and `b` represent an RGB color, and each of `r`, `g`, and `b`
1562            are in the range `0..colormode`
1563
1564        If turtleshape is a polygon, the interior of that polygon is drawn
1565        with the newly set fillcolor.
1566
1567        **Example**
1568        ```python
1569        from ipycc.turtle import Turtle, showscreen
1570
1571        # Show the screen.
1572        showscreen()
1573
1574        # Create a turtle.
1575        t = Turtle()
1576
1577        # Set the turtle's fill color to violet.
1578        t.fillcolor('violet')
1579        # Set the turtle's fill color to its pen color.
1580        col = t.pencolor()
1581        t.fillcolor(col)
1582        # Set the turtle's fill color using RGB values.
1583        t.fillcolor(0, 0.5, 0)
1584        ```
1585        """
1586        if args:
1587            color = _SCREEN._colorstr(args)
1588            if color == self._fillcolor:
1589                return
1590            self._fillcolor = color
1591            self._pen.fill(self._fillcolor)
1592            self._update()
1593        else:
1594            return _SCREEN._color(self._fillcolor)
1595
1596    def filling(self) -> bool:
1597        """Return fillstate (`True` if filling, `False` otherwise).
1598
1599        No argument.
1600
1601        **Example**
1602        ```python
1603        from ipycc.turtle import Turtle, showscreen
1604
1605        # Show the screen.
1606        showscreen()
1607
1608        # Create a turtle.
1609        t = Turtle()
1610
1611        # Begin filling.
1612        t.begin_fill()
1613        # Change the turtle's pen size if it is filling.
1614        if t.filling():
1615            t.pensize(5)
1616        else:
1617            t.pensize(3)
1618        ```
1619        """
1620        return isinstance(self._fillpath, list)
1621
1622    @contextmanager
1623    def fill(self):
1624        """A context manager for filling a shape.
1625
1626        No argument.
1627
1628        Implicitly ensures the code block is wrapped with
1629        `begin_fill()` and `end_fill()`.
1630
1631        **Example**
1632        ```python
1633        from ipycc.turtle import Turtle, showscreen
1634
1635        # Show the screen.
1636        showscreen()
1637
1638        # Create a turtle.
1639        t = Turtle()
1640        t.color("black", "red")
1641
1642        # Fill.
1643        with t.fill():
1644            t.circle(60)
1645        ```
1646        """
1647        self.begin_fill()
1648        try:
1649            yield
1650        finally:
1651            self.end_fill()
1652
1653    def begin_fill(self):
1654        """Called just before drawing a shape to be filled.
1655
1656        No argument.
1657
1658        **Example**
1659        ```python
1660        from ipycc.turtle import Turtle, showscreen
1661
1662        # Show the screen.
1663        showscreen()
1664
1665        # Create a turtle.
1666        t = Turtle()
1667
1668        # Set the turtle's pen and fill colors.
1669        t.color("black", "red")
1670
1671        # Begin filling.
1672        t.begin_fill()
1673        t.circle(60)
1674        # Stop filling.
1675        t.end_fill()
1676        ```
1677        """
1678        self._fillpath = [self._position]
1679
1680    def end_fill(self):
1681        """Fill the shape drawn after the call `begin_fill()`.
1682
1683        No argument.
1684
1685        **Example**
1686        ```python
1687        from ipycc.turtle import Turtle, showscreen
1688
1689        # Show the screen.
1690        showscreen()
1691
1692        # Create a turtle.
1693        t = Turtle()
1694
1695        # Set the turtle's pen and fill color.
1696        t.color("black", "red")
1697    
1698        # Begin filling.
1699        t.begin_fill()
1700        t.circle(60)
1701        # Stop filling.
1702        t.end_fill()
1703        ```
1704        """
1705        if self.filling():
1706            if len(self._fillpath) > 2:
1707                self._pen.begin_shape()
1708                for v in self._fillpath:
1709                    x, y = self._to_screen_coords(v)
1710                    self._pen.vertex(x, y)
1711                self._pen.end_shape()
1712            self._fillpath = None
1713            self._update()
1714
1715    @contextmanager
1716    def poly(self):
1717        """A context manager for recording the vertices of a polygon.
1718
1719        No argument.
1720
1721        Implicitly ensures that the code block is wrapped with
1722        `begin_poly()` and `end_poly()`
1723
1724        **Example**
1725        ```python
1726        from ipycc.turtle import Turtle, showscreen
1727
1728        # Show the screen.
1729        showscreen()
1730
1731        # Create a turtle.
1732        t = Turtle()
1733
1734        # Set the turtle's pen and fill color.
1735        t.color("black", "red")
1736
1737        # Begin filling.
1738        t.begin_fill()
1739
1740        # Create a polygon.
1741        with t.poly():
1742            for i in range(4):
1743                t.forward(50)
1744                t.left(90)
1745        
1746        # Stop filling.
1747        t.end_fill()
1748        ```
1749        """
1750        self.begin_poly()
1751        try:
1752            yield
1753        finally:
1754            self.end_poly()
1755
1756    def begin_poly(self):
1757        """Start recording the vertices of a polygon.
1758
1759        No argument.
1760
1761        Start recording the vertices of a polygon. Current turtle position
1762        is first point of polygon.
1763
1764        **Example**
1765        ```python
1766        from ipycc.turtle import Turtle, showscreen
1767
1768        # Show the screen.
1769        showscreen()
1770
1771        # Create a turtle.
1772        t = Turtle()
1773
1774        # Set the turtle's pen and fill color.
1775        t.color("black", "red")
1776
1777        # Begin filling.
1778        t.begin_fill()
1779
1780        # Begin creating a polygon.
1781        t.begin_poly()
1782        for i in range(4):
1783            t.forward(50)
1784            t.left(90)
1785
1786        # Stop creating a polygon.
1787        t.end_poly()
1788
1789        # Stop filling.
1790        t.end_fill()
1791        ```
1792        """
1793        self._poly = [self._position]
1794        self._creatingPoly = True
1795
1796    def end_poly(self):
1797        """Stop recording the vertices of a polygon.
1798
1799        No argument.
1800
1801        Stop recording the vertices of a polygon. Current turtle position is
1802        last point of polygon. This will be connected with the first point.
1803
1804        **Example**
1805        ```python
1806        from ipycc.turtle import Turtle, showscreen
1807
1808        # Show the screen.
1809        showscreen()
1810
1811        # Create a turtle.
1812        t = Turtle()
1813
1814        # Set the turtle's pen and fill color.
1815        t.color("black", "red")
1816    
1817        # Begin filling.
1818        t.begin_fill()
1819    
1820        # Begin creating a polygon.
1821        t.begin_poly()
1822        for i in range(4):
1823            t.forward(50)
1824            t.left(90)
1825
1826        # Stop creating a polygon.
1827        t.end_poly()
1828
1829        # Stop filling.
1830        t.end_fill()
1831        ```
1832        """
1833        self._creatingPoly = False
1834
1835    def circle(
1836        self, radius: int | float, extent: int | float = None, steps: int = None
1837    ):
1838        """Draw a circle with given radius.
1839
1840        Arguments:
1841        - `radius` -- a number
1842        - `extent` (optional) -- a number
1843        - `steps` (optional) -- an integer
1844
1845        Draw a circle with given radius. The center is `radius` units left
1846        of the turtle; `extent` - an angle - determines which part of the
1847        circle is drawn. If `extent` is not given, draw the entire circle.
1848        If `extent` is not a full circle, one endpoint of the arc is the
1849        current pen position. Draw the arc in counterclockwise direction
1850        if `radius` is positive, otherwise in clockwise direction. Finally
1851        the direction of the turtle is changed by the amount of extent.
1852
1853        As the circle is approximated by an inscribed regular polygon,
1854        `steps` determines the number of steps to use. If not given,
1855        it will be calculated automatically. May be used to draw regular
1856        polygons.
1857
1858        **Example**
1859        ```python
1860        from ipycc.turtle import Turtle, showscreen
1861
1862        # Show the screen.
1863        showscreen()
1864
1865        # Create a turtle.
1866        t = Turtle()
1867
1868        t.circle(50)
1869        t.circle(120, 180)  # semicircle
1870        ```
1871        """
1872        speed = self.speed()
1873        if extent is None:
1874            extent = self._fullcircle
1875        if steps is None:
1876            frac = abs(extent) / self._fullcircle
1877            steps = 1+int(min(11+abs(radius)/6.0, 59.0)*frac)
1878        w = 1.0 * extent / steps
1879        w2 = 0.5 * w
1880        l = 2.0 * radius * math.sin(math.radians(w2)*self._degreesPerAU)
1881        if radius < 0:
1882            l, w, w2 = -l, -w, -w2
1883        tr = tracer()
1884        dl = delay()
1885        if speed == 0:
1886            tracer(0, 0)
1887        else:
1888            self.speed(0)
1889        self._rotate(w2)
1890        for i in range(steps):
1891            self.speed(speed)
1892            self._go(l)
1893            self.speed(0)
1894            self._rotate(w)
1895        self._rotate(-w2)
1896        if speed == 0:
1897            tracer(tr, dl)
1898        self.speed(speed)
1899
1900    def reset(self):
1901        """Return the turtle to its initial state and clear its drawings from
1902        the screen.
1903
1904        No arguments.
1905
1906        **Example**
1907        ```python
1908        from ipycc.turtle import Turtle, showscreen
1909
1910        # Show the screen.
1911        showscreen()
1912
1913        # Create a turtle.
1914        t = Turtle()
1915
1916        # Move the turtle forward.
1917        t.forward(50)
1918
1919        # Reset the turtle.
1920        t.reset()
1921        ```
1922        """
1923        self._drawing = True
1924        self._pencolor = "black"
1925        self._pensize = 1
1926        self._pen.stroke(self._pencolor)
1927        self._pen.stroke_weight(self._pensize)
1928        self._speed = 3
1929        self._shown = True
1930        self._fillcolor = "black"
1931        self._is_filling = False
1932        self._poly = []
1933        self._fillpath = None
1934        self._pen.no_fill()
1935        self._creatingPoly = False
1936        self._position = Vec2D(0, 0)
1937        self._shape = "classic"
1938        self._stretchfactor = (1.0, 1.0)
1939        self._shearfactor = 0.0
1940        self._tilt = 0.0
1941        self._outlinewidth = 1
1942        self._orient = Vec2D(1, 0)
1943        self._angleOrient = 1.0
1944        self.degrees()
1945        self.clear()
1946        self.home()
1947
1948    def clear(self):
1949        """Delete the turtle's drawings from the screen. Do not move turtle.
1950
1951        No arguments.
1952
1953        Delete the turtle's drawings from the screen. Do not move turtle.
1954        State and position of the turtle as well as drawings of other
1955        turtles are not affected.
1956
1957        **Example**
1958        ```python
1959        from ipycc.turtle import Turtle, showscreen
1960
1961        # Show the screen.
1962        showscreen()
1963
1964        # Create a turtle.
1965        t = Turtle()
1966
1967        # Move the turtle forward.
1968        t.forward(50)
1969
1970        # Clear the turtle's drawings.
1971        t.clear()
1972        ```
1973        """
1974        self._pen.clear()
1975        self._update()
1976
1977    def _write(self, txt: str, align: str, fontname: str, fontsize: int | float, fonttype: str):
1978        """Performs the writing for write()
1979        """
1980        self._pen.canvas.save()
1981        self._pen.scale(1, -1)
1982        self._pen.translate(0, -self._pen.height)
1983        x, y = self._to_screen_coords(self._position)
1984        self._pen.fill(self._pencolor)
1985        self._pen.no_stroke()
1986        self._pen.text_align(align)
1987        self._pen.text_font(fontname)
1988        self._pen.text_size(fontsize)
1989        self._pen.text_style(fonttype)
1990        self._pen.text(txt, x, self._pen.height - y)
1991        self._pen.canvas.restore()
1992        self._update()
1993
1994    def write(self, arg, align: str = "left", font: tuple = ("Arial", 8, "normal")):
1995        """Write text at the current turtle position.
1996
1997        Arguments:
1998        - `arg` -- info, which is to be written to the screen
1999        - `align` (optional) -- one of the strings `"left"`, `"center"` or
2000        `"right"`
2001        - `font` (optional) -- a triple (fontname, fontsize, fonttype)
2002
2003        Write text - the string representation of `arg` - at the current
2004        turtle position according to align (`"left"`, `"center"` or `"right"`)
2005        and with the given font.
2006
2007        **Example**
2008        ```python
2009        from ipycc.turtle import Turtle, showscreen
2010
2011        # Show the screen.
2012        showscreen()
2013
2014        # Create a turtle.
2015        t = Turtle()
2016
2017        # Write messages to the screen.
2018        t.write('Home = ', align="center")
2019        t.write((0, 0))
2020        ```
2021        """
2022        fontname, fontsize, fonttype = font
2023        if not align.lower() in (Sketch.LEFT, Sketch.CENTER, Sketch.RIGHT):
2024            raise TurtleGraphicsError('Invalid text alignment. Must be "left", "center", or "right".')
2025        if not isinstance(fontsize, (int, float)):
2026            raise TurtleGraphicsError('Font size must be a number.')
2027        if not fonttype in (Sketch.NORMAL, Sketch.ITALIC, Sketch.BOLD, Sketch.BOLDITALIC):
2028            raise TurtleGraphicsError('Invalid font type. Must be "normal", "italic", "bold", or "bolditalic".')
2029        self._write(str(arg), align.lower(), fontname, fontsize, fonttype)
2030
2031    # ========================================
2032    #             Turtle State
2033    # ========================================
2034
2035    def showturtle(self):
2036        """Make the turtle visible.
2037
2038        Aliases:  `showturtle` | `st`
2039
2040        **Example**
2041        ```python
2042        from ipycc.turtle import Turtle, showscreen
2043
2044        # Show the screen.
2045        showscreen()
2046
2047        # Create a turtle.
2048        t = Turtle()
2049
2050        # Hide the turtle.
2051        t.hideturtle()
2052
2053        # Show the turtle.
2054        t.showturtle()
2055        ```
2056        """
2057        self._shown = True
2058        self._update()
2059
2060    st = showturtle
2061
2062    def hideturtle(self):
2063        """Make the turtle invisible.
2064
2065        Aliases:  `hideturtle` | `ht`
2066
2067        **Example**
2068        ```python
2069        from ipycc.turtle import Turtle, showscreen
2070
2071        # Show the screen.
2072        showscreen()
2073
2074        # Create a turtle.
2075        t = Turtle()
2076
2077        # Hide the turtle.
2078        t.hideturtle()
2079
2080        # Show the turtle.
2081        t.showturtle()
2082        ```
2083        """
2084        self._shown = False
2085        self._update()
2086
2087    ht = hideturtle
2088
2089    def isvisible(self) -> bool:
2090        """Return `True` if the turtle is shown, `False` if it's hidden.
2091
2092        **Example**
2093        ```python
2094        from ipycc.turtle import Turtle, showscreen
2095
2096        # Show the screen.
2097        showscreen()
2098
2099        # Create a turtle.
2100        t = Turtle()
2101
2102        # Hide the turtle and print whether it is visible.
2103        t.hideturtle()
2104        print(t.isvisible()) # False
2105        # Show the turtle and print whether it is visible.
2106        t.showturtle()
2107        print(t.isvisible()) # True
2108        ```
2109        """
2110        return self._shown
2111
2112    def shape(self, name: str = None) -> None | str:
2113        """Set turtle shape to shape with given name / return current shapename.
2114
2115        Optional argument:
2116        `name` -- a string, which is a valid shapename
2117
2118        Set turtle shape to shape with given `name` or, if `name` is not given,
2119        return name of current shape.
2120        Valid shapenames are:
2121        - `"arrow"`
2122        - `"turtle"`
2123        - `"circle"`
2124        - `"square"`
2125        - `"triangle"`
2126        - `"classic"`
2127
2128        ```python
2129        from ipycc.turtle import Turtle, showscreen
2130
2131        # Show the screen.
2132        showscreen()
2133
2134        # Create a turtle.
2135        t = Turtle()
2136
2137        # Print the turtle's default shape.
2138        print(t.shape()) # 'arrow'
2139
2140        # Change the turtle's shape and print it.
2141        t.shape("turtle")
2142        print(t.shape()) # 'turtle'
2143        ```
2144        """
2145        if name is None:
2146            return self._shape
2147        if not name in _turtle_shapes:
2148            raise NameError("There is no shape named %s" % name)
2149        self._shape = name
2150        self._update()
2151
2152    def shapesize(
2153        self, stretch_wid: int | float = None, stretch_len: int | float = None
2154    ) -> float:
2155        """Set/return turtle's stretchfactors/outline. Set resizemode to "user".
2156
2157        Optional arguments:
2158        - `stretch_wid` : positive number
2159        - `stretch_len` : positive number
2160        - `outline`  : positive number
2161
2162        Return or set the pen's attributes x/y-stretchfactors and/or outline.
2163        The turtle will be displayed stretched according to its stretchfactors:
2164        - `stretch_wid` is stretchfactor perpendicular to orientation.
2165        - `stretch_len` is stretchfactor in direction of the turtle's orientation.
2166        - `outline` determines the width of the shapes's outline.
2167
2168        ```python
2169        from ipycc.turtle import Turtle, showscreen
2170
2171        # Show the screen.
2172        showscreen()
2173
2174        # Create a turtle.
2175        t = Turtle()
2176
2177        # Change the turtle's shape size.
2178        t.shapesize(5, 5, 12)
2179        t.shapesize(outline=8)
2180        ```
2181        """
2182        if stretch_wid is stretch_len is None:
2183            return self._stretchfactor
2184        if stretch_wid == 0 or stretch_len == 0:
2185            raise TurtleGraphicsError("stretch_wid/stretch_len must not be zero")
2186        if stretch_wid is not None:
2187            if stretch_len is None:
2188                self._stretchfactor = stretch_wid, stretch_wid
2189            else:
2190                self._stretchfactor = stretch_wid, stretch_len
2191        elif stretch_len is not None:
2192            self._stretchfactor = self._stretchfactor[0], stretch_len
2193        else:
2194            self._stretchfactor = self._stretchfactor
2195        self._update()
2196
2197    def shearfactor(self, shear: int | float = None) -> None | float:
2198        """Set or return the current shearfactor.
2199
2200        Optional argument: `shear` -- number, tangent of the shear angle
2201
2202        Shear the turtleshape according to the given shearfactor `shear`,
2203        which is the tangent of the shear angle. Doesn't change the
2204        turtle's heading (direction of movement).
2205        If `shear` is not given: return the current shearfactor, i. e. the
2206        tangent of the shear angle, by which lines parallel to the
2207        heading of the turtle are sheared.
2208
2209        ```python
2210        from ipycc.turtle import Turtle, showscreen
2211
2212        # Show the screen.
2213        showscreen()
2214
2215        # Create a turtle.
2216        t = Turtle()
2217
2218        # Set the turtle's shape and size.
2219        t.shape("circle")
2220        t.shapesize(5, 2)
2221
2222        # Set the turtle's shear factor and print it.
2223        t.shearfactor(0.5)
2224        print(t.shearfactor()) # 0.5
2225        ```
2226        """
2227        if shear is None:
2228            return self._shearfactor
2229        self._shearfactor = shear
2230
2231    def tiltangle(self, angle: int | float = None) -> None | float:
2232        """Set or return the current tilt-angle.
2233
2234        Optional argument: `angle` -- number
2235
2236        Rotate the turtleshape to point in the direction specified by `angle`,
2237        regardless of its current tilt-angle. Doesn't change the turtle's
2238        heading (direction of movement).
2239        If `angle` is not given: return the current tilt-angle, i. e. the angle
2240        between the orientation of the turtleshape and the heading of the
2241        turtle (its direction of movement).
2242
2243        **Example**
2244        ```python
2245        from ipycc.turtle import Turtle, showscreen
2246
2247        # Show the screen.
2248        showscreen()
2249
2250        # Create a turtle.
2251        t = Turtle()
2252
2253        # Set the turtle's shape and size.
2254        t.shape("circle")
2255        t.shapesize(5, 2)
2256
2257        # Print the turtle's tilt angle.
2258        print(t.tiltangle()) # 0.0
2259
2260        # Tilt the turtle and print the angle.
2261        t.tiltangle(45)
2262        print(t.tiltangle()) # 45.0
2263
2264        # Stamp the turtle's shape.
2265        t.stamp()
2266        
2267        # Move the turtle forward.
2268        t.forward(50)
2269    
2270        #  Tilt the turtle back to its original angle and print it.
2271        t.tiltangle(-45)
2272        print(t.tiltangle()) # 315.0
2273    
2274        # Stamp the turtle's shape and move forward.
2275        t.stamp()
2276        t.forward(50)
2277        ```
2278        """
2279        if angle is None:
2280            tilt = -math.degrees(self._tilt) * self._angleOrient
2281            return (tilt / self._degreesPerAU) % self._fullcircle
2282        else:
2283            tilt = -angle * self._degreesPerAU * self._angleOrient
2284            tilt = math.radians(tilt) % math.tau
2285            self._tilt = tilt
2286
2287    def tilt(self, angle: int | float):
2288        """Rotate the turtleshape by angle.
2289
2290        Argument:
2291        `angle` -- a number
2292
2293        Rotate the turtleshape by `angle` from its current tilt-angle,
2294        but don't change the turtle's heading (direction of movement).
2295
2296        **Example**
2297        ```python
2298        from ipycc.turtle import Turtle, showscreen
2299
2300        # Show the screen.
2301        showscreen()
2302
2303        # Create a turtle.
2304        t = Turtle()
2305
2306        # Set the turtle's shape and size.
2307        t.shape("circle")
2308        t.shapesize(5, 2)
2309    
2310        # Tilt the turtle and move forward.
2311        t.tilt(30)
2312        t.forward(50)
2313
2314        # Tilt the turtle again and move forward.
2315        t.tilt(30)
2316        t.forward(50)
2317        ```
2318        """
2319        self.tiltangle(angle + self.tiltangle())

A class to describe a virtual turtle robot drawing on a screen.

def forward(self, distance: int | float):
598    def forward(self, distance: int | float):
599        """Move the turtle forward by the specified distance.
600
601        Aliases: `forward` | `fd`
602
603        Argument:
604        `distance` -- a number (integer or float)
605
606        Move the turtle forward by the specified `distance`, in the direction
607        the turtle is headed.
608
609        **Example**
610        ```python
611        from ipycc.turtle import Turtle, showscreen
612
613        # Show the screen.
614        showscreen()
615
616        # Create a turtle.
617        t = Turtle()
618
619        print(t.position()) # (0.00, 0.00)
620        t.forward(25)
621        print(t.position()) # (25.00,0.00)
622        t.forward(-75)
623        print(t.position()) # (-50.00,0.00)
624        ```
625        """
626        self._go(distance)

Move the turtle forward by the specified distance.

Aliases: forward | fd

Argument: distance -- a number (integer or float)

Move the turtle forward by the specified distance, in the direction the turtle is headed.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

print(t.position()) # (0.00, 0.00)
t.forward(25)
print(t.position()) # (25.00,0.00)
t.forward(-75)
print(t.position()) # (-50.00,0.00)
def fd(self, distance: int | float):
598    def forward(self, distance: int | float):
599        """Move the turtle forward by the specified distance.
600
601        Aliases: `forward` | `fd`
602
603        Argument:
604        `distance` -- a number (integer or float)
605
606        Move the turtle forward by the specified `distance`, in the direction
607        the turtle is headed.
608
609        **Example**
610        ```python
611        from ipycc.turtle import Turtle, showscreen
612
613        # Show the screen.
614        showscreen()
615
616        # Create a turtle.
617        t = Turtle()
618
619        print(t.position()) # (0.00, 0.00)
620        t.forward(25)
621        print(t.position()) # (25.00,0.00)
622        t.forward(-75)
623        print(t.position()) # (-50.00,0.00)
624        ```
625        """
626        self._go(distance)

Move the turtle forward by the specified distance.

Aliases: forward | fd

Argument: distance -- a number (integer or float)

Move the turtle forward by the specified distance, in the direction the turtle is headed.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

print(t.position()) # (0.00, 0.00)
t.forward(25)
print(t.position()) # (25.00,0.00)
t.forward(-75)
print(t.position()) # (-50.00,0.00)
def backward(self, distance: int | float):
630    def backward(self, distance: int | float):
631        """Move the turtle backward by distance.
632
633        Aliases: `back` | `backward` | `bk`
634
635        Argument:
636        `distance` -- a number
637
638        Move the turtle backward by `distance`, opposite to the direction the
639        turtle is headed. Do not change the turtle's heading.
640
641        **Example**
642        ```python
643        from ipycc.turtle import Turtle, showscreen
644
645        # Show the screen.
646        showscreen()
647
648        # Create a turtle.
649        t = Turtle()
650
651        # Print the turtle's position before and after moving.
652        print(t.position()) # (0.00, 0.00)
653        t.backward(30)
654        print(t.position()) # (-30.00, 0.00)
655        ```
656        """
657        self._go(-distance)

Move the turtle backward by distance.

Aliases: back | backward | bk

Argument: distance -- a number

Move the turtle backward by distance, opposite to the direction the turtle is headed. Do not change the turtle's heading.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's position before and after moving.
print(t.position()) # (0.00, 0.00)
t.backward(30)
print(t.position()) # (-30.00, 0.00)
def back(self, distance: int | float):
630    def backward(self, distance: int | float):
631        """Move the turtle backward by distance.
632
633        Aliases: `back` | `backward` | `bk`
634
635        Argument:
636        `distance` -- a number
637
638        Move the turtle backward by `distance`, opposite to the direction the
639        turtle is headed. Do not change the turtle's heading.
640
641        **Example**
642        ```python
643        from ipycc.turtle import Turtle, showscreen
644
645        # Show the screen.
646        showscreen()
647
648        # Create a turtle.
649        t = Turtle()
650
651        # Print the turtle's position before and after moving.
652        print(t.position()) # (0.00, 0.00)
653        t.backward(30)
654        print(t.position()) # (-30.00, 0.00)
655        ```
656        """
657        self._go(-distance)

Move the turtle backward by distance.

Aliases: back | backward | bk

Argument: distance -- a number

Move the turtle backward by distance, opposite to the direction the turtle is headed. Do not change the turtle's heading.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's position before and after moving.
print(t.position()) # (0.00, 0.00)
t.backward(30)
print(t.position()) # (-30.00, 0.00)
def bk(self, distance: int | float):
630    def backward(self, distance: int | float):
631        """Move the turtle backward by distance.
632
633        Aliases: `back` | `backward` | `bk`
634
635        Argument:
636        `distance` -- a number
637
638        Move the turtle backward by `distance`, opposite to the direction the
639        turtle is headed. Do not change the turtle's heading.
640
641        **Example**
642        ```python
643        from ipycc.turtle import Turtle, showscreen
644
645        # Show the screen.
646        showscreen()
647
648        # Create a turtle.
649        t = Turtle()
650
651        # Print the turtle's position before and after moving.
652        print(t.position()) # (0.00, 0.00)
653        t.backward(30)
654        print(t.position()) # (-30.00, 0.00)
655        ```
656        """
657        self._go(-distance)

Move the turtle backward by distance.

Aliases: back | backward | bk

Argument: distance -- a number

Move the turtle backward by distance, opposite to the direction the turtle is headed. Do not change the turtle's heading.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's position before and after moving.
print(t.position()) # (0.00, 0.00)
t.backward(30)
print(t.position()) # (-30.00, 0.00)
def right(self, angle: int | float):
667    def right(self, angle: int | float):
668        """Turn turtle right by angle units.
669
670        Aliases: `right` | `rt`
671
672        Argument:
673        `angle` -- a number (integer or float)
674
675        Turn turtle right by `angle` units. (Units are by default degrees,
676        but can be set via the `degrees()` and `radians()` methods.)
677        Angle orientation depends on mode. (See this.)
678
679        **Example**
680        ```python
681        from ipycc.turtle import Turtle, showscreen
682
683        # Show the screen.
684        showscreen()
685
686        # Create a turtle.
687        t = Turtle()
688
689        # Print the turtle's heading before and after turning.
690        print(t.heading()) # 22.0
691        t.right(45)
692        print(t.heading()) # 337.0
693        ```
694        """
695        self._rotate(-angle)

Turn turtle right by angle units.

Aliases: right | rt

Argument: angle -- a number (integer or float)

Turn turtle right by angle units. (Units are by default degrees, but can be set via the degrees() and radians() methods.) Angle orientation depends on mode. (See this.)

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's heading before and after turning.
print(t.heading()) # 22.0
t.right(45)
print(t.heading()) # 337.0
def rt(self, angle: int | float):
667    def right(self, angle: int | float):
668        """Turn turtle right by angle units.
669
670        Aliases: `right` | `rt`
671
672        Argument:
673        `angle` -- a number (integer or float)
674
675        Turn turtle right by `angle` units. (Units are by default degrees,
676        but can be set via the `degrees()` and `radians()` methods.)
677        Angle orientation depends on mode. (See this.)
678
679        **Example**
680        ```python
681        from ipycc.turtle import Turtle, showscreen
682
683        # Show the screen.
684        showscreen()
685
686        # Create a turtle.
687        t = Turtle()
688
689        # Print the turtle's heading before and after turning.
690        print(t.heading()) # 22.0
691        t.right(45)
692        print(t.heading()) # 337.0
693        ```
694        """
695        self._rotate(-angle)

Turn turtle right by angle units.

Aliases: right | rt

Argument: angle -- a number (integer or float)

Turn turtle right by angle units. (Units are by default degrees, but can be set via the degrees() and radians() methods.) Angle orientation depends on mode. (See this.)

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's heading before and after turning.
print(t.heading()) # 22.0
t.right(45)
print(t.heading()) # 337.0
def left(self, angle: int | float):
699    def left(self, angle: int | float):
700        """Turn turtle left by angle units.
701
702        Aliases: `left` | `lt`
703
704        Argument:
705        `angle` -- a number (integer or float)
706
707        Turn turtle left by `angle` units. (Units are by default degrees,
708        but can be set via the `degrees()` and `radians()` methods.)
709        Angle orientation depends on mode.
710
711        **Example**
712        ```python
713        from ipycc.turtle import Turtle, showscreen
714
715        # Show the screen.
716        showscreen()
717
718        # Create a turtle.
719        t = Turtle()
720
721        # Print the turtle's heading before and after turning.
722        print(t.heading()) # 22.0
723        t.left(45)
724        print(t.heading()) # 67.0
725        ```
726        """
727        self._rotate(angle)

Turn turtle left by angle units.

Aliases: left | lt

Argument: angle -- a number (integer or float)

Turn turtle left by angle units. (Units are by default degrees, but can be set via the degrees() and radians() methods.) Angle orientation depends on mode.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's heading before and after turning.
print(t.heading()) # 22.0
t.left(45)
print(t.heading()) # 67.0
def lt(self, angle: int | float):
699    def left(self, angle: int | float):
700        """Turn turtle left by angle units.
701
702        Aliases: `left` | `lt`
703
704        Argument:
705        `angle` -- a number (integer or float)
706
707        Turn turtle left by `angle` units. (Units are by default degrees,
708        but can be set via the `degrees()` and `radians()` methods.)
709        Angle orientation depends on mode.
710
711        **Example**
712        ```python
713        from ipycc.turtle import Turtle, showscreen
714
715        # Show the screen.
716        showscreen()
717
718        # Create a turtle.
719        t = Turtle()
720
721        # Print the turtle's heading before and after turning.
722        print(t.heading()) # 22.0
723        t.left(45)
724        print(t.heading()) # 67.0
725        ```
726        """
727        self._rotate(angle)

Turn turtle left by angle units.

Aliases: left | lt

Argument: angle -- a number (integer or float)

Turn turtle left by angle units. (Units are by default degrees, but can be set via the degrees() and radians() methods.) Angle orientation depends on mode.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's heading before and after turning.
print(t.heading()) # 22.0
t.left(45)
print(t.heading()) # 67.0
def goto( self, x: int | float | tuple | Vec2D, y: int | float = None):
731    def goto(self, x: int | float | tuple | Vec2D, y: int | float = None):
732        """Move turtle to an absolute position.
733
734        Aliases: `setpos` | `setposition` | `goto`:
735
736        Arguments:
737        - `x` -- a number or vector
738        - `y` -- a number (optional)
739
740        Move turtle to an absolute position. If the pen is down,
741        a line will be drawn. The turtle's orientation does not change.
742
743        **Example**
744        ```python
745        from ipycc.turtle import Turtle, showscreen
746
747        # Show the screen.
748        showscreen()
749
750        # Create a turtle.
751        t = Turtle()
752
753        # Print the turtle's position before and after moving.
754        print(t.pos()) # (0.00, 0.00)
755        t.goto(60, 30)
756        print(t.pos()) # (60.00, 30.00)
757        ```
758        """
759        if y is None:
760            self._goto(Vec2D(*x))
761        else:
762            self._goto(Vec2D(x, y))

Move turtle to an absolute position.

Aliases: setpos | setposition | goto:

Arguments:

  • x -- a number or vector
  • y -- a number (optional)

Move turtle to an absolute position. If the pen is down, a line will be drawn. The turtle's orientation does not change.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's position before and after moving.
print(t.pos()) # (0.00, 0.00)
t.goto(60, 30)
print(t.pos()) # (60.00, 30.00)
def setpos( self, x: int | float | tuple | Vec2D, y: int | float = None):
731    def goto(self, x: int | float | tuple | Vec2D, y: int | float = None):
732        """Move turtle to an absolute position.
733
734        Aliases: `setpos` | `setposition` | `goto`:
735
736        Arguments:
737        - `x` -- a number or vector
738        - `y` -- a number (optional)
739
740        Move turtle to an absolute position. If the pen is down,
741        a line will be drawn. The turtle's orientation does not change.
742
743        **Example**
744        ```python
745        from ipycc.turtle import Turtle, showscreen
746
747        # Show the screen.
748        showscreen()
749
750        # Create a turtle.
751        t = Turtle()
752
753        # Print the turtle's position before and after moving.
754        print(t.pos()) # (0.00, 0.00)
755        t.goto(60, 30)
756        print(t.pos()) # (60.00, 30.00)
757        ```
758        """
759        if y is None:
760            self._goto(Vec2D(*x))
761        else:
762            self._goto(Vec2D(x, y))

Move turtle to an absolute position.

Aliases: setpos | setposition | goto:

Arguments:

  • x -- a number or vector
  • y -- a number (optional)

Move turtle to an absolute position. If the pen is down, a line will be drawn. The turtle's orientation does not change.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's position before and after moving.
print(t.pos()) # (0.00, 0.00)
t.goto(60, 30)
print(t.pos()) # (60.00, 30.00)
def setposition( self, x: int | float | tuple | Vec2D, y: int | float = None):
731    def goto(self, x: int | float | tuple | Vec2D, y: int | float = None):
732        """Move turtle to an absolute position.
733
734        Aliases: `setpos` | `setposition` | `goto`:
735
736        Arguments:
737        - `x` -- a number or vector
738        - `y` -- a number (optional)
739
740        Move turtle to an absolute position. If the pen is down,
741        a line will be drawn. The turtle's orientation does not change.
742
743        **Example**
744        ```python
745        from ipycc.turtle import Turtle, showscreen
746
747        # Show the screen.
748        showscreen()
749
750        # Create a turtle.
751        t = Turtle()
752
753        # Print the turtle's position before and after moving.
754        print(t.pos()) # (0.00, 0.00)
755        t.goto(60, 30)
756        print(t.pos()) # (60.00, 30.00)
757        ```
758        """
759        if y is None:
760            self._goto(Vec2D(*x))
761        else:
762            self._goto(Vec2D(x, y))

Move turtle to an absolute position.

Aliases: setpos | setposition | goto:

Arguments:

  • x -- a number or vector
  • y -- a number (optional)

Move turtle to an absolute position. If the pen is down, a line will be drawn. The turtle's orientation does not change.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's position before and after moving.
print(t.pos()) # (0.00, 0.00)
t.goto(60, 30)
print(t.pos()) # (60.00, 30.00)
def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None:
767    def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None:
768        """Instantly move turtle to an absolute position.
769
770        Arguments:
771        - `x` -- a number      or     `None`
772        - `y` -- a number             `None`
773        - `fill_gap` -- a boolean     This argument must be specified by name.
774
775        Move turtle to an absolute position. Unlike `goto(x, y)`, a line will not
776        be drawn. The turtle's orientation does not change. If currently
777        filling, the polygon(s) teleported from will be filled after leaving,
778        and filling will begin again after teleporting. This can be disabled
779        with `fill_gap=True`, which makes the imaginary line traveled during
780        teleporting act as a fill barrier like in `goto(x, y)`.
781
782        **Example**
783        ```python
784        from ipycc.turtle import Turtle, showscreen
785
786        # Show the screen.
787        showscreen()
788
789        # Create a turtle.
790        t = Turtle()
791
792        tp = t.pos()
793        print(tp)      # (0.00,0.00)
794        t.teleport(60)
795        print(t.pos()) # (60.00,0.00)
796        t.teleport(y=10)
797        print(t.pos()) # (60.00,10.00)
798        t.teleport(20, 30)
799        print(t.pos()) # (20.00,30.00)
800        ```
801        """
802        pendown = self.isdown()
803        was_filling = self.filling()
804        if pendown:
805            self.penup()
806        if was_filling and not fill_gap:
807            self.end_fill()
808        new_x = x if x is not None else self._position[0]
809        new_y = y if y is not None else self._position[1]
810        self._position = Vec2D(new_x, new_y)
811        if pendown:
812            self.pendown()
813        if was_filling and not fill_gap:
814            self.begin_fill()
815        self._update()

Instantly move turtle to an absolute position.

Arguments:

  • x -- a number or None
  • y -- a number None
  • fill_gap -- a boolean This argument must be specified by name.

Move turtle to an absolute position. Unlike goto(x, y), a line will not be drawn. The turtle's orientation does not change. If currently filling, the polygon(s) teleported from will be filled after leaving, and filling will begin again after teleporting. This can be disabled with fill_gap=True, which makes the imaginary line traveled during teleporting act as a fill barrier like in goto(x, y).

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

tp = t.pos()
print(tp)      # (0.00,0.00)
t.teleport(60)
print(t.pos()) # (60.00,0.00)
t.teleport(y=10)
print(t.pos()) # (60.00,10.00)
t.teleport(20, 30)
print(t.pos()) # (20.00,30.00)
def setx(self, x: int | float):
817    def setx(self, x: int | float):
818        """Set the turtle's first coordinate to `x`.
819
820        Argument:
821        `x` -- a number (integer or float)
822
823        Set the turtle's first coordinate to `x`, leave second coordinate
824        unchanged.
825
826        **Example**
827        ```python
828        from ipycc.turtle import Turtle, showscreen
829
830        # Show the screen.
831        showscreen()
832
833        # Create a turtle.
834        t = Turtle()
835
836        # Print the turtle's position before and after moving.
837        print(t.position()) # (0.00, 240.00)
838        t.setx(10)
839        print(t.position()) # (10.00, 240.00)
840        ```
841        """
842        self._goto(Vec2D(x, self._position[1]))

Set the turtle's first coordinate to x.

Argument: x -- a number (integer or float)

Set the turtle's first coordinate to x, leave second coordinate unchanged.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's position before and after moving.
print(t.position()) # (0.00, 240.00)
t.setx(10)
print(t.position()) # (10.00, 240.00)
def sety(self, y: int | float):
844    def sety(self, y: int | float):
845        """Set the turtle's second coordinate to `y`.
846
847        Argument:
848        `y` -- a number (integer or float)
849
850        Set the turtle's first coordinate to `x`, second coordinate remains
851        unchanged.
852
853        **Example**
854        ```python
855        from ipycc.turtle import Turtle, showscreen
856
857        # Show the screen.
858        showscreen()
859
860        # Create a turtle.
861        t = Turtle()
862
863        # Print the turtle's position before and after moving.
864        print(t.position()) # (0.00, 40.00)
865        t.sety(-10)
866        print(t.position()) # (0.00, -10.00)
867        ```
868        """
869        self._goto(Vec2D(self._position[0], y))

Set the turtle's second coordinate to y.

Argument: y -- a number (integer or float)

Set the turtle's first coordinate to x, second coordinate remains unchanged.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's position before and after moving.
print(t.position()) # (0.00, 40.00)
t.sety(-10)
print(t.position()) # (0.00, -10.00)
def setheading(self, to_angle: int | float):
871    def setheading(self, to_angle: int | float):
872        """Set the orientation of the turtle to `to_angle`.
873
874        Aliases:  `setheading` | `seth`
875
876        Argument:
877        `to_angle` -- a number (integer or float)
878
879        Set the orientation of the turtle to `to_angle`.
880        Here are some common directions in degrees:
881        - 0 - east
882        - 90 - north
883        - 180 - west
884        - 270 - south
885
886        **Example**
887        ```python
888        from ipycc.turtle import Turtle, showscreen
889
890        # Show the screen.
891        showscreen()
892
893        # Create a turtle.
894        t = Turtle()
895
896        # Set the turtle's heading and print it.
897        t.setheading(90)
898        print(t.heading()) # 90
899        ```
900        """
901        angle = (to_angle - self.heading()) * self._angleOrient
902        full = self._fullcircle
903        half = full / 2.0
904        angle = (angle + half) % full - half
905        self._rotate(angle)

Set the orientation of the turtle to to_angle.

Aliases: setheading | seth

Argument: to_angle -- a number (integer or float)

Set the orientation of the turtle to to_angle. Here are some common directions in degrees:

  • 0 - east
  • 90 - north
  • 180 - west
  • 270 - south

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Set the turtle's heading and print it.
t.setheading(90)
print(t.heading()) # 90
def seth(self, to_angle: int | float):
871    def setheading(self, to_angle: int | float):
872        """Set the orientation of the turtle to `to_angle`.
873
874        Aliases:  `setheading` | `seth`
875
876        Argument:
877        `to_angle` -- a number (integer or float)
878
879        Set the orientation of the turtle to `to_angle`.
880        Here are some common directions in degrees:
881        - 0 - east
882        - 90 - north
883        - 180 - west
884        - 270 - south
885
886        **Example**
887        ```python
888        from ipycc.turtle import Turtle, showscreen
889
890        # Show the screen.
891        showscreen()
892
893        # Create a turtle.
894        t = Turtle()
895
896        # Set the turtle's heading and print it.
897        t.setheading(90)
898        print(t.heading()) # 90
899        ```
900        """
901        angle = (to_angle - self.heading()) * self._angleOrient
902        full = self._fullcircle
903        half = full / 2.0
904        angle = (angle + half) % full - half
905        self._rotate(angle)

Set the orientation of the turtle to to_angle.

Aliases: setheading | seth

Argument: to_angle -- a number (integer or float)

Set the orientation of the turtle to to_angle. Here are some common directions in degrees:

  • 0 - east
  • 90 - north
  • 180 - west
  • 270 - south

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Set the turtle's heading and print it.
t.setheading(90)
print(t.heading()) # 90
def home(self):
909    def home(self):
910        """Move turtle to the origin - coordinates `(0,0)`.
911
912        No arguments.
913
914        Move turtle to the origin and reset its heading to 0.
915
916        **Example**
917        ```python
918        from ipycc.turtle import Turtle, showscreen
919
920        # Show the screen.
921        showscreen()
922
923        # Create a turtle.
924        t = Turtle()
925
926        # Move the turtle forward, then move it back home.
927        t.forward(100)
928        t.home()
929        ```
930        """
931        self.goto(0, 0)
932        self.setheading(0)

Move turtle to the origin - coordinates (0,0).

No arguments.

Move turtle to the origin and reset its heading to 0.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Move the turtle forward, then move it back home.
t.forward(100)
t.home()
def dot(self, size: int = None, *color: str | tuple[int | float]):
934    def dot(self, size: int = None, *color: str | tuple[int | float]):
935        """Draw a dot with diameter size, using color.
936
937        Optional arguments:
938        - `size` -- an integer >= 1 (if given)
939        - `color` -- a colorstring or a numeric color tuple
940
941        Draw a circular dot with diameter size, using `color`.
942        If `size` is not given, the maximum of `pensize+4` and `2*pensize` is
943        used.
944
945        **Example**
946        ```python
947        from ipycc.turtle import Turtle, showscreen
948
949        # Show the screen.
950        showscreen()
951
952        # Create a turtle.
953        t = Turtle()
954
955        # Draw dots.
956        t.dot()
957        t.forward(50)
958        t.dot(20, "blue")
959        t.forward(50)
960        ```
961        """
962        if not color:
963            if isinstance(size, (str, tuple)):
964                color = _SCREEN._colorstr(size)
965                size = self._pensize + max(self._pensize, 4)
966            else:
967                color = self._pencolor
968                if not size:
969                    size = self._pensize + max(self._pensize, 4)
970        else:
971            if size is None:
972                size = self._pensize + max(self._pensize, 4)
973            color = _SCREEN._colorstr(color)
974        self._pen.canvas.save()
975        self._pen.no_stroke()
976        self._pen.fill(color)
977        x, y = self._to_screen_coords(self._position)
978        self._pen.circle(x, y, size)
979        self._pen.canvas.restore()
980        self._update()

Draw a dot with diameter size, using color.

Optional arguments:

  • size -- an integer >= 1 (if given)
  • color -- a colorstring or a numeric color tuple

Draw a circular dot with diameter size, using color. If size is not given, the maximum of pensize+4 and 2*pensize is used.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Draw dots.
t.dot()
t.forward(50)
t.dot(20, "blue")
t.forward(50)
def stamp(self):
 982    def stamp(self):
 983        """Stamp a copy of the turtleshape onto the canvas.
 984
 985        No argument.
 986
 987        Stamp a copy of the turtle shape onto the canvas at the current
 988        turtle position.
 989
 990        **Example**
 991        ```python
 992        from ipycc.turtle import Turtle, showscreen
 993
 994        # Show the screen.
 995        showscreen()
 996
 997        # Create a turtle.
 998        t = Turtle()
 999
1000        # Draw a stamp and move.
1001        t.color("blue")
1002        t.stamp()
1003        t.forward(50)
1004        ```
1005        """
1006        self._pen.canvas.save()
1007        x, y = self._to_screen_coords(self._position)
1008        self._pen.translate(x, y)
1009        angle = math.radians(self.heading()) - math.pi / 2
1010        self._pen.rotate(angle)
1011        self._pen.stroke(self._pencolor)
1012        self._pen.stroke_weight(self._outlinewidth)
1013        self._pen.fill(self._fillcolor)
1014        self._pen.begin_shape()
1015        shape = _turtle_shapes[self._shape]
1016        for v in shape:
1017            sx, sy = self._stretchfactor
1018            self._pen.vertex(sx * v[0], sy * v[1])
1019        self._pen.end_shape()
1020        self._pen.reset_matrix()
1021        self._pen.canvas.restore()
1022        self._update()

Stamp a copy of the turtleshape onto the canvas.

No argument.

Stamp a copy of the turtle shape onto the canvas at the current turtle position.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Draw a stamp and move.
t.color("blue")
t.stamp()
t.forward(50)
def speed(self, speed: int | float | str = None) -> None | int:
1024    def speed(self, speed: int | float | str = None) -> None | int:
1025        """Return or set the turtle's speed.
1026
1027        Optional argument:
1028        `speed` -- an integer in the range `0..10` or a `speedstring`
1029        (see below)
1030
1031        Set the turtle's speed to an integer value in the range `0..10`.
1032        If no argument is given: return current speed.
1033
1034        If input is a number greater than 10 or smaller than 0.5,
1035        speed is set to 0.
1036        Speedstrings  are mapped to speedvalues in the following way:
1037        - `'fastest'` :  0
1038        - `'fast'`    :  10
1039        - `'normal'`  :  6
1040        - `'slow'`    :  3
1041        - `'slowest'` :  1
1042        speeds from 1 to 10 enforce increasingly faster animation of
1043        line drawing and turtle turning.
1044
1045        Attention:
1046        `speed = 0` : *no* animation takes place. forward/back makes turtle jump
1047        and likewise left/right make the turtle turn instantly.
1048
1049        **Example**
1050        ```python
1051        from ipycc.turtle import Turtle, showscreen
1052
1053        # Show the screen.
1054        showscreen()
1055
1056        # Create a turtle.
1057        t = Turtle()
1058
1059        # Set the turtle's speed.
1060        t.speed(3)
1061        ```
1062        """
1063        speeds = {"fastest": 0, "fast": 10, "normal": 6, "slow": 3, "slowest": 1}
1064        if speed is None:
1065            return self._speed
1066        if speed in speeds:
1067            speed = speeds[speed]
1068        elif 0.5 < speed < 10.5:
1069            speed = int(round(speed))
1070        else:
1071            speed = 0
1072        self._speed = speed

Return or set the turtle's speed.

Optional argument: speed -- an integer in the range 0..10 or a speedstring (see below)

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 in the following way:

  • '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 : no animation takes place. forward/back makes turtle jump and likewise left/right make the turtle turn instantly.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Set the turtle's speed.
t.speed(3)
def position(self) -> Vec2D:
1074    def position(self) -> Vec2D:
1075        """Return the turtle's current location `(x,y)`, as a `Vec2D`.
1076
1077        Aliases: `pos` | `position`
1078
1079        No arguments.
1080
1081        **Example**
1082        ```python
1083        from ipycc.turtle import Turtle, showscreen
1084
1085        # Show the screen.
1086        showscreen()
1087
1088        # Create a turtle.
1089        t = Turtle()
1090
1091        # Print the turtle's position.
1092        print(t.pos()) # (0.00, 0.00)
1093        ```
1094        """
1095        return self._position

Return the turtle's current location (x,y), as a Vec2D.

Aliases: pos | position

No arguments.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's position.
print(t.pos()) # (0.00, 0.00)
def pos(self) -> Vec2D:
1074    def position(self) -> Vec2D:
1075        """Return the turtle's current location `(x,y)`, as a `Vec2D`.
1076
1077        Aliases: `pos` | `position`
1078
1079        No arguments.
1080
1081        **Example**
1082        ```python
1083        from ipycc.turtle import Turtle, showscreen
1084
1085        # Show the screen.
1086        showscreen()
1087
1088        # Create a turtle.
1089        t = Turtle()
1090
1091        # Print the turtle's position.
1092        print(t.pos()) # (0.00, 0.00)
1093        ```
1094        """
1095        return self._position

Return the turtle's current location (x,y), as a Vec2D.

Aliases: pos | position

No arguments.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's position.
print(t.pos()) # (0.00, 0.00)
def towards( self, x: int | float | tuple | Vec2D, y: int | float = None) -> float:
1099    def towards(self, x: int | float | tuple | Vec2D, y: int | float = None) -> float:
1100        """Return the angle of the line from the turtle's position to `(x,y)`.
1101
1102        Arguments:
1103        - `x` -- a number   or  a pair/vector of numbers   or   a turtle instance
1104        - `y` -- a number (optional)
1105
1106        Return the angle, between the line from turtle-position to position
1107        specified by `x`, `y` and the turtle's start orientation.
1108
1109        **Example**
1110        ```python
1111        from ipycc.turtle import Turtle, showscreen, Vec2D
1112
1113        # Show the screen.
1114        showscreen()
1115
1116        # Create a turtle.
1117        t = Turtle()
1118
1119        # Print the turtle's position and heading.
1120        print(t.pos()) # (10.00, 10.00)
1121        print(t.towards(0, 0)) # 225.0
1122        print(t.towards((0, 0))) # 225.0
1123        v = Vec2D(0, 0)
1124        print(t.towards(v)) # 225.0
1125        ```
1126        """
1127        if y is not None:
1128            pos = Vec2D(x, y)
1129        if isinstance(x, Vec2D):
1130            pos = x
1131        elif isinstance(x, tuple):
1132            pos = Vec2D(*x)
1133        elif isinstance(x, Turtle):
1134            pos = x._position
1135        x, y = pos - self._position
1136        result = round(math.degrees(math.atan2(y, x)), 10) % 360.0
1137        result /= self._degreesPerAU
1138        return (self._angleOffset + self._angleOrient * result) % self._fullcircle

Return the angle of the line from the turtle's position to (x,y).

Arguments:

  • x -- a number or a pair/vector of numbers or a turtle instance
  • y -- a number (optional)

Return the angle, between the line from turtle-position to position specified by x, y and the turtle's start orientation.

Example

from ipycc.turtle import Turtle, showscreen, Vec2D

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's position and heading.
print(t.pos()) # (10.00, 10.00)
print(t.towards(0, 0)) # 225.0
print(t.towards((0, 0))) # 225.0
v = Vec2D(0, 0)
print(t.towards(v)) # 225.0
def xcor(self) -> float:
1140    def xcor(self) -> float:
1141        """Return the turtle's x coordinate.
1142
1143        No arguments.
1144
1145        **Example**
1146        ```python
1147        from ipycc.turtle import Turtle, showscreen
1148
1149        # Show the screen.
1150        showscreen()
1151
1152        # Create a turtle.
1153        t = Turtle()
1154
1155        # Move the turtle and print its x-coordinate.
1156        t.left(60)
1157        t.forward(100)
1158        print(tutrtle.xcor()) # 50.0
1159        ```
1160        """
1161        return self._position[0]

Return the turtle's x coordinate.

No arguments.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Move the turtle and print its x-coordinate.
t.left(60)
t.forward(100)
print(tutrtle.xcor()) # 50.0
def ycor(self) -> float:
1163    def ycor(self) -> float:
1164        """Return the turtle's y coordinate.
1165
1166        No arguments.
1167
1168        **Example**
1169        ```python
1170        from ipycc.turtle import Turtle, showscreen
1171
1172        # Show the screen.
1173        showscreen()
1174
1175        # Create a turtle.
1176        t = Turtle()
1177
1178        # Move the turtle and print its y-coordinate.
1179        t.left(60)
1180        t.forward(100)
1181        print(t.ycor()) # 86.6025403784
1182        ```
1183        """
1184        return self._position[1]

Return the turtle's y coordinate.

No arguments.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Move the turtle and print its y-coordinate.
t.left(60)
t.forward(100)
print(t.ycor()) # 86.6025403784
def heading(self) -> float:
1186    def heading(self) -> float:
1187        """Return the turtle's current heading.
1188
1189        No arguments.
1190
1191        **Example**
1192        ```python
1193        from ipycc.turtle import Turtle, showscreen
1194
1195        # Show the screen.
1196        showscreen()
1197
1198        # Create a turtle.
1199        t = Turtle()
1200
1201        # Turn the turtle and print its heading.
1202        t.left(67)
1203        print(t.heading()) # 67.0
1204        ```
1205        """
1206        x, y = self._orient
1207        result = round(math.degrees(math.atan2(y, x)), 10) % 360.0
1208        result /= self._degreesPerAU
1209        return (self._angleOffset + self._angleOrient*result) % self._fullcircle

Return the turtle's current heading.

No arguments.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Turn the turtle and print its heading.
t.left(67)
print(t.heading()) # 67.0
def distance(self, x, y: int | float = None) -> float:
1211    def distance(self, x, y: int | float = None) -> float:
1212        """Return the distance from the turtle to `(x,y)` in turtle step units.
1213
1214        Arguments:
1215        - `x` -- a number or a pair/vector of numbers or a `Turtle` instance
1216        - `y` -- a number (optional)
1217
1218        **Example**
1219        ```python
1220        from ipycc.turtle import Turtle, showscreen
1221
1222        # Show the screen.
1223        showscreen()
1224
1225        # Create a turtle.
1226        t = Turtle()
1227
1228        # Print the turtle's position and distance to a point.
1229        print(t.pos()) # (0.00, 0.00)
1230        print(t.distance(30, 40)) # 50.0
1231
1232        # Create another turtle.
1233        t2 = Turtle()
1234
1235        # Move the second turtle and print its distance from
1236        # the first turtle.
1237        t2.forward(77)
1238        print(t.distance(t2)) # 77.0
1239        ```
1240        """
1241        if y is not None:
1242            pos = Vec2D(x, y)
1243        if isinstance(x, Vec2D):
1244            pos = x
1245        elif isinstance(x, tuple):
1246            pos = Vec2D(*x)
1247        elif isinstance(x, Turtle):
1248            pos = x._position
1249        return abs(pos - self._position)

Return the distance from the turtle to (x,y) in turtle step units.

Arguments:

  • x -- a number or a pair/vector of numbers or a Turtle instance
  • y -- a number (optional)

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's position and distance to a point.
print(t.pos()) # (0.00, 0.00)
print(t.distance(30, 40)) # 50.0

# Create another turtle.
t2 = Turtle()

# Move the second turtle and print its distance from
# the first turtle.
t2.forward(77)
print(t.distance(t2)) # 77.0
def degrees(self, fullcircle: int | float = 360.0):
1257    def degrees(self, fullcircle: int | float = 360.0):
1258        """Set angle measurement units to degrees.
1259
1260        Optional argument:
1261        `fullcircle` -  a number
1262
1263        Set angle measurement units, i. e. set number
1264        of 'degrees' for a full circle. Default value is
1265        360 degrees.
1266
1267        **Example**
1268        ```python
1269        from ipycc.turtle import Turtle, showscreen
1270
1271        # Show the screen.
1272        showscreen()
1273
1274        # Create a turtle.
1275        t = Turtle()
1276
1277        # Turn the turtle and print its heading.
1278        t.left(90)
1279        print(t.heading()) # 90
1280
1281        # Change angle measurement unit to grad (also known as gon,
1282        # grade, or gradian and equals 1/100-th of the right angle.)
1283        t.degrees(400.0)
1284        print(t.heading()) # 100
1285        ```
1286        """
1287        self._setDegreesPerAU(fullcircle)

Set angle measurement units to degrees.

Optional argument: fullcircle - a number

Set angle measurement units, i. e. set number of 'degrees' for a full circle. Default value is 360 degrees.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Turn the turtle and print its heading.
t.left(90)
print(t.heading()) # 90

# Change angle measurement unit to grad (also known as gon,
# grade, or gradian and equals 1/100-th of the right angle.)
t.degrees(400.0)
print(t.heading()) # 100
def radians(self):
1289    def radians(self):
1290        """Set the angle measurement units to radians.
1291
1292        No arguments.
1293
1294        **Example**
1295        ```python
1296        from ipycc.turtle import Turtle, showscreen
1297
1298        # Show the screen.
1299        showscreen()
1300
1301        # Create a turtle.
1302        t = Turtle()
1303
1304        # Print the turtle's heading in degrees and radians.
1305        print(t.heading()) # 90
1306        t.radians()
1307        print(t.heading()) # 1.5707963267948966
1308        ```
1309        """
1310        self._setDegreesPerAU(math.tau)

Set the angle measurement units to radians.

No arguments.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's heading in degrees and radians.
print(t.heading()) # 90
t.radians()
print(t.heading()) # 1.5707963267948966
def pendown(self):
1316    def pendown(self):
1317        """Pull the pen down -- drawing when moving.
1318
1319        Aliases: `pendown` | `pd` | `down`
1320
1321        No argument.
1322
1323        **Example**
1324        ```python
1325        from ipycc.turtle import Turtle, showscreen
1326
1327        # Show the screen.
1328        showscreen()
1329
1330        # Create a turtle.
1331        t = Turtle()
1332
1333        # Put the turtle's pen down and move.
1334        t.pendown()
1335        t.forward(100)
1336        ```
1337        """
1338        self._drawing = True

Pull the pen down -- drawing when moving.

Aliases: pendown | pd | down

No argument.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Put the turtle's pen down and move.
t.pendown()
t.forward(100)
def pd(self):
1316    def pendown(self):
1317        """Pull the pen down -- drawing when moving.
1318
1319        Aliases: `pendown` | `pd` | `down`
1320
1321        No argument.
1322
1323        **Example**
1324        ```python
1325        from ipycc.turtle import Turtle, showscreen
1326
1327        # Show the screen.
1328        showscreen()
1329
1330        # Create a turtle.
1331        t = Turtle()
1332
1333        # Put the turtle's pen down and move.
1334        t.pendown()
1335        t.forward(100)
1336        ```
1337        """
1338        self._drawing = True

Pull the pen down -- drawing when moving.

Aliases: pendown | pd | down

No argument.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Put the turtle's pen down and move.
t.pendown()
t.forward(100)
def down(self):
1316    def pendown(self):
1317        """Pull the pen down -- drawing when moving.
1318
1319        Aliases: `pendown` | `pd` | `down`
1320
1321        No argument.
1322
1323        **Example**
1324        ```python
1325        from ipycc.turtle import Turtle, showscreen
1326
1327        # Show the screen.
1328        showscreen()
1329
1330        # Create a turtle.
1331        t = Turtle()
1332
1333        # Put the turtle's pen down and move.
1334        t.pendown()
1335        t.forward(100)
1336        ```
1337        """
1338        self._drawing = True

Pull the pen down -- drawing when moving.

Aliases: pendown | pd | down

No argument.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Put the turtle's pen down and move.
t.pendown()
t.forward(100)
def penup(self):
1343    def penup(self):
1344        """Pull the pen up -- no drawing when moving.
1345
1346        Aliases: `penup` | `pu` | `up`
1347
1348        No argument
1349
1350        **Example**
1351        ```python
1352        from ipycc.turtle import Turtle, showscreen
1353
1354        # Show the screen.
1355        showscreen()
1356
1357        # Create a turtle.
1358        t = Turtle()
1359
1360        # Pick the turtle's pen up and move.
1361        t.penup()
1362        t.forward(100)
1363        ```
1364        """
1365        self._drawing = False

Pull the pen up -- no drawing when moving.

Aliases: penup | pu | up

No argument

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Pick the turtle's pen up and move.
t.penup()
t.forward(100)
def pu(self):
1343    def penup(self):
1344        """Pull the pen up -- no drawing when moving.
1345
1346        Aliases: `penup` | `pu` | `up`
1347
1348        No argument
1349
1350        **Example**
1351        ```python
1352        from ipycc.turtle import Turtle, showscreen
1353
1354        # Show the screen.
1355        showscreen()
1356
1357        # Create a turtle.
1358        t = Turtle()
1359
1360        # Pick the turtle's pen up and move.
1361        t.penup()
1362        t.forward(100)
1363        ```
1364        """
1365        self._drawing = False

Pull the pen up -- no drawing when moving.

Aliases: penup | pu | up

No argument

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Pick the turtle's pen up and move.
t.penup()
t.forward(100)
def up(self):
1343    def penup(self):
1344        """Pull the pen up -- no drawing when moving.
1345
1346        Aliases: `penup` | `pu` | `up`
1347
1348        No argument
1349
1350        **Example**
1351        ```python
1352        from ipycc.turtle import Turtle, showscreen
1353
1354        # Show the screen.
1355        showscreen()
1356
1357        # Create a turtle.
1358        t = Turtle()
1359
1360        # Pick the turtle's pen up and move.
1361        t.penup()
1362        t.forward(100)
1363        ```
1364        """
1365        self._drawing = False

Pull the pen up -- no drawing when moving.

Aliases: penup | pu | up

No argument

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Pick the turtle's pen up and move.
t.penup()
t.forward(100)
def pensize(self, width: int | float = None) -> None | float:
1370    def pensize(self, width: int | float = None) -> None | float:
1371        """Set or return the line thickness.
1372
1373        Aliases:  `pensize` | `width`
1374
1375        Argument:
1376        `width` -- positive number
1377
1378        Set the line thickness to `width` or return it. If no argument is
1379        given, current pensize is returned.
1380
1381        **Example**
1382        ```python
1383        from ipycc.turtle import Turtle, showscreen
1384
1385        # Show the screen.
1386        showscreen()
1387
1388        # Create a turtle.
1389        t = Turtle()
1390
1391        # Print the turtle's pen size and move.
1392        print(t.pensize()) # 1
1393        t.forward(50)
1394
1395        # Change the turtle's pen size and move.
1396        t.pensize(10)   # from here on lines of width 10 are drawn
1397        t.forward(50)
1398        ```
1399        """
1400        if width is None:
1401            return self._pensize
1402        self._pensize = width
1403        self._pen.stroke_weight(self._pensize)

Set or return the line thickness.

Aliases: pensize | width

Argument: width -- positive number

Set the line thickness to width or return it. If no argument is given, current pensize is returned.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's pen size and move.
print(t.pensize()) # 1
t.forward(50)

# Change the turtle's pen size and move.
t.pensize(10)   # from here on lines of width 10 are drawn
t.forward(50)
def width(self, width: int | float = None) -> None | float:
1370    def pensize(self, width: int | float = None) -> None | float:
1371        """Set or return the line thickness.
1372
1373        Aliases:  `pensize` | `width`
1374
1375        Argument:
1376        `width` -- positive number
1377
1378        Set the line thickness to `width` or return it. If no argument is
1379        given, current pensize is returned.
1380
1381        **Example**
1382        ```python
1383        from ipycc.turtle import Turtle, showscreen
1384
1385        # Show the screen.
1386        showscreen()
1387
1388        # Create a turtle.
1389        t = Turtle()
1390
1391        # Print the turtle's pen size and move.
1392        print(t.pensize()) # 1
1393        t.forward(50)
1394
1395        # Change the turtle's pen size and move.
1396        t.pensize(10)   # from here on lines of width 10 are drawn
1397        t.forward(50)
1398        ```
1399        """
1400        if width is None:
1401            return self._pensize
1402        self._pensize = width
1403        self._pen.stroke_weight(self._pensize)

Set or return the line thickness.

Aliases: pensize | width

Argument: width -- positive number

Set the line thickness to width or return it. If no argument is given, current pensize is returned.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's pen size and move.
print(t.pensize()) # 1
t.forward(50)

# Change the turtle's pen size and move.
t.pensize(10)   # from here on lines of width 10 are drawn
t.forward(50)
def isdown(self) -> bool:
1407    def isdown(self) -> bool:
1408        """Return `True` if pen is down, `False` if it's up.
1409
1410        No argument.
1411
1412        **Example**
1413        ```python
1414        from ipycc.turtle import Turtle, showscreen
1415
1416        # Show the screen.
1417        showscreen()
1418
1419        # Create a turtle.
1420        t = Turtle()
1421
1422        # Pick the turtle's pen up and print its state.
1423        t.penup()
1424        print(t.isdown()) # False
1425        # Put the turtle's pen down and print its state.
1426        t.pendown()
1427        print(t.isdown()) # True
1428        ```
1429        """
1430        return self._drawing

Return True if pen is down, False if it's up.

No argument.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Pick the turtle's pen up and print its state.
t.penup()
print(t.isdown()) # False
# Put the turtle's pen down and print its state.
t.pendown()
print(t.isdown()) # True
def color(self, *args) -> None | str | tuple:
1432    def color(self, *args) -> None | str | tuple:
1433        """Return or set the pencolor and fillcolor.
1434
1435        Arguments:
1436        Several input formats are allowed.
1437        They use 0, 1, 2, or 3 arguments as follows:
1438
1439        - `color()` returns the current pencolor and the current fillcolor
1440        as a pair of color specification strings.
1441        - `color(colorstring)`, `color((r,g,b))`, `color(r,g,b)` sets both
1442        `fillcolor()` and `pencolor()` to the given value.
1443        - `color(colorstring1, colorstring2)`, `color((r1,g1,b1), (r2,g2,b2))`
1444        sets `pencolor(colorstring1)` and `fillcolor(colorstring2)` or
1445        `pencolor((r1,g1,b1))` and `fillcolor((r2,g2,b2))`.
1446
1447        If turtleshape is a polygon, outline and interior of that polygon
1448        is drawn with the newly set colors.
1449
1450        For more info see: `pencolor()`, `fillcolor()`
1451
1452        **Example**
1453        ```python
1454        from ipycc.turtle import Turtle, showscreen
1455
1456        # Show the screen.
1457        showscreen()
1458
1459        # Create a turtle.
1460        t = Turtle()
1461
1462        # Set the turtle's pen and fill color, then print them.
1463        t.color('red', 'green')
1464        print(t.color()) # ('red', 'green')
1465        # Change the color mode.
1466        t.colormode(255)
1467        # Set the turtle's pen and fill color, then print them.
1468        t.color((40, 80, 120), (160, 200, 240))
1469        print(t.color()) # ('#285078', '#a0c8f0')
1470        ```
1471        """
1472        if args:
1473            l = len(args)
1474            if l == 1:
1475                pcolor = fcolor = args[0]
1476            elif l == 2:
1477                pcolor, fcolor = args
1478            elif l == 3:
1479                pcolor = fcolor = args
1480            pcolor = _SCREEN._colorstr(pcolor)
1481            fcolor = _SCREEN._colorstr(fcolor)
1482            self._pencolor = pcolor
1483            self._pen.stroke(self._pencolor)
1484            self._pen.stroke_weight(self._pensize)
1485            self._fillcolor = fcolor
1486            self._pen.fill(self._fillcolor)
1487            self._update()
1488        else:
1489            return _SCREEN._color(self._pencolor), _SCREEN._color(self._fillcolor)

Return or set the pencolor and fillcolor.

Arguments: Several input formats are allowed. They use 0, 1, 2, or 3 arguments as follows:

  • color() returns the current pencolor and the current fillcolor as a pair of color specification strings.
  • color(colorstring), color((r,g,b)), color(r,g,b) sets both fillcolor() and pencolor() to the given value.
  • color(colorstring1, colorstring2), color((r1,g1,b1), (r2,g2,b2)) sets pencolor(colorstring1) and fillcolor(colorstring2) or pencolor((r1,g1,b1)) and fillcolor((r2,g2,b2)).

If turtleshape is a polygon, outline and interior of that polygon is drawn with the newly set colors.

For more info see: pencolor(), fillcolor()

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Set the turtle's pen and fill color, then print them.
t.color('red', 'green')
print(t.color()) # ('red', 'green')
# Change the color mode.
t.colormode(255)
# Set the turtle's pen and fill color, then print them.
t.color((40, 80, 120), (160, 200, 240))
print(t.color()) # ('#285078', '#a0c8f0')
def pencolor(self, *args) -> None | str | tuple:
1491    def pencolor(self, *args) -> None | str | tuple:
1492        """ Return or set the pencolor.
1493
1494        Arguments:
1495        Four input formats are allowed:
1496          - `pencolor()`
1497            Return the current pencolor as color specification string,
1498            possibly in hex-number format (see example).
1499            May be used as input to another color/pencolor/fillcolor call.
1500          - `pencolor(colorstring)`
1501            a [Tk color specification string](https://www.tcl-lang.org/man/tcl8.4/TkCmd/colors.htm),
1502            such as `"red"` or `"yellow"`
1503          - `pencolor((r, g, b))`
1504            *a tuple* of `r`, `g`, and `b`, which represent, an RGB color,
1505            and each of `r`, `g`, and `b` are in the range `0..colormode`,
1506            where `colormode` is either 1.0 or 255
1507          - `pencolor(r, g, b)`
1508            `r`, `g`, and `b` represent an RGB color, and each of `r`, `g`,
1509            and `b` are in the range `0..colormode`
1510
1511        If turtleshape is a polygon, the outline of that polygon is drawn
1512        with the newly set pencolor.
1513
1514        **Example**
1515        ```python
1516        from ipycc.turtle import Turtle, showscreen
1517
1518        # Show the screen.
1519        showscreen()
1520
1521        # Create a turtle.
1522        t = Turtle()
1523
1524        # Set the turtle's pen color to brown, then print it.
1525        t.pencolor('brown')
1526        print(t.pencolor()) # 'brown'
1527        # Set the turtle's pen color using a tuple, then print it.
1528        tup = (0.2, 0.8, 0.55)
1529        t.pencolor(tup)
1530        print(t.pencolor()) # '#33cc8c'
1531        ```
1532        """
1533        if args:
1534            color = _SCREEN._colorstr(args)
1535            if color == self._pencolor:
1536                return
1537            self._pencolor = color
1538            self._pen.stroke(self._pencolor)
1539            self._pen.stroke_weight(self._pensize)
1540            self._update()
1541        else:
1542            return _SCREEN._color(self._pencolor)

Return or set the pencolor.

Arguments: Four input formats are allowed:

  • pencolor() Return the current pencolor as color specification string, possibly in hex-number format (see example). May be used as input to another color/pencolor/fillcolor call.
  • pencolor(colorstring) a Tk color specification string, such as "red" or "yellow"
  • pencolor((r, g, b)) a tuple of r, g, and b, which represent, an RGB color, and each of r, g, and b are in the range 0..colormode, where colormode is either 1.0 or 255
  • pencolor(r, g, b) r, g, and b represent an RGB color, and each of r, g, and b are in the range 0..colormode

If turtleshape is a polygon, the outline of that polygon is drawn with the newly set pencolor.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Set the turtle's pen color to brown, then print it.
t.pencolor('brown')
print(t.pencolor()) # 'brown'
# Set the turtle's pen color using a tuple, then print it.
tup = (0.2, 0.8, 0.55)
t.pencolor(tup)
print(t.pencolor()) # '#33cc8c'
def fillcolor(self, *args) -> None | str | tuple:
1544    def fillcolor(self, *args) -> None | str | tuple:
1545        """Return or set the fillcolor.
1546
1547        Arguments:
1548        Four input formats are allowed:
1549          - `fillcolor()`
1550            Return the current fillcolor as color specification string,
1551            possibly in hex-number format (see example).
1552            May be used as input to another color/pencolor/fillcolor call.
1553          - `fillcolor(colorstring)`
1554            a [Tk color specification string](https://www.tcl-lang.org/man/tcl8.4/TkCmd/colors.htm),
1555            such as `"red"` or `"yellow"`
1556          - `fillcolor((r, g, b))`
1557            *a tuple* of `r`, `g`, and `b`, which represent, an RGB color,
1558            and each of `r`, `g`, and `b` are in the range `0..colormode`,
1559            where `colormode` is either 1.0 or 255
1560          - `fillcolor(r, g, b)`
1561            `r`, `g`, and `b` represent an RGB color, and each of `r`, `g`, and `b`
1562            are in the range `0..colormode`
1563
1564        If turtleshape is a polygon, the interior of that polygon is drawn
1565        with the newly set fillcolor.
1566
1567        **Example**
1568        ```python
1569        from ipycc.turtle import Turtle, showscreen
1570
1571        # Show the screen.
1572        showscreen()
1573
1574        # Create a turtle.
1575        t = Turtle()
1576
1577        # Set the turtle's fill color to violet.
1578        t.fillcolor('violet')
1579        # Set the turtle's fill color to its pen color.
1580        col = t.pencolor()
1581        t.fillcolor(col)
1582        # Set the turtle's fill color using RGB values.
1583        t.fillcolor(0, 0.5, 0)
1584        ```
1585        """
1586        if args:
1587            color = _SCREEN._colorstr(args)
1588            if color == self._fillcolor:
1589                return
1590            self._fillcolor = color
1591            self._pen.fill(self._fillcolor)
1592            self._update()
1593        else:
1594            return _SCREEN._color(self._fillcolor)

Return or set the fillcolor.

Arguments: Four input formats are allowed:

  • fillcolor() Return the current fillcolor as color specification string, possibly in hex-number format (see example). May be used as input to another color/pencolor/fillcolor call.
  • fillcolor(colorstring) a Tk color specification string, such as "red" or "yellow"
  • fillcolor((r, g, b)) a tuple of r, g, and b, which represent, an RGB color, and each of r, g, and b are in the range 0..colormode, where colormode is either 1.0 or 255
  • fillcolor(r, g, b) r, g, and b represent an RGB color, and each of r, g, and b are in the range 0..colormode

If turtleshape is a polygon, the interior of that polygon is drawn with the newly set fillcolor.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Set the turtle's fill color to violet.
t.fillcolor('violet')
# Set the turtle's fill color to its pen color.
col = t.pencolor()
t.fillcolor(col)
# Set the turtle's fill color using RGB values.
t.fillcolor(0, 0.5, 0)
def filling(self) -> bool:
1596    def filling(self) -> bool:
1597        """Return fillstate (`True` if filling, `False` otherwise).
1598
1599        No argument.
1600
1601        **Example**
1602        ```python
1603        from ipycc.turtle import Turtle, showscreen
1604
1605        # Show the screen.
1606        showscreen()
1607
1608        # Create a turtle.
1609        t = Turtle()
1610
1611        # Begin filling.
1612        t.begin_fill()
1613        # Change the turtle's pen size if it is filling.
1614        if t.filling():
1615            t.pensize(5)
1616        else:
1617            t.pensize(3)
1618        ```
1619        """
1620        return isinstance(self._fillpath, list)

Return fillstate (True if filling, False otherwise).

No argument.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Begin filling.
t.begin_fill()
# Change the turtle's pen size if it is filling.
if t.filling():
    t.pensize(5)
else:
    t.pensize(3)
@contextmanager
def fill(self):
1622    @contextmanager
1623    def fill(self):
1624        """A context manager for filling a shape.
1625
1626        No argument.
1627
1628        Implicitly ensures the code block is wrapped with
1629        `begin_fill()` and `end_fill()`.
1630
1631        **Example**
1632        ```python
1633        from ipycc.turtle import Turtle, showscreen
1634
1635        # Show the screen.
1636        showscreen()
1637
1638        # Create a turtle.
1639        t = Turtle()
1640        t.color("black", "red")
1641
1642        # Fill.
1643        with t.fill():
1644            t.circle(60)
1645        ```
1646        """
1647        self.begin_fill()
1648        try:
1649            yield
1650        finally:
1651            self.end_fill()

A context manager for filling a shape.

No argument.

Implicitly ensures the code block is wrapped with begin_fill() and end_fill().

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()
t.color("black", "red")

# Fill.
with t.fill():
    t.circle(60)
def begin_fill(self):
1653    def begin_fill(self):
1654        """Called just before drawing a shape to be filled.
1655
1656        No argument.
1657
1658        **Example**
1659        ```python
1660        from ipycc.turtle import Turtle, showscreen
1661
1662        # Show the screen.
1663        showscreen()
1664
1665        # Create a turtle.
1666        t = Turtle()
1667
1668        # Set the turtle's pen and fill colors.
1669        t.color("black", "red")
1670
1671        # Begin filling.
1672        t.begin_fill()
1673        t.circle(60)
1674        # Stop filling.
1675        t.end_fill()
1676        ```
1677        """
1678        self._fillpath = [self._position]

Called just before drawing a shape to be filled.

No argument.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Set the turtle's pen and fill colors.
t.color("black", "red")

# Begin filling.
t.begin_fill()
t.circle(60)
# Stop filling.
t.end_fill()
def end_fill(self):
1680    def end_fill(self):
1681        """Fill the shape drawn after the call `begin_fill()`.
1682
1683        No argument.
1684
1685        **Example**
1686        ```python
1687        from ipycc.turtle import Turtle, showscreen
1688
1689        # Show the screen.
1690        showscreen()
1691
1692        # Create a turtle.
1693        t = Turtle()
1694
1695        # Set the turtle's pen and fill color.
1696        t.color("black", "red")
1697    
1698        # Begin filling.
1699        t.begin_fill()
1700        t.circle(60)
1701        # Stop filling.
1702        t.end_fill()
1703        ```
1704        """
1705        if self.filling():
1706            if len(self._fillpath) > 2:
1707                self._pen.begin_shape()
1708                for v in self._fillpath:
1709                    x, y = self._to_screen_coords(v)
1710                    self._pen.vertex(x, y)
1711                self._pen.end_shape()
1712            self._fillpath = None
1713            self._update()

Fill the shape drawn after the call begin_fill().

No argument.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Set the turtle's pen and fill color.
t.color("black", "red")

# Begin filling.
t.begin_fill()
t.circle(60)
# Stop filling.
t.end_fill()
@contextmanager
def poly(self):
1715    @contextmanager
1716    def poly(self):
1717        """A context manager for recording the vertices of a polygon.
1718
1719        No argument.
1720
1721        Implicitly ensures that the code block is wrapped with
1722        `begin_poly()` and `end_poly()`
1723
1724        **Example**
1725        ```python
1726        from ipycc.turtle import Turtle, showscreen
1727
1728        # Show the screen.
1729        showscreen()
1730
1731        # Create a turtle.
1732        t = Turtle()
1733
1734        # Set the turtle's pen and fill color.
1735        t.color("black", "red")
1736
1737        # Begin filling.
1738        t.begin_fill()
1739
1740        # Create a polygon.
1741        with t.poly():
1742            for i in range(4):
1743                t.forward(50)
1744                t.left(90)
1745        
1746        # Stop filling.
1747        t.end_fill()
1748        ```
1749        """
1750        self.begin_poly()
1751        try:
1752            yield
1753        finally:
1754            self.end_poly()

A context manager for recording the vertices of a polygon.

No argument.

Implicitly ensures that the code block is wrapped with begin_poly() and end_poly()

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Set the turtle's pen and fill color.
t.color("black", "red")

# Begin filling.
t.begin_fill()

# Create a polygon.
with t.poly():
    for i in range(4):
        t.forward(50)
        t.left(90)

# Stop filling.
t.end_fill()
def begin_poly(self):
1756    def begin_poly(self):
1757        """Start recording the vertices of a polygon.
1758
1759        No argument.
1760
1761        Start recording the vertices of a polygon. Current turtle position
1762        is first point of polygon.
1763
1764        **Example**
1765        ```python
1766        from ipycc.turtle import Turtle, showscreen
1767
1768        # Show the screen.
1769        showscreen()
1770
1771        # Create a turtle.
1772        t = Turtle()
1773
1774        # Set the turtle's pen and fill color.
1775        t.color("black", "red")
1776
1777        # Begin filling.
1778        t.begin_fill()
1779
1780        # Begin creating a polygon.
1781        t.begin_poly()
1782        for i in range(4):
1783            t.forward(50)
1784            t.left(90)
1785
1786        # Stop creating a polygon.
1787        t.end_poly()
1788
1789        # Stop filling.
1790        t.end_fill()
1791        ```
1792        """
1793        self._poly = [self._position]
1794        self._creatingPoly = True

Start recording the vertices of a polygon.

No argument.

Start recording the vertices of a polygon. Current turtle position is first point of polygon.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Set the turtle's pen and fill color.
t.color("black", "red")

# Begin filling.
t.begin_fill()

# Begin creating a polygon.
t.begin_poly()
for i in range(4):
    t.forward(50)
    t.left(90)

# Stop creating a polygon.
t.end_poly()

# Stop filling.
t.end_fill()
def end_poly(self):
1796    def end_poly(self):
1797        """Stop recording the vertices of a polygon.
1798
1799        No argument.
1800
1801        Stop recording the vertices of a polygon. Current turtle position is
1802        last point of polygon. This will be connected with the first point.
1803
1804        **Example**
1805        ```python
1806        from ipycc.turtle import Turtle, showscreen
1807
1808        # Show the screen.
1809        showscreen()
1810
1811        # Create a turtle.
1812        t = Turtle()
1813
1814        # Set the turtle's pen and fill color.
1815        t.color("black", "red")
1816    
1817        # Begin filling.
1818        t.begin_fill()
1819    
1820        # Begin creating a polygon.
1821        t.begin_poly()
1822        for i in range(4):
1823            t.forward(50)
1824            t.left(90)
1825
1826        # Stop creating a polygon.
1827        t.end_poly()
1828
1829        # Stop filling.
1830        t.end_fill()
1831        ```
1832        """
1833        self._creatingPoly = False

Stop recording the vertices of a polygon.

No argument.

Stop recording the vertices of a polygon. Current turtle position is last point of polygon. This will be connected with the first point.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Set the turtle's pen and fill color.
t.color("black", "red")

# Begin filling.
t.begin_fill()

# Begin creating a polygon.
t.begin_poly()
for i in range(4):
    t.forward(50)
    t.left(90)

# Stop creating a polygon.
t.end_poly()

# Stop filling.
t.end_fill()
def circle( self, radius: int | float, extent: int | float = None, steps: int = None):
1835    def circle(
1836        self, radius: int | float, extent: int | float = None, steps: int = None
1837    ):
1838        """Draw a circle with given radius.
1839
1840        Arguments:
1841        - `radius` -- a number
1842        - `extent` (optional) -- a number
1843        - `steps` (optional) -- an integer
1844
1845        Draw a circle with given radius. The center is `radius` units left
1846        of the turtle; `extent` - an angle - determines which part of the
1847        circle is drawn. If `extent` is not given, draw the entire circle.
1848        If `extent` is not a full circle, one endpoint of the arc is the
1849        current pen position. Draw the arc in counterclockwise direction
1850        if `radius` is positive, otherwise in clockwise direction. Finally
1851        the direction of the turtle is changed by the amount of extent.
1852
1853        As the circle is approximated by an inscribed regular polygon,
1854        `steps` determines the number of steps to use. If not given,
1855        it will be calculated automatically. May be used to draw regular
1856        polygons.
1857
1858        **Example**
1859        ```python
1860        from ipycc.turtle import Turtle, showscreen
1861
1862        # Show the screen.
1863        showscreen()
1864
1865        # Create a turtle.
1866        t = Turtle()
1867
1868        t.circle(50)
1869        t.circle(120, 180)  # semicircle
1870        ```
1871        """
1872        speed = self.speed()
1873        if extent is None:
1874            extent = self._fullcircle
1875        if steps is None:
1876            frac = abs(extent) / self._fullcircle
1877            steps = 1+int(min(11+abs(radius)/6.0, 59.0)*frac)
1878        w = 1.0 * extent / steps
1879        w2 = 0.5 * w
1880        l = 2.0 * radius * math.sin(math.radians(w2)*self._degreesPerAU)
1881        if radius < 0:
1882            l, w, w2 = -l, -w, -w2
1883        tr = tracer()
1884        dl = delay()
1885        if speed == 0:
1886            tracer(0, 0)
1887        else:
1888            self.speed(0)
1889        self._rotate(w2)
1890        for i in range(steps):
1891            self.speed(speed)
1892            self._go(l)
1893            self.speed(0)
1894            self._rotate(w)
1895        self._rotate(-w2)
1896        if speed == 0:
1897            tracer(tr, dl)
1898        self.speed(speed)

Draw a circle with given radius.

Arguments:

  • radius -- a number
  • extent (optional) -- a number
  • steps (optional) -- an integer

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.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

t.circle(50)
t.circle(120, 180)  # semicircle
def reset(self):
1900    def reset(self):
1901        """Return the turtle to its initial state and clear its drawings from
1902        the screen.
1903
1904        No arguments.
1905
1906        **Example**
1907        ```python
1908        from ipycc.turtle import Turtle, showscreen
1909
1910        # Show the screen.
1911        showscreen()
1912
1913        # Create a turtle.
1914        t = Turtle()
1915
1916        # Move the turtle forward.
1917        t.forward(50)
1918
1919        # Reset the turtle.
1920        t.reset()
1921        ```
1922        """
1923        self._drawing = True
1924        self._pencolor = "black"
1925        self._pensize = 1
1926        self._pen.stroke(self._pencolor)
1927        self._pen.stroke_weight(self._pensize)
1928        self._speed = 3
1929        self._shown = True
1930        self._fillcolor = "black"
1931        self._is_filling = False
1932        self._poly = []
1933        self._fillpath = None
1934        self._pen.no_fill()
1935        self._creatingPoly = False
1936        self._position = Vec2D(0, 0)
1937        self._shape = "classic"
1938        self._stretchfactor = (1.0, 1.0)
1939        self._shearfactor = 0.0
1940        self._tilt = 0.0
1941        self._outlinewidth = 1
1942        self._orient = Vec2D(1, 0)
1943        self._angleOrient = 1.0
1944        self.degrees()
1945        self.clear()
1946        self.home()

Return the turtle to its initial state and clear its drawings from the screen.

No arguments.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Move the turtle forward.
t.forward(50)

# Reset the turtle.
t.reset()
def clear(self):
1948    def clear(self):
1949        """Delete the turtle's drawings from the screen. Do not move turtle.
1950
1951        No arguments.
1952
1953        Delete the turtle's drawings from the screen. Do not move turtle.
1954        State and position of the turtle as well as drawings of other
1955        turtles are not affected.
1956
1957        **Example**
1958        ```python
1959        from ipycc.turtle import Turtle, showscreen
1960
1961        # Show the screen.
1962        showscreen()
1963
1964        # Create a turtle.
1965        t = Turtle()
1966
1967        # Move the turtle forward.
1968        t.forward(50)
1969
1970        # Clear the turtle's drawings.
1971        t.clear()
1972        ```
1973        """
1974        self._pen.clear()
1975        self._update()

Delete the turtle's drawings from the screen. Do not move turtle.

No arguments.

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.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Move the turtle forward.
t.forward(50)

# Clear the turtle's drawings.
t.clear()
def write(self, arg, align: str = 'left', font: tuple = ('Arial', 8, 'normal')):
1994    def write(self, arg, align: str = "left", font: tuple = ("Arial", 8, "normal")):
1995        """Write text at the current turtle position.
1996
1997        Arguments:
1998        - `arg` -- info, which is to be written to the screen
1999        - `align` (optional) -- one of the strings `"left"`, `"center"` or
2000        `"right"`
2001        - `font` (optional) -- a triple (fontname, fontsize, fonttype)
2002
2003        Write text - the string representation of `arg` - at the current
2004        turtle position according to align (`"left"`, `"center"` or `"right"`)
2005        and with the given font.
2006
2007        **Example**
2008        ```python
2009        from ipycc.turtle import Turtle, showscreen
2010
2011        # Show the screen.
2012        showscreen()
2013
2014        # Create a turtle.
2015        t = Turtle()
2016
2017        # Write messages to the screen.
2018        t.write('Home = ', align="center")
2019        t.write((0, 0))
2020        ```
2021        """
2022        fontname, fontsize, fonttype = font
2023        if not align.lower() in (Sketch.LEFT, Sketch.CENTER, Sketch.RIGHT):
2024            raise TurtleGraphicsError('Invalid text alignment. Must be "left", "center", or "right".')
2025        if not isinstance(fontsize, (int, float)):
2026            raise TurtleGraphicsError('Font size must be a number.')
2027        if not fonttype in (Sketch.NORMAL, Sketch.ITALIC, Sketch.BOLD, Sketch.BOLDITALIC):
2028            raise TurtleGraphicsError('Invalid font type. Must be "normal", "italic", "bold", or "bolditalic".')
2029        self._write(str(arg), align.lower(), fontname, fontsize, fonttype)

Write text at the current turtle position.

Arguments:

  • arg -- info, which is to be written to the screen
  • align (optional) -- one of the strings "left", "center" or "right"
  • font (optional) -- a triple (fontname, fontsize, fonttype)

Write text - the string representation of arg - at the current turtle position according to align ("left", "center" or "right") and with the given font.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Write messages to the screen.
t.write('Home = ', align="center")
t.write((0, 0))
def showturtle(self):
2035    def showturtle(self):
2036        """Make the turtle visible.
2037
2038        Aliases:  `showturtle` | `st`
2039
2040        **Example**
2041        ```python
2042        from ipycc.turtle import Turtle, showscreen
2043
2044        # Show the screen.
2045        showscreen()
2046
2047        # Create a turtle.
2048        t = Turtle()
2049
2050        # Hide the turtle.
2051        t.hideturtle()
2052
2053        # Show the turtle.
2054        t.showturtle()
2055        ```
2056        """
2057        self._shown = True
2058        self._update()

Make the turtle visible.

Aliases: showturtle | st

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Hide the turtle.
t.hideturtle()

# Show the turtle.
t.showturtle()
def st(self):
2035    def showturtle(self):
2036        """Make the turtle visible.
2037
2038        Aliases:  `showturtle` | `st`
2039
2040        **Example**
2041        ```python
2042        from ipycc.turtle import Turtle, showscreen
2043
2044        # Show the screen.
2045        showscreen()
2046
2047        # Create a turtle.
2048        t = Turtle()
2049
2050        # Hide the turtle.
2051        t.hideturtle()
2052
2053        # Show the turtle.
2054        t.showturtle()
2055        ```
2056        """
2057        self._shown = True
2058        self._update()

Make the turtle visible.

Aliases: showturtle | st

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Hide the turtle.
t.hideturtle()

# Show the turtle.
t.showturtle()
def hideturtle(self):
2062    def hideturtle(self):
2063        """Make the turtle invisible.
2064
2065        Aliases:  `hideturtle` | `ht`
2066
2067        **Example**
2068        ```python
2069        from ipycc.turtle import Turtle, showscreen
2070
2071        # Show the screen.
2072        showscreen()
2073
2074        # Create a turtle.
2075        t = Turtle()
2076
2077        # Hide the turtle.
2078        t.hideturtle()
2079
2080        # Show the turtle.
2081        t.showturtle()
2082        ```
2083        """
2084        self._shown = False
2085        self._update()

Make the turtle invisible.

Aliases: hideturtle | ht

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Hide the turtle.
t.hideturtle()

# Show the turtle.
t.showturtle()
def ht(self):
2062    def hideturtle(self):
2063        """Make the turtle invisible.
2064
2065        Aliases:  `hideturtle` | `ht`
2066
2067        **Example**
2068        ```python
2069        from ipycc.turtle import Turtle, showscreen
2070
2071        # Show the screen.
2072        showscreen()
2073
2074        # Create a turtle.
2075        t = Turtle()
2076
2077        # Hide the turtle.
2078        t.hideturtle()
2079
2080        # Show the turtle.
2081        t.showturtle()
2082        ```
2083        """
2084        self._shown = False
2085        self._update()

Make the turtle invisible.

Aliases: hideturtle | ht

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Hide the turtle.
t.hideturtle()

# Show the turtle.
t.showturtle()
def isvisible(self) -> bool:
2089    def isvisible(self) -> bool:
2090        """Return `True` if the turtle is shown, `False` if it's hidden.
2091
2092        **Example**
2093        ```python
2094        from ipycc.turtle import Turtle, showscreen
2095
2096        # Show the screen.
2097        showscreen()
2098
2099        # Create a turtle.
2100        t = Turtle()
2101
2102        # Hide the turtle and print whether it is visible.
2103        t.hideturtle()
2104        print(t.isvisible()) # False
2105        # Show the turtle and print whether it is visible.
2106        t.showturtle()
2107        print(t.isvisible()) # True
2108        ```
2109        """
2110        return self._shown

Return True if the turtle is shown, False if it's hidden.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Hide the turtle and print whether it is visible.
t.hideturtle()
print(t.isvisible()) # False
# Show the turtle and print whether it is visible.
t.showturtle()
print(t.isvisible()) # True
def shape(self, name: str = None) -> None | str:
2112    def shape(self, name: str = None) -> None | str:
2113        """Set turtle shape to shape with given name / return current shapename.
2114
2115        Optional argument:
2116        `name` -- a string, which is a valid shapename
2117
2118        Set turtle shape to shape with given `name` or, if `name` is not given,
2119        return name of current shape.
2120        Valid shapenames are:
2121        - `"arrow"`
2122        - `"turtle"`
2123        - `"circle"`
2124        - `"square"`
2125        - `"triangle"`
2126        - `"classic"`
2127
2128        ```python
2129        from ipycc.turtle import Turtle, showscreen
2130
2131        # Show the screen.
2132        showscreen()
2133
2134        # Create a turtle.
2135        t = Turtle()
2136
2137        # Print the turtle's default shape.
2138        print(t.shape()) # 'arrow'
2139
2140        # Change the turtle's shape and print it.
2141        t.shape("turtle")
2142        print(t.shape()) # 'turtle'
2143        ```
2144        """
2145        if name is None:
2146            return self._shape
2147        if not name in _turtle_shapes:
2148            raise NameError("There is no shape named %s" % name)
2149        self._shape = name
2150        self._update()

Set turtle shape to shape with given name / return current shapename.

Optional argument: name -- a string, which is a valid shapename

Set turtle shape to shape with given name or, if name is not given, return name of current shape. Valid shapenames are:

  • "arrow"
  • "turtle"
  • "circle"
  • "square"
  • "triangle"
  • "classic"
from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's default shape.
print(t.shape()) # 'arrow'

# Change the turtle's shape and print it.
t.shape("turtle")
print(t.shape()) # 'turtle'
def shapesize( self, stretch_wid: int | float = None, stretch_len: int | float = None) -> float:
2152    def shapesize(
2153        self, stretch_wid: int | float = None, stretch_len: int | float = None
2154    ) -> float:
2155        """Set/return turtle's stretchfactors/outline. Set resizemode to "user".
2156
2157        Optional arguments:
2158        - `stretch_wid` : positive number
2159        - `stretch_len` : positive number
2160        - `outline`  : positive number
2161
2162        Return or set the pen's attributes x/y-stretchfactors and/or outline.
2163        The turtle will be displayed stretched according to its stretchfactors:
2164        - `stretch_wid` is stretchfactor perpendicular to orientation.
2165        - `stretch_len` is stretchfactor in direction of the turtle's orientation.
2166        - `outline` determines the width of the shapes's outline.
2167
2168        ```python
2169        from ipycc.turtle import Turtle, showscreen
2170
2171        # Show the screen.
2172        showscreen()
2173
2174        # Create a turtle.
2175        t = Turtle()
2176
2177        # Change the turtle's shape size.
2178        t.shapesize(5, 5, 12)
2179        t.shapesize(outline=8)
2180        ```
2181        """
2182        if stretch_wid is stretch_len is None:
2183            return self._stretchfactor
2184        if stretch_wid == 0 or stretch_len == 0:
2185            raise TurtleGraphicsError("stretch_wid/stretch_len must not be zero")
2186        if stretch_wid is not None:
2187            if stretch_len is None:
2188                self._stretchfactor = stretch_wid, stretch_wid
2189            else:
2190                self._stretchfactor = stretch_wid, stretch_len
2191        elif stretch_len is not None:
2192            self._stretchfactor = self._stretchfactor[0], stretch_len
2193        else:
2194            self._stretchfactor = self._stretchfactor
2195        self._update()

Set/return turtle's stretchfactors/outline. Set resizemode to "user".

Optional arguments:

  • stretch_wid : positive number
  • stretch_len : positive number
  • outline : positive number

Return or set the pen's attributes x/y-stretchfactors and/or outline. The turtle will be displayed stretched according to its stretchfactors:

  • stretch_wid is stretchfactor perpendicular to orientation.
  • stretch_len is stretchfactor in direction of the turtle's orientation.
  • outline determines the width of the shapes's outline.
from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Change the turtle's shape size.
t.shapesize(5, 5, 12)
t.shapesize(outline=8)
def shearfactor(self, shear: int | float = None) -> None | float:
2197    def shearfactor(self, shear: int | float = None) -> None | float:
2198        """Set or return the current shearfactor.
2199
2200        Optional argument: `shear` -- number, tangent of the shear angle
2201
2202        Shear the turtleshape according to the given shearfactor `shear`,
2203        which is the tangent of the shear angle. Doesn't change the
2204        turtle's heading (direction of movement).
2205        If `shear` is not given: return the current shearfactor, i. e. the
2206        tangent of the shear angle, by which lines parallel to the
2207        heading of the turtle are sheared.
2208
2209        ```python
2210        from ipycc.turtle import Turtle, showscreen
2211
2212        # Show the screen.
2213        showscreen()
2214
2215        # Create a turtle.
2216        t = Turtle()
2217
2218        # Set the turtle's shape and size.
2219        t.shape("circle")
2220        t.shapesize(5, 2)
2221
2222        # Set the turtle's shear factor and print it.
2223        t.shearfactor(0.5)
2224        print(t.shearfactor()) # 0.5
2225        ```
2226        """
2227        if shear is None:
2228            return self._shearfactor
2229        self._shearfactor = shear

Set or return the current shearfactor.

Optional argument: shear -- number, tangent of the shear angle

Shear the turtleshape according to the given shearfactor shear, which is the tangent of the shear angle. Doesn't 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.

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Set the turtle's shape and size.
t.shape("circle")
t.shapesize(5, 2)

# Set the turtle's shear factor and print it.
t.shearfactor(0.5)
print(t.shearfactor()) # 0.5
def tiltangle(self, angle: int | float = None) -> None | float:
2231    def tiltangle(self, angle: int | float = None) -> None | float:
2232        """Set or return the current tilt-angle.
2233
2234        Optional argument: `angle` -- number
2235
2236        Rotate the turtleshape to point in the direction specified by `angle`,
2237        regardless of its current tilt-angle. Doesn't change the turtle's
2238        heading (direction of movement).
2239        If `angle` is not given: return the current tilt-angle, i. e. the angle
2240        between the orientation of the turtleshape and the heading of the
2241        turtle (its direction of movement).
2242
2243        **Example**
2244        ```python
2245        from ipycc.turtle import Turtle, showscreen
2246
2247        # Show the screen.
2248        showscreen()
2249
2250        # Create a turtle.
2251        t = Turtle()
2252
2253        # Set the turtle's shape and size.
2254        t.shape("circle")
2255        t.shapesize(5, 2)
2256
2257        # Print the turtle's tilt angle.
2258        print(t.tiltangle()) # 0.0
2259
2260        # Tilt the turtle and print the angle.
2261        t.tiltangle(45)
2262        print(t.tiltangle()) # 45.0
2263
2264        # Stamp the turtle's shape.
2265        t.stamp()
2266        
2267        # Move the turtle forward.
2268        t.forward(50)
2269    
2270        #  Tilt the turtle back to its original angle and print it.
2271        t.tiltangle(-45)
2272        print(t.tiltangle()) # 315.0
2273    
2274        # Stamp the turtle's shape and move forward.
2275        t.stamp()
2276        t.forward(50)
2277        ```
2278        """
2279        if angle is None:
2280            tilt = -math.degrees(self._tilt) * self._angleOrient
2281            return (tilt / self._degreesPerAU) % self._fullcircle
2282        else:
2283            tilt = -angle * self._degreesPerAU * self._angleOrient
2284            tilt = math.radians(tilt) % math.tau
2285            self._tilt = tilt

Set or return the current tilt-angle.

Optional argument: angle -- number

Rotate the turtleshape to point in the direction specified by angle, regardless of its current tilt-angle. Doesn't 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).

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Set the turtle's shape and size.
t.shape("circle")
t.shapesize(5, 2)

# Print the turtle's tilt angle.
print(t.tiltangle()) # 0.0

# Tilt the turtle and print the angle.
t.tiltangle(45)
print(t.tiltangle()) # 45.0

# Stamp the turtle's shape.
t.stamp()

# Move the turtle forward.
t.forward(50)

#  Tilt the turtle back to its original angle and print it.
t.tiltangle(-45)
print(t.tiltangle()) # 315.0

# Stamp the turtle's shape and move forward.
t.stamp()
t.forward(50)
def tilt(self, angle: int | float):
2287    def tilt(self, angle: int | float):
2288        """Rotate the turtleshape by angle.
2289
2290        Argument:
2291        `angle` -- a number
2292
2293        Rotate the turtleshape by `angle` from its current tilt-angle,
2294        but don't change the turtle's heading (direction of movement).
2295
2296        **Example**
2297        ```python
2298        from ipycc.turtle import Turtle, showscreen
2299
2300        # Show the screen.
2301        showscreen()
2302
2303        # Create a turtle.
2304        t = Turtle()
2305
2306        # Set the turtle's shape and size.
2307        t.shape("circle")
2308        t.shapesize(5, 2)
2309    
2310        # Tilt the turtle and move forward.
2311        t.tilt(30)
2312        t.forward(50)
2313
2314        # Tilt the turtle again and move forward.
2315        t.tilt(30)
2316        t.forward(50)
2317        ```
2318        """
2319        self.tiltangle(angle + self.tiltangle())

Rotate the turtleshape by angle.

Argument: angle -- a number

Rotate the turtleshape by angle from its current tilt-angle, but don't change the turtle's heading (direction of movement).

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Set the turtle's shape and size.
t.shape("circle")
t.shapesize(5, 2)

# Tilt the turtle and move forward.
t.tilt(30)
t.forward(50)

# Tilt the turtle again and move forward.
t.tilt(30)
t.forward(50)
class Vec2D(builtins.tuple):
10class Vec2D(tuple):
11    """A 2 dimensional vector class, used as a helper class
12    for implementing turtle graphics.
13    May be useful for turtle graphics programs also.
14    Derived from tuple, so a vector is a tuple!
15
16    Provides (for `a`, `b` vectors, `k` number):
17    -  `a+b` vector addition
18    - `a-b` vector subtraction
19    - `a*b` inner product
20    - `k*a` and `a*k` multiplication with scalar
21    - `|a|` absolute value of `a`
22    - `a.rotate(angle)` rotation
23    """
24
25    def __new__(cls, x, y):
26        return tuple.__new__(cls, (x, y))
27
28    def __add__(self, other):
29        return Vec2D(self[0] + other[0], self[1] + other[1])
30
31    def __mul__(self, other):
32        if isinstance(other, Vec2D):
33            return self[0] * other[0] + self[1] * other[1]
34        return Vec2D(self[0] * other, self[1] * other)
35
36    def __rmul__(self, other):
37        if isinstance(other, int) or isinstance(other, float):
38            return Vec2D(self[0] * other, self[1] * other)
39        return NotImplemented
40
41    def __sub__(self, other):
42        return Vec2D(self[0] - other[0], self[1] - other[1])
43
44    def __neg__(self):
45        return Vec2D(-self[0], -self[1])
46
47    def __abs__(self):
48        return math.hypot(*self)
49
50    def rotate(self, angle: int | float):
51        """Returns a vector with the same magnitude that is rotated
52        counterclockwise by a given angle.
53
54        Argument: `angle` -- a number
55
56        **Example**
57        ```python
58        from ipycc.turtle import Vec2D
59
60        v1 = Vec2D(1, 0)
61        v2 = v1.rotate(90)
62        print(v1) # (1.00,0.00)
63        print(v2) # (0.00,1.00)
64        ```
65        """
66        perp = Vec2D(-self[1], self[0])
67        angle = math.radians(angle)
68        c, s = math.cos(angle), math.sin(angle)
69        return Vec2D(self[0] * c + perp[0] * s, self[1] * c + perp[1] * s)
70
71    def __getnewargs__(self):
72        return (self[0], self[1])
73
74    def __repr__(self):
75        return "(%.2f,%.2f)" % self

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 rotate(self, angle: int | float):
50    def rotate(self, angle: int | float):
51        """Returns a vector with the same magnitude that is rotated
52        counterclockwise by a given angle.
53
54        Argument: `angle` -- a number
55
56        **Example**
57        ```python
58        from ipycc.turtle import Vec2D
59
60        v1 = Vec2D(1, 0)
61        v2 = v1.rotate(90)
62        print(v1) # (1.00,0.00)
63        print(v2) # (0.00,1.00)
64        ```
65        """
66        perp = Vec2D(-self[1], self[0])
67        angle = math.radians(angle)
68        c, s = math.cos(angle), math.sin(angle)
69        return Vec2D(self[0] * c + perp[0] * s, self[1] * c + perp[1] * s)

Returns a vector with the same magnitude that is rotated counterclockwise by a given angle.

Argument: angle -- a number

Example

from ipycc.turtle import Vec2D

v1 = Vec2D(1, 0)
v2 = v1.rotate(90)
print(v1) # (1.00,0.00)
print(v2) # (0.00,1.00)
def setup(width: int | float, height: int | float):
250def setup(width: int | float, height: int | float):
251    """Sets the size of the screen.
252
253    Arguments:
254    - `width` -- a number
255    - `height` -- a number
256
257    The first two arguments, `width` and `height`, set the width of the
258    drawing screen in pixels.
259
260    Calling `setup()` will resize the screen and all turtles will be reset.
261
262    **Example**
263    ```python
264    from ipycc.turtle import Turtle, showscreen, setup
265
266    # Show the screen.
267    showscreen()
268
269    # Set the screen to half size.
270    setup(200, 200)
271
272    # Create a turtle.
273    t = Turtle()
274    ```
275    """
276    global _SCREEN
277    new_screen = _Screen(width, height)
278    new_screen._turtles = _SCREEN._turtles
279    for t in new_screen._turtles:
280        t._pen = Sketch(width, height)
281        t.reset()
282    _SCREEN = new_screen

Sets the size of the screen.

Arguments:

  • width -- a number
  • height -- a number

The first two arguments, width and height, set the width of the drawing screen in pixels.

Calling setup() will resize the screen and all turtles will be reset.

Example

from ipycc.turtle import Turtle, showscreen, setup

# Show the screen.
showscreen()

# Set the screen to half size.
setup(200, 200)

# Create a turtle.
t = Turtle()
def showscreen():
285def showscreen():
286    """Shows the screen to which turtles are drawing.
287
288    Calling `showscreen()` displays the drawing screen beneath the
289    code cell in which it's called.
290
291    **Example**
292    ```python
293    from ipycc.turtle import Turtle, showscreen
294
295    # Show the screen.
296    showscreen()
297
298    # Create a turtle and move it.
299    t = Turtle()
300    t.forward(100)
301
302    # Create a turtle and move it.
303    t2 = Turtle()
304    for i in range(4):
305        t2.forward(50)
306        t2.left(90)
307    ```
308    """
309    global _SCREEN
310    # Copy the screen and reassign its turtles.
311    new_screen = _SCREEN.replace()
312    _SCREEN = new_screen
313    # Show the screen.
314    _SCREEN.show()

Shows the screen to which turtles are drawing.

Calling showscreen() displays the drawing screen beneath the code cell in which it's called.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle and move it.
t = Turtle()
t.forward(100)

# Create a turtle and move it.
t2 = Turtle()
for i in range(4):
    t2.forward(50)
    t2.left(90)
def tracer(n: int = None, delay: int = None) -> int:
317def tracer(n: int = None, delay: int = None) -> int:
318    """Turns turtle animation on/off and set delay for updating drawings.
319
320    Optional arguments:
321    - `n` -- a nonnegative integer
322    - `delay` -- a nonnegative integer
323    
324    If no argument is passed, the current rate of screen updates is returned. The
325    default value is 1.
326
327    If `n` is given, only each n-th regular screen update is really performed.
328    This feature can be used to accelerate the drawing of complex graphics.
329
330    If `delay` is given, it sets the screen's delay value.
331    
332    **Example**
333    ```python
334    from ipycc.turtle import Turtle, showscreen, tracer
335
336    # Show the screen.
337    showscreen()
338
339    # Create a turtle.
340    t = Turtle()
341
342    # Draw every 8th frame with a delay of 25 ms.
343    tracer(8, 25)
344    dist = 2
345    for i in range(200):
346        fd(dist)
347        rt(90)
348        dist += 2
349    ```
350    """
351    if n is None:
352        return _SCREEN._tracing
353    _SCREEN._tracing = int(n)
354    _SCREEN._updatecounter = 0
355    if delay is not None:
356        _SCREEN._delayvalue = int(delay)
357    if _SCREEN._tracing:
358        _SCREEN._update()

Turns turtle animation on/off and set delay for updating drawings.

Optional arguments:

  • n -- a nonnegative integer
  • delay -- a nonnegative integer

If no argument is passed, the current rate of screen updates is returned. The default value is 1.

If n is given, only each n-th regular screen update is really performed. This feature can be used to accelerate the drawing of complex graphics.

If delay is given, it sets the screen's delay value.

Example

from ipycc.turtle import Turtle, showscreen, tracer

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Draw every 8th frame with a delay of 25 ms.
tracer(8, 25)
dist = 2
for i in range(200):
    fd(dist)
    rt(90)
    dist += 2
def delay(delay: int = None) -> int:
361def delay(delay: int = None) -> int:
362    """ Return or set the drawing delay in milliseconds.
363
364    Optional argument:
365    `delay` -- positive integer
366
367    **Example**
368    ```python
369    from ipycc.turtle import delay
370
371    delay(15)
372    print(delay()) # 15
373    ```
374    """
375    if delay is None:
376        return _SCREEN._delayvalue
377    _SCREEN._delayvalue = int(delay)

Return or set the drawing delay in milliseconds.

Optional argument: delay -- positive integer

Example

from ipycc.turtle import delay

delay(15)
print(delay()) # 15
@contextmanager
def no_animation():
380@contextmanager
381def no_animation():
382    """Temporarily turn off auto-updating the screen.
383
384    This is useful for drawing complex shapes where even the fastest setting
385    is too slow. Once this context manager is exited, the drawing will
386    be displayed.
387
388    **Example**
389    ```python
390    from ipycc.turtle import Turtle, showscreen, no_animation
391
392    # Show the screen.
393    showscreen()
394
395    # Create a turtle.
396    t = Turtle()
397
398    # Draw a circle without animation.
399    with no_animation():
400        for i in range(360):
401            t.forward(1)
402            t.left(1)
403    ```
404    """
405    t = tracer()
406    try:
407        tracer(0)
408        yield
409    finally:
410        tracer(t)

Temporarily turn off auto-updating the screen.

This is useful for drawing complex shapes where even the fastest setting is too slow. Once this context manager is exited, the drawing will be displayed.

Example

from ipycc.turtle import Turtle, showscreen, no_animation

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Draw a circle without animation.
with no_animation():
    for i in range(360):
        t.forward(1)
        t.left(1)
def clearscreen():
413def clearscreen():
414    """Delete all drawings and all turtles from the screen.
415    
416    Resets the now empty screen to its initial state with a white background.
417
418    **Example**
419    ```python
420    from ipycc.turtle import Turtle, showscreen, clearscreen
421
422    # Show the screen.
423    showscreen()
424
425    # Create a turtle.
426    t = Turtle()
427
428    # Move the turtle forward.
429    t.forward(100)
430    
431    # Clear the screen.
432    clearscreen()
433    ```
434    """
435    for t in _SCREEN._turtles:
436        t.clear()
437        t.hideturtle()
438    _SCREEN._turtles = []
439    _SCREEN._sketch.background("white")

Delete all drawings and all turtles from the screen.

Resets the now empty screen to its initial state with a white background.

Example

from ipycc.turtle import Turtle, showscreen, clearscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Move the turtle forward.
t.forward(100)

# Clear the screen.
clearscreen()
def resetscreen():
442def resetscreen():
443    """Reset all turtles on the screen to their initial state.
444
445    Calling `resetscreen()` resets all turtles on the screen.
446
447    **Example**
448    ```python
449    from ipycc.turtle import Turtle, showscreen, resetscreen
450
451    # Show the screen.
452    showscreen()
453
454    # Create a turtle.
455    t = Turtle()
456
457    # Move the turtle forward.
458    t.forward(100)
459    
460    # Reset the screen.
461    resetscreen()
462    ```
463    """
464    for t in _SCREEN._turtles:
465        t.reset()

Reset all turtles on the screen to their initial state.

Calling resetscreen() resets all turtles on the screen.

Example

from ipycc.turtle import Turtle, showscreen, resetscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Move the turtle forward.
t.forward(100)

# Reset the screen.
resetscreen()
def colormode(cmode: int | float = None) -> None | int | float:
468def colormode(cmode: int | float = None) -> None | int | float:
469    """Return the colormode or set it to 1.0 or 255.
470
471    Optional argument:
472    `cmode` -- one of the values 1.0 or 255
473
474    r, g, b values of colortriples have to be in range `0..cmode`.
475
476    **Example**
477    ```python
478    from ipycc.turtle import Turtle, showscreen
479
480    # Show the screen.
481    showscreen()
482
483    # Create a turtle.
484    t = Turtle()
485
486    # Print the turtle's default color mode.
487    print(t.colormode()) # 1.0
488    # Change the turtle's color mode and change its color.
489    t.colormode(255)
490    t.color(240, 160, 80)
491    ```
492    """
493    if cmode is None:
494        return _SCREEN._colormode
495    if cmode == 1.0:
496        _SCREEN._colormode = float(cmode)
497    elif cmode == 255:
498        _SCREEN._colormode = int(cmode)

Return the colormode or set it to 1.0 or 255.

Optional argument: cmode -- one of the values 1.0 or 255

r, g, b values of colortriples have to be in range 0..cmode.

Example

from ipycc.turtle import Turtle, showscreen

# Show the screen.
showscreen()

# Create a turtle.
t = Turtle()

# Print the turtle's default color mode.
print(t.colormode()) # 1.0
# Change the turtle's color mode and change its color.
t.colormode(255)
t.color(240, 160, 80)
def bgcolor(*args) -> None | str:
501def bgcolor(*args) -> None | str:
502    """Set or return background color of the turtle's screen.
503
504    Arguments:
505    Four input formats are allowed:
506        - `bgcolor()`
507        Return the current background as color specification string,
508        possibly in hex-number format (see example).
509        May be used as input to another color/pencolor/fillcolor call.
510        - `bgcolor(colorstring)`
511        a [Tk color specification string](https://www.tcl-lang.org/man/tcl8.4/TkCmd/colors.htm),
512        such as `"red"` or `"yellow"`
513        - `bgcolor((r, g, b))`
514        *a tuple* of `r`, `g`, and `b`, which represent, an RGB color,
515        and each of `r`, `g`, and `b` are in the range `0..colormode`,
516        where `colormode` is either 1.0 or 255
517        - `bgcolor(r, g, b)`
518        `r`, `g`, and `b` represent an RGB color, and each of `r`, `g`,
519        and `b` are in the range `0..colormode`
520
521    **Example**
522    ```python
523    from ipycc.turtle import showscreen, bgcolor
524
525    # Show the screen.
526    showscreen()
527
528    # Set the screen's background color and print it.
529    bgcolor("orange")
530    print(bgcolor()) # 'orange'
531    ```
532    """
533    if args:
534        _SCREEN._bgcolor = _SCREEN._colorstr(args)
535        _SCREEN._update()
536    else:
537        return _SCREEN._bgcolor

Set or return background color of the turtle's screen.

Arguments: Four input formats are allowed: - bgcolor() Return the current background as color specification string, possibly in hex-number format (see example). May be used as input to another color/pencolor/fillcolor call. - bgcolor(colorstring) a Tk color specification string, such as "red" or "yellow" - bgcolor((r, g, b)) a tuple of r, g, and b, which represent, an RGB color, and each of r, g, and b are in the range 0..colormode, where colormode is either 1.0 or 255 - bgcolor(r, g, b) r, g, and b represent an RGB color, and each of r, g, and b are in the range 0..colormode

Example

from ipycc.turtle import showscreen, bgcolor

# Show the screen.
showscreen()

# Set the screen's background color and print it.
bgcolor("orange")
print(bgcolor()) # 'orange'