le* 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 (for a Turtle instance named turtle):
        >>> turtle.pencolor('brown')
        >>> tup = (0.2, 0.8, 0.55)
        >>> turtle.pencolor(tup)
        >>> turtle.pencolor()
        '#33cc8c'
        """
        if args:
            color = self._colorstr(args)
            if color == self._pencolor:
                return
            self.pen(pencolor=color)
        else:
            return self._color(self._pencolor)

    def fillcolor(self, *args):
        """ 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)
            s is 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 (for a Turtle instance named turtle):
        >>> turtle.fillcolor('violet')
        >>> col = turtle.pencolor()
        >>> turtle.fillcolor(col)
        >>> turtle.fillcolor(0, .5, 0)
        """
        if args:
            color = self._colorstr(args)
            if color == self._fillcolor:
                return
            self.pen(fillcolor=color)
        else:
            return self._color(self._fillcolor)

    def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None:
        """To be overwritten by child class RawTurtle.
        Includes no TNavigator references.
        """
        pendown = self.isdown()
        if pendown:
            self.pen(pendown=False)
        self.pen(pendown=pendown)

    def showturtle(self):
        """Makes the turtle visible.

        Aliases: showturtle | st

        No argument.

        Example (for a Turtle instance named turtle):
        >>> turtle.hideturtle()
        >>> turtle.showturtle()
        """
        self.pen(shown=True)

    def hideturtle(self):
        """Makes the turtle invisible.

        Aliases: hideturtle | ht

        No argument.

        It's a good idea to do this while you're in the
        middle of a complicated drawing, because hiding
        the turtle speeds up the drawing observably.

        Example (for a Turtle instance named turtle):
        >>> turtle.hideturtle()
        """
        self.pen(shown=False)

    def isvisible(self):
        """Return True if the Turtle is shown, False if it's hidden.

        No argument.

        Example (for a Turtle instance named turtle):
        >>> turtle.hideturtle()
        >>> print(turtle.isvisible())
        False
        """
        return self._shown

    def pen(self, pen=None, **pendict):
        """Return or set the pen's attributes.

        Arguments:
            pen -- a dictionary with some or all of the below listed keys.
            **pendict -- one or more keyword-arguments with the below
                         listed keys as keywords.

        Return or set the pen's attributes in a 'pen-dictionary'
        with the following key/value pairs:
           "shown"      :   True/False
           "pendown"    :   True/False
           "pencolor"   :   color-string or color-tuple
           "fillcolor"  :   color-string or color-tuple
           "pensize"    :   positive number
           "speed"      :   number in range 0..10
           "resizemode" :   "auto" or "user" or "noresize"
           "stretchfactor": (positive number, positive number)
           "shearfactor":   number
           "outline"    :   positive number
           "tilt"       :   number

        This dictionary can be used as argument for a subsequent
        pen()-call to restore the former pen-state. Moreover one
        or more of these attributes can be provided as keyword-arguments.
        This can be used to set several pen attributes in one statement.


        Examples (for a Turtle instance named turtle):
        >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
        >>> turtle.pen()
        {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
        'pencolor': 'red', 'pendown': True, 'fillcolor': 'black',
        'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
        >>> penstate=turtle.pen()
        >>> turtle.color("yellow","")
        >>> turtle.penup()
        >>> turtle.pen()
        {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
        'pencolor': 'yellow', 'pendown': False, 'fillcolor': '',
        'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
        >>> p.pen(penstate, fillcolor="green")
        >>> p.pen()
        {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
        'pencolor': 'red', 'pendown': True, 'fillcolor': 'green',
        'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
        """
        _pd =  {"shown"         : self._shown,
                "pendown"       : self._drawing,
                "pencolor"      : self._pencolor,
                "fillcolor"     : self._fillcolor,
                "pensize"       : self._pensize,
                "speed"         : self._speed,
                "resizemode"    : self._resizemode,
                "stretchfactor" : self._stretchfactor,
                "shearfactor"   : self._shearfactor,
                "outline"       : self._outlinewidth,
                "tilt"          : self._tilt
               }

        if not (pen or pendict):
            return _pd

        if isinstance(pen, dict):
            p = pen
        else:
            p = {}
        p.update(pendict)

        _p_buf = {}
        for key in p:
            _p_buf[key] = _pd[key]

        if self.undobuffer:
            self.undobuffer.push(("pen", _p_buf))

        newLine = False
        if "pendown" in p:
            if self._drawing != p["pendown"]:
                newLine = True
        if "pencolor" in p:
            if isinstance(p["pencolor"], tuple):
                p["pencolor"] = self._colorstr((p["pencolor"],))
            if self._pencolor != p["pencolor"]:
                newLine = True
        if "pensize" in p:
            if self._pensize != p["pensize"]:
                newLine = True
        if newLine:
            self._newLine()
        if "pendown" in p:
            self._drawing = p["pendown"]
        if "pencolor" in p:
            self._pencolor = p["pencolor"]
        if "pensize" in p:
            self._pensize = p["pensize"]
        if "fillcolor" in p:
            if isinstance(p["fillcolor"], tuple):
                p["fillcolor"] = self._colorstr((p["fillcolor"],))
            self._fillcolor = p["fillcolor"]
        if "speed" in p:
            self._speed = p["speed"]
        if "resizemode" in p:
            self._resizemode = p["resizemode"]
        if "stretchfactor" in p:
            sf = p["stretchfactor"]
            if isinstance(sf, (int, float)):
                sf = (sf, sf)
            self._stretchfactor = sf
        if "shearfactor" in p:
            self._shearfactor = p["shearfactor"]
        if "outline" in p:
            self._outlinewidth = p["outline"]
        if "shown" in p:
            self._shown = p["shown"]
        if "tilt" in p:
            self._tilt = p["tilt"]
        if "stretchfactor" in p or "tilt" in p or "shearfactor" in p:
            scx, scy = self._stretchfactor
            shf = self._shearfactor
            sa, ca = math.sin(self._tilt), math.cos(self._tilt)
            self._shapetrafo = ( scx*ca, scy*(shf*ca + sa),
                                -scx*sa, scy*(ca - shf*sa))
        self._update()

## three dummy methods to be implemented by child class:

    def _newLine(self, usePos = True):
        """dummy method - to be overwritten by child class"""
    def _update(self, count=True, forced=False):
        """dummy method - to be overwritten by child class"""
    def _color(self, args):
        """dummy method - to be overwritten by child class"""
    def _colorstr(self, args):
        """dummy method - to be overwritten by child class"""

    width = pensize
    up = penup
    pu = penup
    pd = pendown
    down = pendown
    st = showturtle
    ht = hideturtle


class _TurtleImage(object):
    """Helper class: Datatype to store Turtle attributes
    """

    def __init__(self, screen, shapeIndex):
        self.screen = screen
        self._type = None
        self._setshape(shapeIndex)

    def _setshape(self, shapeIndex):
        screen = self.screen
        self.shapeIndex = shapeIndex
        if self._type == "polygon" == screen._shapes[shapeIndex]._type:
            return
        if self._type == "image" == screen._shapes[shapeIndex]._type:
            return
        if self._type in ["image", "polygon"]:
            screen._delete(self._item)
        elif self._type == "compound":
            for item in self._item:
                screen._delete(item)
        self._type = screen._shapes[shapeIndex]._type
        if self._type == "polygon":
            self._item = screen._createpoly()
        elif self._type == "image":
            self._item = screen._createimage(screen._shapes["blank"]._data)
        elif self._type == "compound":
            self._item = [screen._createpoly() for item in
                                          screen._shapes[shapeIndex]._data]


class RawTurtle(TPen, TNavigator):
    """Animation part of the RawTurtle.
    Puts RawTurtle upon a TurtleScreen and provides tools for
    its animation.
    """
    screens = []

    def __init__(self, canvas=None,
                 shape=_CFG["shape"],
                 undobuffersize=_CFG["undobuffersize"],
                 visible=_CFG["visible"]):
        if isinstance(canvas, _Screen):
            self.screen = canvas
        elif isinstance(canvas, TurtleScreen):
            if canvas not in RawTurtle.screens:
                RawTurtle.screens.append(canvas)
            self.screen = canvas
        elif isinstance(canvas, (ScrolledCanvas, Canvas)):
            for screen in RawTurtle.screens:
                if screen.cv == canvas:
                    self.screen = screen
                    break
            else:
                self.screen = TurtleScreen(canvas)
                RawTurtle.screens.append(self.screen)
        else:
            raise TurtleGraphicsError("bad canvas argument %s" % canvas)

        screen = self.screen
        TNavigator.__init__(self, screen.mode())
        TPen.__init__(self)
        screen._turtles.append(self)
        self.drawingLineItem = screen._createline()
        self.turtle = _TurtleImage(screen, shape)
        self._poly = None
        self._creatingPoly = False
        self._fillitem = self._fillpath = None
        self._shown = visible
        self._hidden_from_screen = False
        self.currentLineItem = screen._createline()
        self.currentLine = [self._position]
        self.items = [self.currentLineItem]
        self.stampItems = []
        self._undobuffersize = undobuffersize
        self.undobuffer = Tbuffer(undobuffersize)
        self._update()

    def reset(self):
        """Delete the turtle's drawings and restore its default values.

        No argument.

        Delete the turtle's drawings from the screen, re-center the turtle
        and set variables to the default values.

        Example (for a Turtle instance named turtle):
        >>> turtle.position()
        (0.00,-22.00)
        >>> turtle.heading()
        100.0
        >>> turtle.reset()
        >>> turtle.position()
        (0.00,0.00)
        >>> turtle.heading()
        0.0
        """
        TNavigator.reset(self)
        TPen._reset(self)
        self._clear()
        self._drawturtle()
        self._update()

    def setundobuffer(self, size):
        """Set or disable undobuffer.

        Argument:
        size -- an integer or None

        If size is an integer an empty undobuffer of given size is installed.
        Size gives the maximum number of turtle-actions that can be undone
        by the undo() function.
        If size is None, no undobuffer is present.

        Example (for a Turtle instance named turtle):
        >>> turtle.setundobuffer(42)
        """
        if size is None or size <= 0:
            self.undobuffer = None
        else:
            self.undobuffer = Tbuffer(size)

    def undobufferentries(self):
        """Return count of entries in the undobuffer.

        No argument.

        Example (for a Turtle instance named turtle):
        >>> while undobufferentries():
        ...     undo()
        """
        if self.undobuffer is None:
            return 0
        return self.undobuffer.nr_of_items()

    def _clear(self):
        """Delete all of pen's drawings"""
        self._fillitem = self._fillpath = None
        for item in self.items:
            self.screen._delete(item)
        self.currentLineItem = self.screen._createline()
        self.currentLine = []
        if self._drawing:
            self.currentLine.append(self._position)
        self.items = [self.currentLineItem]
        self.clearstamps()
        self.setundobuffer(self._undobuffersize)


    def clear(self):
        """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.

        Examples (for a Turtle instance named turtle):
        >>> turtle.clear()
        """
        self._clear()
        self._update()

    def _update_data(self):
        self.screen._incrementudc()
        if self.screen._updatecounter != 0:
            return
        if len(self.currentLine)>1:
            self.screen._drawline(self.currentLineItem, self.currentLine,
                                  self._pencolor, self._pensize)

    def _update(self):
        """Perform a Turtle-data update.
        """
        screen = self.screen
        if screen._tracing == 0:
            return
        elif screen._tracing == 1:
            self._update_data()
            self._drawturtle()
            screen._update()                  # TurtleScreenBase
            screen._delay(screen._delayvalue) # TurtleScreenBase
        else:
            self._update_data()
            if screen._updatecounter == 0:
                for t in screen.turtles():
                    t._drawturtle()
                screen._update()

    def _tracer(self, flag=None, delay=None):
        """Turns turtle animation on/off and set delay for update drawings.

        Optional arguments:
        n -- nonnegative  integer
        delay -- nonnegative  integer

        If n is given, only each n-th regular screen update is really performed.
        (Can be used to accelerate the drawing of complex graphics.)
        Second arguments sets delay value (see RawTurtle.delay())

        Example (for a Turtle instance named turtle):
        >>> turtle.tracer(8, 25)
        >>> dist = 2
        >>> for i in range(200):
        ...     turtle.fd(dist)
        ...     turtle.rt(90)
        ...     dist += 2
        """
        return self.screen.tracer(flag, delay)

    def _color(self, args):
        return self.screen._color(args)

    def _colorstr(self, args):
        return self.screen._colorstr(args)

    def _cc(self, args):
        """Convert colortriples to hexstrings.
        """
        if isinstance(args, str):
            return args
        try:
            r, g, b = args
        except (TypeError, ValueError):
            raise TurtleGraphicsError("bad color arguments: %s" % str(args))
        if self.screen._colormode == 1.0:
            r, g, b = [round(255.0*x) for x in (r, g, b)]
        if not ((0 <= r <= 255) and (0 <= g <= 255) and (0 <= b <= 255)):
            raise TurtleGraphicsError("bad color sequence: %s" % str(args))
        return "#%02x%02x%02x" % (r, g, b)

    def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None:
        """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.

        call: teleport(x, y)         # two coordinates
        --or: teleport(x)            # teleport to x position, keeping y as is
        --or: teleport(y=y)          # teleport to y position, keeping x as is
        --or: teleport(x, y, fill_gap=True)
                                     # teleport but fill the gap in between

        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 (for a Turtle instance named turtle):
        >>> tp = turtle.pos()
        >>> tp
        (0.00,0.00)
        >>> turtle.teleport(60)
        >>> turtle.pos()
        (60.00,0.00)
        >>> turtle.teleport(y=10)
        >>> turtle.pos()
        (60.00,10.00)
        >>> turtle.teleport(20, 30)
        >>> turtle.pos()
        (20.00,30.00)
        """
        pendown = self.isdown()
        was_filling = self.filling()
        if pendown:
            self.pen(pendown=False)
        if was_filling and not fill_gap:
            self.end_fill()
        new_x = x if x is not None else self._position[0]
        new_y = y if y is not None else self._position[1]
        self._position = Vec2D(new_x, new_y)
        self.pen(pendown=pendown)
        if was_filling and not fill_gap:
            self.begin_fill()

    def clone(self):
        """Create and return a clone of the turtle.

        No argument.

        Create and return a clone of the turtle with same position, heading
        and turtle properties.

        Example (for a Turtle instance named mick):
        mick = Turtle()
        joe = mick.clone()
        """
        screen = self.screen
        self._newLine(self._drawing)

        turtle = self.turtle
        self.screen = None
        self.turtle = None  # too make self deepcopy-able

        q = deepcopy(self)

        self.screen = screen
        self.turtle = turtle

        q.screen = screen
        q.turtle = _TurtleImage(screen, self.turtle.shapeIndex)

        screen._turtles.append(q)
        ttype = screen._shapes[self.turtle.shapeIndex]._type
        if ttype == "polygon":
            q.turtle._item = screen._createpoly()
        elif ttype == "image":
            q.turtle._item = screen._createimage(screen._shapes["blank"]._data)
        elif ttype == "compound":
            q.turtle._item = [screen._createpoly() for item in
                              screen._shapes[self.turtle.shapeIndex]._data]
        q.currentLineItem = screen._createline()
        q._update()
        return q

    def shape(self, name=None):
        """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.
        Shape with name must exist in the TurtleScreen's shape dictionary.
        Initially there are the following polygon shapes:
        'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'.
        To learn about how to deal with shapes see Screen-method register_shape.

        Example (for a Turtle instance named turtle):
        >>> turtle.shape()
        'arrow'
        >>> turtle.shape("turtle")
        >>> turtle.shape()
        'turtle'
        """
        if name is None:
            return self.turtle.shapeIndex
        if not name in self.screen.getshapes():
            raise TurtleGraphicsError("There is no shape named %s" % name)
        self.turtle._setshape(name)
        self._update()

    def shapesize(self, stretch_wid=None, stretch_len=None, outline=None):
        """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.
        Set resizemode to "user".
        If and only if resizemode is set to "user", the turtle will be displayed
        stretched according to its stretchfactors:
        stretch_wid is stretchfactor perpendicular to orientation
        stretch_len is stretchfactor in direction of turtles orientation.
        outline determines the width of the shapes's outline.

        Examples (for a Turtle instance named turtle):
        >>> turtle.resizemode("user")
        >>> turtle.shapesize(5, 5, 12)
        >>> turtle.shapesize(outline=8)
        """
        if stretch_wid is stretch_len is outline is None:
            stretch_wid, stretch_len = self._stretchfactor
            return stretch_wid, stretch_len, self._outlinewidth
        if stretch_wid == 0 or stretch_len == 0:
            raise TurtleGraphicsError("stretch_wid/stretch_len must not be zero")
        if stretch_wid is not None:
            if stretch_len is None:
                stretchfactor = stretch_wid, stretch_wid
            else:
                stretchfactor = stretch_wid, stretch_len
        elif stretch_len is not None:
            stretchfactor = self._stretchfactor[0], stretch_len
        else:
            stretchfactor = self._stretchfactor
        if outline is None:
            outline = self._outlinewidth
        self.pen(resizemode="user",
                 stretchfactor=stretchfactor, outline=outline)

    def shearfactor(self, shear=None):
        """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. DO NOT change the
        turtle's heading (direction of movement).
        If shear is not given: return the current shearfactor, i. e. the
        tangent of the shear angle, by which lines parallel to the
        heading of the turtle are sheared.

        Examples (for a Turtle instance named turtle):
        >>> turtle.shape("circle")
        >>> turtle.shapesize(5,2)
        >>> turtle.shearfactor(0.5)
        >>> turtle.shearfactor()
        >>> 0.5
        """
        if shear is None:
            return self._shearfactor
        self.pen(resizemode="user", shearfactor=shear)

    def settiltangle(self, angle):
        """Rotate the turtleshape to point in the specified direction

        Argument: angle -- number

        Rotate the turtleshape to point in the direction specified by angle,
        regardless of its current tilt-angle. DO NOT change the turtle's
        heading (direction of movement).

        Deprecated since Python 3.1

        Examples (for a Turtle instance named turtle):
        >>> turtle.shape("circle")
        >>> turtle.shapesize(5,2)
        >>> turtle.settiltangle(45)
        >>> turtle.stamp()
        >>> turtle.fd(50)
        >>> turtle.settiltangle(-45)
        >>> turtle.stamp()
        >>> turtle.fd(50)
        """
        warnings._deprecated("turtle.RawTurtle.settiltangle()",
                             "{name!r} is deprecated since Python 3.1 and scheduled "
                             "for removal in Python {remove}. Use tiltangle() instead.",
                             remove=(3, 13))
        self.tiltangle(angle)

    def tiltangle(self, angle=None):
        """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. DO NOT change the turtle's
        heading (direction of movement).
        If angle is not given: return the current tilt-angle, i. e. the angle
        between the orientation of the turtleshape and the heading of the
        turtle (its direction of movement).

        (Incorrectly marked as deprecated since Python 3.1, it is really
        settiltangle that is deprecated.)

        Examples (for a Turtle instance named turtle):
        >>> turtle.shape("circle")
        >>> turtle.shapesize(5, 2)
        >>> turtle.tiltangle()
        0.0
        >>> turtle.tiltangle(45)
        >>> turtle.tiltangle()
        45.0
        >>> turtle.stamp()
        >>> turtle.fd(50)
        >>> turtle.tiltangle(-45)
        >>> turtle.tiltangle()
        315.0
        >>> turtle.stamp()
        >>> turtle.fd(50)
        """
        if angle is None:
            tilt = -math.degrees(self._tilt) * self._angleOrient
            return (tilt / self._degreesPerAU) % self._fullcircle
        else:
            tilt = -angle * self._degreesPerAU * self._angleOrient
            tilt = math.radians(tilt) % math.tau
            self.pen(resizemode="user", tilt=tilt)

    def tilt(self, angle):
        """Rotate the turtleshape by angle.

        Argument:
        angle - a number

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

        Examples (for a Turtle instance named turtle):
        >>> turtle.shape("circle")
        >>> turtle.shapesize(5,2)
        >>> turtle.tilt(30)
        >>> turtle.fd(50)
        >>> turtle.tilt(30)
        >>> turtle.fd(50)
        """
        self.tiltangle(angle + self.tiltangle())

    def shapetransform(self, t11=None, t12=None, t21=None, t22=None):
        """Set or return the current transformation matrix of the turtle shape.

        Optional arguments: t11, t12, t21, t22 -- numbers.

        If none of the matrix elements are given, return the transformation
        matrix.
        Otherwise set the given elements and transform the turtleshape
        according to the matrix consisting of first row t11, t12 and
        second row t21, 22.
        Modify stretchfactor, shearfactor and tiltangle according to the
        given matrix.

        Examples (for a Turtle instance named turtle):
        >>> turtle.shape("square")
        >>> turtle.shapesize(4,2)
        >>> turtle.shearfactor(-0.5)
        >>> turtle.shapetransform()
        (4.0, -1.0, -0.0, 2.0)
        """
        if t11 is t12 is t21 is t22 is None:
            return self._shapetrafo
        m11, m12, m21, m22 = self._shapetrafo
        if t11 is not None: m11 = t11
        if t12 is not None: m12 = t12
        if t21 is not None: m21 = t21
        if t22 is not None: m22 = t22
        if t11 * t22 - t12 * t21 == 0:
            raise TurtleGraphicsError("Bad shape transform matrix: must not be singular")
        self._shapetrafo = (m11, m12, m21, m22)
        alfa = math.atan2(-m21, m11) % math.tau
        sa, ca = math.sin(alfa), math.cos(alfa)
        a11, a12, a21, a22 = (ca*m11 - sa*m21, ca*m12 - sa*m22,
                              sa*m11 + ca*m21, sa*m12 + ca*m22)
        self._stretchfactor = a11, a22
        self._shearfactor = a12/a22
        self._tilt = alfa
        self.pen(resizemode="user")


    def _polytrafo(self, poly):
        """Computes transformed polygon shapes from a shape
        according to current position and heading.
        """
        screen = self.screen
        p0, p1 = self._position
        e0, e1 = self._orient
        e = Vec2D(e0, e1 * screen.yscale / screen.xscale)
        e0, e1 = (1.0 / abs(e)) * e
        return [(p0+(e1*x+e0*y)/screen.xscale, p1+(-e0*x+e1*y)/screen.yscale)
                                                           for (x, y) in poly]

    def get_shapepoly(self):
        """Return the current shape polygon as tuple of coordinate pairs.

        No argument.

        Examples (for a Turtle instance named turtle):
        >>> turtle.shape("square")
        >>> turtle.shapetransform(4, -1, 0, 2)
        >>> turtle.get_shapepoly()
        ((50, -20), (30, 20), (-50, 20), (-30, -20))

        """
        shape = self.screen._shapes[self.turtle.shapeIndex]
        if shape._type == "polygon":
            return self._getshapepoly(shape._data, shape._type == "compound")
        # else return None

    def _getshapepoly(self, polygon, compound=False):
        """Calculate transformed shape polygon according to resizemode
        and shapetransform.
        """
        if self._resizemode == "user" or compound:
            t11, t12, t21, t22 = self._shapetrafo
        elif self._resizemode == "auto":
            l = max(1, self._pensize/5.0)
            t11, t12, t21, t22 = l, 0, 0, l
        elif self._resizemode == "noresize":
            return polygon
        return tuple((t11*x + t12*y, t21*x + t22*y) for (x, y) in polygon)

    def _drawturtle(self):
        """Manages the correct rendering of the turtle with respect to
        its shape, resizemode, stretch and tilt etc."""
        screen = self.screen
        shape = screen._shapes[self.turtle.shapeIndex]
        ttype = shape._type
        titem = self.turtle._item
        if self._shown and screen._updatecounter == 0 and screen._tracing > 0:
            self._hidden_from_screen = False
            tshape = shape._data
            if ttype == "polygon":
                if self._resizemode == "noresize": w = 1
                elif self._resizemode == "auto": w = self._pensize
                else: w =self._outlinewidth
                shape = self._polytrafo(self._getshapepoly(tshape))
                fc, oc = self._fillcolor, self._pencolor
                screen._drawpoly(titem, shape, fill=fc, outline=oc,
                                                      width=w, top=True)
            elif ttype == "image":
                screen._drawimage(titem, self._position, tshape)
            elif ttype == "compound":
                for item, (poly, fc, oc) in zip(titem, tshape):
                    poly = self._polytrafo(self._getshapepoly(poly, True))
                    screen._drawpoly(item, poly, fill=self._cc(fc),
                                     outline=self._cc(oc), width=self._outlinewidth, top=True)
        else:
            if self._hidden_from_screen:
                return
            if ttype == "polygon":
                screen._drawpoly(titem, ((0, 0), (0, 0), (0, 0)), "", "")
            elif ttype == "image":
                screen._drawimage(titem, self._position,
                                          screen._shapes["blank"]._data)
            elif ttype == "compound":
                for item in titem:
                    screen._drawpoly(item, ((0, 0), (0, 0), (0, 0)), "", "")
            self._hidden_from_screen = True

##############################  stamp stuff  ###############################

    def stamp(self):
        """Stamp a copy of the turtleshape onto the canvas and return its id.

        No argument.

        Stamp a copy of the turtle shape onto the canvas at the current
        turtle position. Return a stamp_id for that stamp, which can be
        used to delete it by calling clearstamp(stamp_id).

        Example (for a Turtle instance named turtle):
        >>> turtle.color("blue")
        >>> turtle.stamp()
        13
        >>> turtle.fd(50)
        """
        screen = self.screen
        shape = screen._shapes[self.turtle.shapeIndex]
        ttype = shape._type
        tshape = shape._data
        if ttype == "polygon":
            stitem = screen._createpoly()
            if self._resizemode == "noresize": w = 1
            elif self._resizemode == "auto": w = self._pensize
            else: w =self._outlinewidth
            shape = self._polytrafo(self._getshapepoly(tshape))
            fc, oc = self._fillcolor, self._pencolor
            screen._drawpoly(stitem, shape, fill=fc, outline=oc,
                                                  width=w, top=True)
        elif ttype == "image":
            stitem = screen._createimage("")
            screen._drawimage(stitem, self._position, tshape)
        elif ttype == "compound":
            stitem = []
            for element in tshape:
                item = screen._createpoly()
                stitem.append(item)
            stitem = tuple(stitem)
            for item, (poly, fc, oc) in zip(stitem, tshape):
                poly = self._polytrafo(self._getshapepoly(poly, True))
                screen._drawpoly(item, poly, fill=self._cc(fc),
                                 outline=self._cc(oc), width=self._outlinewidth, top=True)
        self.stampItems.append(stitem)
        self.undobuffer.push(("stamp", stitem))
        return stitem

    def _clearstamp(self, stampid):
        """does the work for clearstamp() and clearstamps()
        """
        if stampid in self.stampItems:
            if isinstance(stampid, tuple):
                for subitem in stampid:
                    self.screen._delete(subitem)
            else:
                self.screen._delete(stampid)
            self.stampItems.remove(stampid)
        # Delete stampitem from undobuffer if necessary
        # if clearstamp is called directly.
        item = ("stamp", stampid)
        buf = self.undobuffer
        if item not in buf.buffer:
            return
        index = buf.buffer.index(item)
        buf.buffer.remove(item)
        if index <= buf.ptr:
            buf.ptr = (buf.ptr - 1) % buf.bufsize
        buf.buffer.insert((buf.ptr+1)%buf.bufsize, [None])

    def clearstamp(self, stampid):
        """Delete stamp with given stampid

        Argument:
        stampid - an integer, must be return value of previous stamp() call.

        Example (for a Turtle instance named turtle):
        >>> turtle.color("blue")
        >>> astamp = turtle.stamp()
        >>> turtle.fd(50)
        >>> turtle.clearstamp(astamp)
        """
        self._clearstamp(stampid)
        self._update()

    def clearstamps(self, n=None):
        """Delete all or first/last n of turtle's stamps.

        Optional argument:
        n -- an integer

        If n is None, delete all of pen's stamps,
        else if n > 0 delete first n stamps
        else if n < 0 delete last n stamps.

        Example (for a Turtle instance named turtle):
        >>> for i in range(8):
        ...     turtle.stamp(); turtle.fd(30)
        ...
        >>> turtle.clearstamps(2)
        >>> turtle.clearstamps(-2)
        >>> turtle.clearstamps()
        """
        if n is None:
            toDelete = self.stampItems[:]
        elif n >= 0:
            toDelete = self.stampItems[:n]
        else:
            toDelete = self.stampItems[n:]
        for item in toDelete:
            self._clearstamp(item)
        self._update()

    def _goto(self, end):
        """Move the pen to the point end, thereby drawing a line
        if pen is down. All other methods for turtle movement depend
        on this one.
        """
        ## Version with undo-stuff
        go_modes = ( self._drawing,
                     self._pencolor,
                     self._pensize,
                     isinstance(self._fillpath, list))
        screen = self.screen
        undo_entry = ("go", self._position, end, go_modes,
                      (self.currentLineItem,
                      self.currentLine[:],
                      screen._pointlist(self.currentLineItem),
                      self.items[:])
                      )
        if self.undobuffer:
            self.undobuffer.push(undo_entry)
        start = self._position
        if self._speed and screen._tracing == 1:
            diff = (end-start)
            diffsq = (diff[0]*screen.xscale)**2 + (diff[1]*screen.yscale)**2
            nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed))
            delta = diff * (1.0/nhops)
            for n in range(1, nhops):
                if n == 1:
                    top = True
                else:
                    top = False
                self._position = start + delta * n
                if self._drawing:
                    screen._drawline(self.drawingLineItem,
                                     (start, self._position),
                                     self._pencolor, self._pensize, top)
                self._update()
            if self._drawing:
                screen._drawline(self.drawingLineItem, ((0, 0), (0, 0)),
                                               fill="", width=self._pensize)
        # Turtle now at end,
        if self._drawing: # now update currentLine
            self.currentLine.append(end)
        if isinstance(self._fillpath, list):
            self._fillpath.append(end)
        ######    vererbung!!!!!!!!!!!!!!!!!!!!!!
        self._position = end
        if self._creatingPoly:
            self._poly.append(end)
        if len(self.currentLine) > 42: # 42! answer to the ultimate question
                                       # of life, the universe and everything
            self._newLine()
        self._update() #count=True)

    def _undogoto(self, entry):
        """Reverse a _goto. Used for undo()
        """
        old, new, go_modes, coodata = entry
        drawing, pc, ps, filling = go_modes
        cLI, cL, pl, items = coodata
        screen = self.screen
        if abs(self._position - new) > 0.5:
            print ("undogoto: HALLO-DA-STIMMT-WAS-NICHT!")
        # restore former situation
        self.currentLineItem = cLI
        self.currentLine = cL

        if pl == [(0, 0), (0, 0)]:
            usepc = ""
        else:
            usepc = pc
        screen._drawline(cLI, pl, fill=usepc, width=ps)

        todelete = [i for i in self.items if (i not in items) and
                                       (screen._type(i) == "line")]
        for i in todelete:
            screen._delete(i)
            self.items.remove(i)

        start = old
        if self._speed and screen._tracing == 1:
            diff = old - new
            diffsq = (diff[0]*screen.xscale)**2 + (diff[1]*screen.yscale)**2
            nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed))
            delta = diff * (1.0/nhops)
            for n in range(1, nhops):
                if n == 1:
                    top = True
                else:
                    top = False
                self._position = new + delta * n
                if drawing:
                    screen._drawline(self.drawingLineItem,
                                     (start, self._position),
                                     pc, ps, top)
                self._update()
            if drawing:
                screen._drawline(self.drawingLineItem, ((0, 0), (0, 0)),
                                               fill="", width=ps)
        # Turtle now at position old,
        self._position = old
        ##  if undo is done during creating a polygon, the last vertex
        ##  will be deleted. if the polygon is entirely deleted,
        ##  creatingPoly will be set to False.
        ##  Polygons created before the last one will not be affected by undo()
        if self._creatingPoly:
            if len(self._poly) > 0:
                self._poly.pop()
            if self._poly == []:
                self._creatingPoly = False
                self._poly = None
        if filling:
            if self._fillpath == []:
                self._fillpath = None
                print("Unwahrscheinlich in _undogoto!")
            elif self._fillpath is not None:
                self._fillpath.pop()
        self._update() #count=True)

    def _rotate(self, angle):
        """Turns pen clockwise by angle.
        """
        if self.undobuffer:
            self.undobuffer.push(("rot", angle, self._degreesPerAU))
        angle *= self._degreesPerAU
        neworient = self._orient.rotate(angle)
        tracing = self.screen._tracing
        if tracing == 1 and self._speed > 0:
            anglevel = 3.0 * self._speed
            steps = 1 + int(abs(angle)/anglevel)
            delta = 1.0*angle/steps
            for _ in range(steps):
                self._orient = self._orient.rotate(delta)
                self._update()
        self._orient = neworient
        self._update()

    def _newLine(self, usePos=True):
        """Closes current line item and starts a new one.
           Remark: if current line became too long, animation
           performance (via _drawline) slowed down considerably.
        """
        if len(self.currentLine) > 1:
            self.screen._drawline(self.currentLineItem, self.currentLine,
                                      self._pencolor, self._pensize)
            self.currentLineItem = self.screen._createline()
            self.items.append(self.currentLineItem)
        else:
            self.screen._drawline(self.currentLineItem, top=True)
        self.currentLine = []
        if usePos:
            self.currentLine = [self._position]

    def filling(self):
        """Return fillstate (True if filling, False else).

        No argument.

        Example (for a Turtle instance named turtle):
        >>> turtle.begin_fill()
        >>> if turtle.filling():
        ...     turtle.pensize(5)
        ... else:
        ...     turtle.pensize(3)
        """
        return isinstance(self._fillpath, list)

    def begin_fill(self):
        """Called just before drawing a shape to be filled.

        No argument.

        Example (for a Turtle instance named turtle):
        >>> turtle.color("black", "red")
        >>> turtle.begin_fill()
        >>> turtle.circle(60)
        >>> turtle.end_fill()
        """
        if not self.filling():
            self._fillitem = self.screen._createpoly()
            self.items.append(self._fillitem)
        self._fillpath = [self._position]
        self._newLine()
        if self.undobuffer:
            self.undobuffer.push(("beginfill", self._fillitem))
        self._update()


    def end_fill(self):
        """Fill the shape drawn after the call begin_fill().

        No argument.

        Example (for a Turtle instance named turtle):
        >>> turtle.color("black", "red")
        >>> turtle.begin_fill()
        >>> turtle.circle(60)
        >>> turtle.end_fill()
        """
        if self.filling():
            if len(self._fillpath) > 2:
                self.screen._drawpoly(self._fillitem, self._fillpath,
                                      fill=self._fillcolor)
                if self.undobuffer:
                    self.undobuffer.push(("dofill", self._fillitem))
            self._fillitem = self._fillpath = None
            self._update()

    def dot(self, size=None, *color):
        """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 (for a Turtle instance named turtle):
        >>> turtle.dot()
        >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
        """
        if not color:
            if isinstance(size, (str, tuple)):
                color = self._colorstr(size)
                size = self._pensize + max(self._pensize, 4)
            else:
                color = self._pencolor
                if not size:
                    size = self._pensize + max(self._pensize, 4)
        else:
            if size is None:
                size = self._pensize + max(self._pensize, 4)
            color = self._colorstr(color)
        # If screen were to gain a dot function, see GH #104218.
        pen = self.pen()
        if self.undobuffer:
            self.undobuffer.push(["seq"])
            self.undobuffer.cumulate = True
        try:
            if self.resizemode() == 'auto':
                self.ht()
            self.pendown()
            self.pensize(size)
            self.pencolor(color)
            self.forward(0)
        finally:
            self.pen(pen)
        if self.undobuffer:
            self.undobuffer.cumulate = False

    def _write(self, txt, align, font):
        """Performs the writing for write()
        """
        item, end = self.screen._write(self._position, txt, align, font,
                                                          self._pencolor)
        self._update()
        self.items.append(item)
        if self.undobuffer:
            self.undobuffer.push(("wri", item))
        return end

    def write(self, arg, move=False, align="left", font=("Arial", 8, "normal")):
        """Write text at the current turtle position.

        Arguments:
        arg -- info, which is to be written to the TurtleScreen
        move (optional) -- True/False
        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.
        If move is True, the pen is moved to the bottom-right corner
        of the text. By default, move is False.

        Example (for a Turtle instance named turtle):
        >>> turtle.write('Home = ', True, align="center")
        >>> turtle.write((0,0), True)
        """
        if self.undobuffer:
            self.undobuffer.push(["seq"])
            self.undobuffer.cumulate = True
        end = self._write(str(arg), align.lower(), font)
        if move:
            x, y = self.pos()
            self.setpos(end, y)
        if self.undobuffer:
            self.undobuffer.cumulate = False

    def begin_poly(self):
        """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 (for a Turtle instance named turtle):
        >>> turtle.begin_poly()
        """
        self._poly = [self._position]
        self._creatingPoly = True

    def end_poly(self):
        """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 (for a Turtle instance named turtle):
        >>> turtle.end_poly()
        """
        self._creatingPoly = False

    def get_poly(self):
        """Return the lastly recorded polygon.

        No argument.

        Example (for a Turtle instance named turtle):
        >>> p = turtle.get_poly()
        >>> turtle.register_shape("myFavouriteShape", p)
        """
        ## check if there is any poly?
        if self._poly is not None:
            return tuple(self._poly)

    def getscreen(self):
        """Return the TurtleScreen object, the turtle is drawing  on.

        No argument.

        Return the TurtleScreen object, the turtle is drawing  on.
        So TurtleScreen-methods can be called for that object.

        Example (for a Turtle instance named turtle):
        >>> ts = turtle.getscreen()
        >>> ts
        <turtle.TurtleScreen object at 0x0106B770>
        >>> ts.bgcolor("pink")
        """
        return self.screen

    def getturtle(self):
        """Return the Turtleobject itself.

        No argument.

        Only reasonable use: as a function to return the 'anonymous turtle':

        Example:
        >>> pet = getturtle()
        >>> pet.fd(50)
        >>> pet
        <turtle.Turtle object at 0x0187D810>
        >>> turtles()
        [<turtle.Turtle object at 0x0187D810>]
        """
        return self

    getpen = getturtle


    ################################################################
    ### screen oriented methods recurring to methods of TurtleScreen
    ################################################################

    def _delay(self, delay=None):
        """Set delay value which determines speed of turtle animation.
        """
        return self.screen.delay(delay)

    def onclick(self, fun, btn=1, add=None):
        """Bind fun to mouse-click event on this turtle on canvas.

        Arguments:
        fun --  a function with two arguments, to which will be assigned
                the coordinates of the clicked point on the canvas.
        btn --  number of the mouse-button defaults to 1 (left mouse button).
        add --  True or False. If True, new binding will be added, otherwise
                it will replace a former binding.

        Example for the anonymous turtle, i. e. the procedural way:

        >>> def turn(x, y):
        ...     left(360)
        ...
        >>> onclick(turn)  # Now clicking into the turtle will turn it.
        >>> onclick(None)  # event-binding will be removed
        """
        self.screen._onclick(self.turtle._item, fun, btn, add)
        self._update()

    def onrelease(self, fun, btn=1, add=None):
        """Bind fun to mouse-button-release event on this turtle on canvas.

        Arguments:
        fun -- a function with two arguments, to which will be assigned
                the coordinates of the clicked point on the canvas.
        btn --  number of the mouse-button defaults to 1 (left mouse button).

        Example (for a MyTurtle instance named joe):
        >>> class MyTurtle(Turtle):
        ...     def glow(self,x,y):
        ...             self.fillcolor("red")
        ...     def unglow(self,x,y):
        ...             self.fillcolor("")
        ...
        >>> joe = MyTurtle()
        >>> joe.onclick(joe.glow)
        >>> joe.onrelease(joe.unglow)

        Clicking on joe turns fillcolor red, unclicking turns it to
        transparent.
        """
        self.screen._onrelease(self.turtle._item, fun, btn, add)
        self._update()

    def ondrag(self, fun, btn=1, add=None):
        """Bind fun to mouse-move event on this turtle on canvas.

        Arguments:
        fun -- a function with two arguments, to which will be assigned
               the coordinates of the clicked point on the canvas.
        btn -- number of the mouse-button defaults to 1 (left mouse button).

        Every sequence of mouse-move-events on a turtle is preceded by a
        mouse-click event on that turtle.

        Example (for a Turtle instance named turtle):
        >>> turtle.ondrag(turtle.goto)

        Subsequently clicking and dragging a Turtle will move it
        across the screen thereby producing handdrawings (if pen is
        down).
        """
        self.screen._ondrag(self.turtle._item, fun, btn, add)


    def _undo(self, action, data):
        """Does the main part of the work for undo()
        """
        if self.undobuffer is None:
            return
        if action == "rot":
            angle, degPAU = data
            self._rotate(-angle*degPAU/self._degreesPerAU)
            dummy = self.undobuffer.pop()
        elif action == "stamp":
            stitem = data[0]
            self.clearstamp(stitem)
        elif action == "go":
            self._undogoto(data)
        elif action in ["wri", "dot"]:
            item = data[0]
            self.screen._delete(item)
            self.items.remove(item)
        elif action == "dofill":
            item = data[0]
            self.screen._drawpoly(item, ((0, 0),(0, 0),(0, 0)),
                                  fill="", outline="")
        elif action == "beginfill":
            item = data[0]
            self._fillitem = self._fillpath = None
            if item in self.items:
                self.screen._delete(item)
                self.items.remove(item)
        elif action == "pen":
            TPen.pen(self, data[0])
            self.undobuffer.pop()

    def undo(self):
        """undo (repeatedly) the last turtle action.

        No argument.

        undo (repeatedly) the last turtle action.
        Number of available undo actions is determined by the size of
        the undobuffer.

        Example (for a Turtle instance named turtle):
        >>> for i in range(4):
        ...     turtle.fd(50); turtle.lt(80)
        ...
        >>> for i in range(8):
        ...     turtle.undo()
        ...
        """
        if self.undobuffer is None:
            return
        item = self.undobuffer.pop()
        action = item[0]
        data = item[1:]
        if action == "seq":
            while data:
                item = data.pop()
                self._undo(item[0], item[1:])
        else:
            self._undo(action, data)

    turtlesize = shapesize

RawPen = RawTurtle

###  Screen - Singleton  ########################

def Screen():
    """Return the singleton screen object.
    If none exists at the moment, create a new one and return it,
    else return the existing one."""
    if Turtle._screen is None:
        Turtle._screen = _Screen()
    return Turtle._screen

class _Screen(TurtleScreen):

    _root = None
    _canvas = None
    _title = _CFG["title"]

    def __init__(self):
        if _Screen._root is None:
            _Screen._root = self._root = _Root()
            self._root.title(_Screen._title)
            self._root.ondestroy(self._destroy)
        if _Screen._canvas is None:
            width = _CFG["width"]
            height = _CFG["height"]
            canvwidth = _CFG["canvwidth"]
            canvheight = _CFG["canvheight"]
            leftright = _CFG["leftright"]
            topbottom = _CFG["topbottom"]
            self._root.setupcanvas(width, height, canvwidth, canvheight)
            _Screen._canvas = self._root._getcanvas()
            TurtleScreen.__init__(self, _Screen._canvas)
            self.setup(width, height, leftright, topbottom)

    def setup(self, width=_CFG["width"], height=_CFG["height"],
              startx=_CFG["leftright"], starty=_CFG["topbottom"]):
        """ Set the size and position of the main window.

        Arguments:
        width: as integer a size in pixels, as float a fraction of the screen.
          Default is 50% of screen.
        height: as integer the height in pixels, as float a fraction of the
          screen. Default is 75% of screen.
        startx: if positive, starting position in pixels from the left
          edge of the screen, if negative from the right edge
          Default, startx=None is to center window horizontally.
        starty: if positive, starting position in pixels from the top
          edge of the screen, if negative from the bottom edge
          Default, starty=None is to center window vertically.

        Examples (for a Screen instance named screen):
        >>> screen.setup (width=200, height=200, startx=0, starty=0)

        sets window to 200x200 pixels, in upper left of screen

        >>> screen.setup(width=.75, height=0.5, startx=None, starty=None)

        sets window to 75% of screen by 50% of screen and centers
        """
        if not hasattr(self._root, "set_geometry"):
            return
        sw = self._root.win_width()
        sh = self._root.win_height()
        if isinstance(width, float) and 0 <= width <= 1:
            width = sw*width
        if startx is None:
            startx = (sw - width) / 2
        if isinstance(height, float) and 0 <= height <= 1:
            height = sh*height
        if starty is None:
            starty = (sh - height) / 2
        self._root.set_geometry(width, height, startx, starty)
        self.update()

    def title(self, titlestring):
        """Set title of turtle-window

        Argument:
        titlestring -- a string, to appear in the titlebar of the
                       turtle graphics window.

        This is a method of Screen-class. Not available for TurtleScreen-
        objects.

        Example (for a Screen instance named screen):
        >>> screen.title("Welcome to the turtle-zoo!")
        """
        if _Screen._root is not None:
            _Screen._root.title(titlestring)
        _Screen._title = titlestring

    def _destroy(self):
        root = self._root
        if root is _Screen._root:
            Turtle._pen = None
            Turtle._screen = None
            _Screen._root = None
            _Screen._canvas = None
        TurtleScreen._RUNNING = False
        root.destroy()

    def bye(self):
        """Shut the turtlegraphics window.

        Example (for a TurtleScreen instance named screen):
        >>> screen.bye()
        """
        self._destroy()

    def exitonclick(self):
        """Go into mainloop until the mouse is clicked.

        No arguments.

        Bind bye() method to mouseclick on TurtleScreen.
        If "using_IDLE" - value in configuration dictionary is False
        (default value), enter mainloop.
        If IDLE with -n switch (no subprocess) is used, this value should be
        set to True in turtle.cfg. In this case IDLE's mainloop
        is active also for the client script.

        This is a method of the Screen-class and not available for
        TurtleScreen instances.

        Example (for a Screen instance named screen):
        >>> screen.exitonclick()

        """
        def exitGracefully(x, y):
            """Screen.bye() with two dummy-parameters"""
            self.bye()
        self.onclick(exitGracefully)
        if _CFG["using_IDLE"]:
            return
        try:
            mainloop()
        except AttributeError:
            exit(0)

class Turtle(RawTurtle):
    """RawTurtle auto-creating (scrolled) canvas.

    When a Turtle object is created or a function derived from some
    Turtle method is called a TurtleScreen object is automatically created.
    """
    _pen = None
    _screen = None

    def __init__(self,
                 shape=_CFG["shape"],
                 undobuffersize=_CFG["undobuffersize"],
                 visible=_CFG["visible"]):
        if Turtle._screen is None:
            Turtle._screen = Screen()
        RawTurtle.__init__(self, Turtle._screen,
                           shape=shape,
                           undobuffersize=undobuffersize,
                           visible=visible)

Pen = Turtle

def write_docstringdict(filename="turtle_docstringdict"):
    """Create and write docstring-dictionary to file.

    Optional argument:
    filename -- a string, used as filename
                default value is turtle_docstringdict

    Has to be called explicitly, (not used by the turtle-graphics classes)
    The docstring dictionary will be written to the Python script <filename>.py
    It is intended to serve as a template for translation of the docstrings
    into different languages.
    """
    docsdict = {}

    for methodname in _tg_screen_functions:
        key = "_Screen."+methodname
        docsdict[key] = eval(key).__doc__
    for methodname in _tg_turtle_functions:
        key = "Turtle."+methodname
        docsdict[key] = eval(key).__doc__

    with open("%s.py" % filename,"w") as f:
        keys = sorted(x for x in docsdict
                      if x.split('.')[1] not in _alias_list)
        f.write('docsdict = {\n\n')
        for key in keys[:-1]:
            f.write('%s :\n' % repr(key))
            f.write('        """%s\n""",\n\n' % docsdict[key])
        key = keys[-1]
        f.write('%s :\n' % repr(key))
        f.write('        """%s\n"""\n\n' % docsdict[key])
        f.write("}\n")
        f.close()

def read_docstrings(lang):
    """Read in docstrings from lang-specific docstring dictionary.

    Transfer docstrings, translated to lang, from a dictionary-file
    to the methods of classes Screen and Turtle and - in revised form -
    to the corresponding functions.
    """
    modname = "turtle_docstringdict_%(language)s" % {'language':lang.lower()}
    module = __import__(modname)
    docsdict = module.docsdict
    for key in docsdict:
        try:
#            eval(key).im_func.__doc__ = docsdict[key]
            eval(key).__doc__ = docsdict[key]
        except Exception:
            print("Bad docstring-entry: %s" % key)

_LANGUAGE = _CFG["language"]

try:
    if _LANGUAGE != "english":
        read_docstrings(_LANGUAGE)
except ImportError:
    print("Cannot find docsdict for", _LANGUAGE)
except Exception:
    print ("Unknown Error when trying to import %s-docstring-dictionary" %
                                                                  _LANGUAGE)


def getmethparlist(ob):
    """Get strings describing the arguments for the given object

    Returns a pair of strings representing function parameter lists
    including parenthesis.  The first string is suitable for use in
    function definition and the second is suitable for use in function
    call.  The "self" parameter is not included.
    """
    orig_sig = inspect.signature(ob)
    # bit of a hack for methods - turn it into a function
    # but we drop the "self" param.
    # Try and build one for Python defined functions
    func_sig = orig_sig.replace(
        parameters=list(orig_sig.parameters.values())[1:],
    )

    call_args = []
    for param in func_sig.parameters.values():
        match param.kind:
            case (
                inspect.Parameter.POSITIONAL_ONLY
                | inspect.Parameter.POSITIONAL_OR_KEYWORD
            ):
                call_args.append(param.name)
            case inspect.Parameter.VAR_POSITIONAL:
                call_args.append(f'*{param.name}')
            case inspect.Parameter.KEYWORD_ONLY:
                call_args.append(f'{param.name}={param.name}')
            case inspect.Parameter.VAR_KEYWORD:
                call_args.append(f'**{param.name}')
            case _:
                raise RuntimeError('Unsupported parameter kind', param.kind)
    call_text = f'({', '.join(call_args)})'

    return str(func_sig), call_text

def _turtle_docrevise(docstr):
    """To reduce docstrings from RawTurtle class for functions
    """
    import re
    if docstr is None:
        return None
    turtlename = _CFG["exampleturtle"]
    newdocstr = docstr.replace("%s." % turtlename,"")
    parexp = re.compile(r' \(.+ %s\):' % turtlename)
    newdocstr = parexp.sub(":", newdocstr)
    return newdocstr

def _screen_docrevise(docstr):
    """To reduce docstrings from TurtleScreen class for functions
    """
    import re
    if docstr is None:
        return None
    screenname = _CFG["examplescreen"]
    newdocstr = docstr.replace("%s." % screenname,"")
    parexp = re.compile(r' \(.+ %s\):' % screenname)
    newdocstr = parexp.sub(":", newdocstr)
    return newdocstr

## The following mechanism makes all methods of RawTurtle and Turtle available
## as functions. So we can enhance, change, add, delete methods to these
## classes and do not need to change anything here.

__func_body = """\
def {name}{paramslist}:
    if {obj} is None:
        if not TurtleScreen._RUNNING:
            TurtleScreen._RUNNING = True
            raise Terminator
        {obj} = {init}
    try:
        return {obj}.{name}{argslist}
    except TK.TclError:
        if not TurtleScreen._RUNNING:
            TurtleScreen._RUNNING = True
            raise Terminator
        raise
"""

def _make_global_funcs(functions, cls, obj, init, docrevise):
    for methodname in functions:
        method = getattr(cls, methodname)
        pl1, pl2 = getmethparlist(method)
        if pl1 == "":
            print(">>>>>>", pl1, pl2)
            continue
        defstr = __func_body.format(obj=obj, init=init, name=methodname,
                                    paramslist=pl1, argslist=pl2)
        exec(defstr, globals())
        globals()[methodname].__doc__ = docrevise(method.__doc__)

_make_global_funcs(_tg_screen_functions, _Screen,
                   'Turtle._screen', 'Screen()', _screen_docrevise)
_make_global_funcs(_tg_turtle_functions, Turtle,
                   'Turtle._pen', 'Turtle()', _turtle_docrevise)


done = mainloop

if __name__ == "__main__":
    def switchpen():
        if isdown():
            pu()
        else:
            pd()

    def demo1():
        """Demo of old turtle.py - module"""
        reset()
        tracer(True)
        up()
        backward(100)
        down()
        # draw 3 squares; the last filled
        width(3)
        for i in range(3):
            if i == 2:
                begin_fill()
            for _ in range(4):
                forward(20)
                left(90)
            if i == 2:
                color("maroon")
                end_fill()
            up()
            forward(30)
            down()
        width(1)
        color("black")
        # move out of the way
        tracer(False)
        up()
        right(90)
        forward(100)
        right(90)
        forward(100)
        right(180)
        down()
        # some text
        write("startstart", 1)
        write("start", 1)
        color("red")
        # staircase
        for i in range(5):
            forward(20)
            left(90)
            forward(20)
            right(90)
        # filled staircase
        tracer(True)
        begin_fill()
        for i in range(5):
            forward(20)
            left(90)
            forward(20)
            right(90)
        end_fill()
        # more text

    def demo2():
        """Demo of some new features."""
        speed(1)
        st()
        pensize(3)
        setheading(towards(0, 0))
        radius = distance(0, 0)/2.0
        rt(90)
        for _ in range(18):
            switchpen()
            circle(radius, 10)
        write("wait a moment...")
        while undobufferentries():
            undo()
        reset()
        lt(90)
        colormode(255)
        laenge = 10
        pencolor("green")
        pensize(3)
        lt(180)
        for i in range(-2, 16):
            if i > 0:
                begin_fill()
                fillcolor(255-15*i, 0, 15*i)
            for _ in range(3):
                fd(laenge)
                lt(120)
            end_fill()
            laenge += 10
            lt(15)
            speed((speed()+1)%12)
        #end_fill()

        lt(120)
        pu()
        fd(70)
        rt(30)
        pd()
        color("red","yellow")
        speed(0)
        begin_fill()
        for _ in range(4):
            circle(50, 90)
            rt(90)
            fd(30)
            rt(90)
        end_fill()
        lt(90)
        pu()
        fd(30)
        pd()
        shape("turtle")

        tri = getturtle()
        tri.resizemode("auto")
        turtle = Turtle()
        turtle.resizemode("auto")
        turtle.shape("turtle")
        turtle.reset()
        turtle.left(90)
        turtle.speed(0)
        turtle.up()
        turtle.goto(280, 40)
        turtle.lt(30)
        turtle.down()
        turtle.speed(6)
        turtle.color("blue","orange")
        turtle.pensize(2)
        tri.speed(6)
        setheading(towards(turtle))
        count = 1
        while tri.distance(turtle) > 4:
            turtle.fd(3.5)
            turtle.lt(0.6)
            tri.setheading(tri.towards(turtle))
            tri.fd(4)
            if count % 20 == 0:
                turtle.stamp()
                tri.stamp()
                switchpen()
            count += 1
        tri.write("CAUGHT! ", font=("Arial", 16, "bold"), align="right")
        tri.pencolor("black")
        tri.pencolor("red")

        def baba(xdummy, ydummy):
            clearscreen()
            bye()

        time.sleep(2)

        while undobufferentries():
            tri.undo()
            turtle.undo()
        tri.fd(50)
        tri.write("  Click me!", font = ("Courier", 12, "bold") )
        tri.onclick(baba, 1)

    demo1()
    demo2()
    exitonclick()
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        .   K   ..     __init__.py    __main__.py    __pycache__    
bytedesign.py      chaos.py   clock.py   
colormixer.py       	forest.py   !   fractalcurves.py"   lindenmayer.py  #   minimal_hanoi.py$   nim.py  %   paint.py&   peace.py'   
penrose.py  (   planet_and_moon.py  )   
rosette.py  *   round_dance.py  +   sorting_animate.py  ,   tree.py -   
turtle.cfg  .   two_canvases.py /  
yinyang.py                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          """
    --------------------------------------
        About this viewer
    --------------------------------------

    Tiny demo viewer to view turtle graphics example scripts.

    Quickly and dirtyly assembled by Gregor Lingl.
    June, 2006

    For more information see: turtledemo - Help

    Have fun!
"""
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      #!/usr/bin/env python3

"""
  ----------------------------------------------
      turtleDemo - Help
  ----------------------------------------------

  This document has two sections:

  (1) How to use the demo viewer
  (2) How to add your own demos to the demo repository


  (1) How to use the demo viewer.

  Select a demoscript from the example menu.
  The (syntax colored) source code appears in the left
  source code window. IT CANNOT BE EDITED, but ONLY VIEWED!

  The demo viewer windows can be resized. The divider between text
  and canvas can be moved by grabbing it with the mouse. The text font
  size can be changed from the menu and with Control/Command '-'/'+'.
  It can also be changed on most systems with Control-mousewheel
  when the mouse is over the text.

  Press START button to start the demo.
  Stop execution by pressing the STOP button.
  Clear screen by pressing the CLEAR button.
  Restart by pressing the START button again.

  SPECIAL demos, such as clock.py are those which run EVENTDRIVEN.

      Press START button to start the demo.

      - Until the EVENTLOOP is entered everything works
      as in an ordinary demo script.

      - When the EVENTLOOP is entered, you control the
      application by using the mouse and/or keys (or it's
      controlled by some timer events)
      To stop it you can and must press the STOP button.

      While the EVENTLOOP is running, the examples menu is disabled.

      - Only after having pressed the STOP button, you may
      restart it or choose another example script.

   * * * * * * * *
   In some rare situations there may occur interferences/conflicts
   between events concerning the demo script and those concerning the
   demo-viewer. (They run in the same process.) Strange behaviour may be
   the consequence and in the worst case you must close and restart the
   viewer.
   * * * * * * * *


   (2) How to add your own demos to the demo repository

   - Place the file in the same directory as turtledemo/__main__.py
     IMPORTANT! When imported, the demo should not modify the system
     by calling functions in other modules, such as sys, tkinter, or
     turtle. Global variables should be initialized in main().

   - The code must contain a main() function which will
     be executed by the viewer (see provided example scripts).
     It may return a string which will be displayed in the Label below
     the source code window (when execution has finished.)

   - In order to run mydemo.py by itself, such as during development,
     add the following at the end of the file:

    if __name__ == '__main__':
        main()
        mainloop()  # keep window open

    python -m turtledemo.mydemo  # will then run it

   - If the demo is EVENT DRIVEN, main must return the string
     "EVENTLOOP". This informs the demo viewer that the script is
     still running and must be stopped by the user!

     If an "EVENTLOOP" demo runs by itself, as with clock, which uses
     ontimer, or minimal_hanoi, which loops by recursion, then the
     code should catch the turtle.Terminator exception that will be
     raised when the user presses the STOP button.  (Paint is not such
     a demo; it only acts in response to mouse clicks and movements.)
"""
import sys
import os

from tkinter import *
from idlelib.colorizer import ColorDelegator, color_config
from idlelib.percolator import Percolator
from idlelib.textview import view_text
import turtle
from turtledemo import __doc__ as about_turtledemo

if sys.platform == 'win32':
    from idlelib.util import fix_win_hidpi
    fix_win_hidpi()

demo_dir = os.path.dirname(os.path.abspath(__file__))
darwin = sys.platform == 'darwin'
STARTUP = 1
READY = 2
RUNNING = 3
DONE = 4
EVENTDRIVEN = 5

menufont = ("Arial", 12, NORMAL)
btnfont = ("Arial", 12, 'bold')
txtfont = ['Lucida Console', 10, 'normal']

MINIMUM_FONT_SIZE = 6
MAXIMUM_FONT_SIZE = 100
font_sizes = [8, 9, 10, 11, 12, 14, 18, 20, 22, 24, 30]

def getExampleEntries():
    return [entry[:-3] for entry in os.listdir(demo_dir) if
            entry.endswith(".py") and entry[0] != '_']

help_entries = (  # (help_label,  help_doc)
    ('Turtledemo help', __doc__),
    ('About turtledemo', about_turtledemo),
    ('About turtle module', turtle.__doc__),
    )


class DemoWindow(object):

    def __init__(self, filename=None):
        self.root = root = turtle._root = Tk()
        root.title('Python turtle-graphics examples')
        root.wm_protocol("WM_DELETE_WINDOW", self._destroy)

        if darwin:
            import subprocess
            # Make sure we are the currently activated OS X application
            # so that our menu bar appears.
            subprocess.run(
                    [
                        '/usr/bin/osascript',
                        '-e', 'tell application "System Events"',
                        '-e', 'set frontmost of the first process whose '
                              'unix id is {} to true'.format(os.getpid()),
                        '-e', 'end tell',
                    ],
                    stderr=subprocess.DEVNULL,
                    stdout=subprocess.DEVNULL,)

        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(0, weight=1)
        root.grid_columnconfigure(1, minsize=90, weight=1)
        root.grid_columnconfigure(2, minsize=90, weight=1)
        root.grid_columnconfigure(3, minsize=90, weight=1)

        self.mBar = Menu(root, relief=RAISED, borderwidth=2)
        self.mBar.add_cascade(menu=self.makeLoadDemoMenu(self.mBar),
                              label='Examples', underline=0)
        self.mBar.add_cascade(menu=self.makeFontMenu(self.mBar),
                              label='Fontsize', underline=0)
        self.mBar.add_cascade(menu=self.makeHelpMenu(self.mBar),
                              label='Help', underline=0)
        root['menu'] = self.mBar

        pane = PanedWindow(root, orient=HORIZONTAL, sashwidth=5,
                           sashrelief=SOLID, bg='#ddd')
        pane.add(self.makeTextFrame(pane))
        pane.add(self.makeGraphFrame(pane))
        pane.grid(row=0, columnspan=4, sticky='news')

        self.output_lbl = Label(root, height= 1, text=" --- ", bg="#ddf",
                                font=("Arial", 16, 'normal'), borderwidth=2,
                                relief=RIDGE)
        if darwin:  # Leave Mac button colors alone - #44254.
            self.start_btn = Button(root, text=" START ", font=btnfont,
                                    fg='#00cc22', command=self.startDemo)
            self.stop_btn = Button(root, text=" STOP ", font=btnfont,
                                   fg='#00cc22', command=self.stopIt)
            self.clear_btn = Button(root, text=" CLEAR ", font=btnfont,
                                    fg='#00cc22', command = self.clearCanvas)
        else:
            self.start_btn = Button(root, text=" START ", font=btnfont,
                                    fg="white", disabledforeground = "#fed",
                                    command=self.startDemo)
            self.stop_btn = Button(root, text=" STOP ", font=btnfont,
                                   fg="white", disabledforeground = "#fed",
                                   command=self.stopIt)
            self.clear_btn = Button(root, text=" CLEAR ", font=btnfont,
                                    fg="white", disabledforeground="#fed",
                                    command = self.clearCanvas)
        self.output_lbl.grid(row=1, column=0, sticky='news', padx=(0,5))
        self.start_btn.grid(row=1, column=1, sticky='ew')
        self.stop_btn.grid(row=1, column=2, sticky='ew')
        self.clear_btn.grid(row=1, column=3, sticky='ew')

        Percolator(self.text).insertfilter(ColorDelegator())
        self.dirty = False
        self.exitflag = False
        if filename:
            self.loadfile(filename)
        self.configGUI(DISABLED, DISABLED, DISABLED,
                       "Choose example from menu", "black")
        self.state = STARTUP


    def onResize(self, event):
        cwidth = self.canvas.winfo_width()
        cheight = self.canvas.winfo_height()
        self.canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth)
        self.canvas.yview_moveto(0.5*(self.canvheight-cheight)/self.canvheight)

    def makeTextFrame(self, root):
        self.text_frame = text_frame = Frame(root)
        self.text = text = Text(text_frame, name='text', padx=5,
                                wrap='none', width=45)
        color_config(text)

        self.vbar = vbar = Scrollbar(text_frame, name='vbar')
        vbar['command'] = text.yview
        vbar.pack(side=LEFT, fill=Y)
        self.hbar = hbar = Scrollbar(text_frame, name='hbar', orient=HORIZONTAL)
        hbar['command'] = text.xview
        hbar.pack(side=BOTTOM, fill=X)
        text['yscrollcommand'] = vbar.set
        text['xscrollcommand'] = hbar.set

        text['font'] = tuple(txtfont)
        shortcut = 'Command' if darwin else 'Control'
        text.bind_all('<%s-minus>' % shortcut, self.decrease_size)
        text.bind_all('<%s-underscore>' % shortcut, self.decrease_size)
        text.bind_all('<%s-equal>' % shortcut, self.increase_size)
        text.bind_all('<%s-plus>' % shortcut, self.increase_size)
        text.bind('<Control-MouseWheel>', self.update_mousewheel)
        text.bind('<Control-Button-4>', self.increase_size)
        text.bind('<Control-Button-5>', self.decrease_size)

        text.pack(side=LEFT, fill=BOTH, expand=1)
        return text_frame

    def makeGraphFrame(self, root):
        # t._Screen is a singleton class instantiated or retrieved
        # by calling Screen.  Since tdemo canvas needs a different
        # configuration, we manually set class attributes before
        # calling Screen and manually call superclass init after.
        turtle._Screen._root = root

        self.canvwidth = 1000
        self.canvheight = 800
        turtle._Screen._canvas = self.canvas = canvas = turtle.ScrolledCanvas(
                root, 800, 600, self.canvwidth, self.canvheight)
        canvas.adjustScrolls()
        canvas._rootwindow.bind('<Configure>', self.onResize)
        canvas._canvas['borderwidth'] = 0

        self.screen = screen = turtle.Screen()
        turtle.TurtleScreen.__init__(screen, canvas)
        turtle.RawTurtle.screens = [screen]
        return canvas

    def set_txtsize(self, size):
        txtfont[1] = size
        self.text['font'] = tuple(txtfont)
        self.output_lbl['text'] = 'Font size %d' % size

    def decrease_size(self, dummy=None):
        self.set_txtsize(max(txtfont[1] - 1, MINIMUM_FONT_SIZE))
        return 'break'

    def increase_size(self, dummy=None):
        self.set_txtsize(min(txtfont[1] + 1, MAXIMUM_FONT_SIZE))
        return 'break'

    def update_mousewheel(self, event):
        # For wheel up, event.delta = 120 on Windows, -1 on darwin.
        # X-11 sends Control-Button-4 event instead.
        if (event.delta < 0) == (not darwin):
            return self.decrease_size()
        else:
            return self.increase_size()

    def configGUI(self, start, stop, clear, txt="", color="blue"):
        if darwin:  # Leave Mac button colors alone - #44254.
            self.start_btn.config(state=start)
            self.stop_btn.config(state=stop)
            self.clear_btn.config(state=clear)
        else:
            self.start_btn.config(state=start,
                                  bg="#d00" if start == NORMAL else "#fca")
            self.stop_btn.config(state=stop,
                                 bg="#d00" if stop == NORMAL else "#fca")
            self.clear_btn.config(state=clear,
                                  bg="#d00" if clear == NORMAL else "#fca")
        self.output_lbl.config(text=txt, fg=color)

    def makeLoadDemoMenu(self, master):
        menu = Menu(master)

        for entry in getExampleEntries():
            def load(entry=entry):
                self.loadfile(entry)
            menu.add_command(label=entry, underline=0,
                             font=menufont, command=load)
        return menu

    def makeFontMenu(self, master):
        menu = Menu(master)
        menu.add_command(label="Decrease (C-'-')", command=self.decrease_size,
                         font=menufont)
        menu.add_command(label="Increase (C-'+')", command=self.increase_size,
                         font=menufont)
        menu.add_separator()

        for size in font_sizes:
            def resize(size=size):
                self.set_txtsize(size)
            menu.add_command(label=str(size), underline=0,
                             font=menufont, command=resize)
        return menu

    def makeHelpMenu(self, master):
        menu = Menu(master)

        for help_label, help_file in help_entries:
            def show(help_label=help_label, help_file=help_file):
                view_text(self.root, help_label, help_file)
            menu.add_command(label=help_label, font=menufont, command=show)
        return menu

    def refreshCanvas(self):
        if self.dirty:
            self.screen.clear()
            self.dirty=False

    def loadfile(self, filename):
        self.clearCanvas()
        turtle.TurtleScreen._RUNNING = False
        modname = 'turtledemo.' + filename
        __import__(modname)
        self.module = sys.modules[modname]
        with open(self.module.__file__, 'r') as f:
            chars = f.read()
        self.text.delete("1.0", "end")
        self.text.insert("1.0", chars)
        self.root.title(filename + " - a Python turtle graphics example")
        self.configGUI(NORMAL, DISABLED, DISABLED,
                       "Press start button", "red")
        self.state = READY

    def startDemo(self):
        self.refreshCanvas()
        self.dirty = True
        turtle.TurtleScreen._RUNNING = True
        self.configGUI(DISABLED, NORMAL, DISABLED,
                       "demo running...", "black")
        self.screen.clear()
        self.screen.mode("standard")
        self.state = RUNNING

        try:
            result = self.module.main()
            if result == "EVENTLOOP":
                self.state = EVENTDRIVEN
            else:
                self.state = DONE
        except turtle.Terminator:
            if self.root is None:
                return
            self.state = DONE
            result = "stopped!"
        if self.state == DONE:
            self.configGUI(NORMAL, DISABLED, NORMAL,
                           result)
        elif self.state == EVENTDRIVEN:
            self.exitflag = True
            self.configGUI(DISABLED, NORMAL, DISABLED,
                           "use mouse/keys or STOP", "red")

    def clearCanvas(self):
        self.refreshCanvas()
        self.screen._delete("all")
        self.canvas.config(cursor="")
        self.configGUI(NORMAL, DISABLED, DISABLED)

    def stopIt(self):
        if self.exitflag:
            self.clearCanvas()
            self.exitflag = False
            self.configGUI(NORMAL, DISABLED, DISABLED,
                           "STOPPED!", "red")
        turtle.TurtleScreen._RUNNING = False

    def _destroy(self):
        turtle.TurtleScreen._RUNNING = False
        self.root.destroy()
        self.root = None


def main():
    demo = DemoWindow()
    demo.root.mainloop()

if __name__ == '__main__':
    main()
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           .      ..      __init__.cpython-312.pyc    __main__.cpython-312.pyc	  $ bytedesign.cpython-312.pyc  
    chaos.cpython-312.pyc       clock.cpython-312.pyc     $ colormixer.cpython-312.pyc  
    forest.cpython-312.pyc    ( fractalcurves.cpython-312.pyc     $ lindenmayer.cpython-312.pyc   ( minimal_hanoi.cpython-312.pyc      nim.cpython-312.pyc     paint.cpython-312.pyc       peace.cpython-312.pyc       penrose.cpython-312.pyc   ( planet_and_moon.cpython-312.pyc     rosette.cpython-312.pyc   $ round_dance.cpython-312.pyc   ( sorting_animate.cpython-312.pyc    tree.cpython-312.pyc  $ two_canvases.cpython-312.pyc  <
yinyang.cpython-312.pyc                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

   h~                       d Z y)a3  
    --------------------------------------
        About this viewer
    --------------------------------------

    Tiny demo viewer to view turtle graphics example scripts.

    Quickly and dirtyly assembled by Gregor Lingl.
    June, 2006

    For more information see: turtledemo - Help

    Have fun!
N)__doc__     */usr/lib/python3.12/turtledemo/__init__.py<module>r      s
   
r                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 

   <A                      d Z ddlZddlZddl ddlmZmZ ddlmZ ddl	m
Z
 ddlZddlm Z
 ej                  dk(  r
dd	lmZ  e        ej"                  j%                  ej"                  j'                  e            Zej                  d
k(  ZdZdZd
ZdZdZddefZdZg dZdZ dZ!g dZ"d Z#de fde
fdej                   ffZ$ G d de%      Z&d Z'e(dk(  r e'        yy)a  
  ----------------------------------------------
      turtleDemo - Help
  ----------------------------------------------

  This document has two sections:

  (1) How to use the demo viewer
  (2) How to add your own demos to the demo repository


  (1) How to use the demo viewer.

  Select a demoscript from the example menu.
  The (syntax colored) source code appears in the left
  source code window. IT CANNOT BE EDITED, but ONLY VIEWED!

  The demo viewer windows can be resized. The divider between text
  and canvas can be moved by grabbing it with the mouse. The text font
  size can be changed from the menu and with Control/Command '-'/'+'.
  It can also be changed on most systems with Control-mousewheel
  when the mouse is over the text.

  Press START button to start the demo.
  Stop execution by pressing the STOP button.
  Clear screen by pressing the CLEAR button.
  Restart by pressing the START button again.

  SPECIAL demos, such as clock.py are those which run EVENTDRIVEN.

      Press START button to start the demo.

      - Until the EVENTLOOP is entered everything works
      as in an ordinary demo script.

      - When the EVENTLOOP is entered, you control the
      application by using the mouse and/or keys (or it's
      controlled by some timer events)
      To stop it you can and must press the STOP button.

      While the EVENTLOOP is running, the examples menu is disabled.

      - Only after having pressed the STOP button, you may
      restart it or choose another example script.

   * * * * * * * *
   In some rare situations there may occur interferences/conflicts
   between events concerning the demo script and those concerning the
   demo-viewer. (They run in the same process.) Strange behaviour may be
   the consequence and in the worst case you must close and restart the
   viewer.
   * * * * * * * *


   (2) How to add your own demos to the demo repository

   - Place the file in the same directory as turtledemo/__main__.py
     IMPORTANT! When imported, the demo should not modify the system
     by calling functions in other modules, such as sys, tkinter, or
     turtle. Global variables should be initialized in main().

   - The code must contain a main() function which will
     be executed by the viewer (see provided example scripts).
     It may return a string which will be displayed in the Label below
     the source code window (when execution has finished.)

   - In order to run mydemo.py by itself, such as during development,
     add the following at the end of the file:

    if __name__ == '__main__':
        main()
        mainloop()  # keep window open

    python -m turtledemo.mydemo  # will then run it

   - If the demo is EVENT DRIVEN, main must return the string
     "EVENTLOOP". This informs the demo viewer that the script is
     still running and must be stopped by the user!

     If an "EVENTLOOP" demo runs by itself, as with clock, which uses
     ontimer, or minimal_hanoi, which loops by recursion, then the
     code should catch the turtle.Terminator exception that will be
     raised when the user presses the STOP button.  (Paint is not such
     a demo; it only acts in response to mouse clicks and movements.)
    N)*)ColorDelegatorcolor_config)
Percolator)	view_text)__doc__win32)
fix_win_hidpidarwin               Arial   )r   r   bold)zLucida Console
   normal   d   )   	   r      r                     c                      t        j                  t              D  cg c]   } | j                  d      r
| d   dk7  r| d d " c} S c c} w )Nz.pyr   _)oslistdirdemo_direndswith)entrys    */usr/lib/python3.12/turtledemo/__main__.pygetExampleEntriesr*   v   sL    $&JJx$8 7$85NN5!eAh#o 
#2J$8 7 7 7s   %AzTurtledemo helpzAbout turtledemozAbout turtle modulec                       e Zd ZddZd Zd Zd Zd ZddZddZ	d	 Z
dd
Zd Zd Z
d
 Zd Zd Zd Zd Zd Zd Zy)
DemoWindowNc           
      N   t               x| _        x}t        _        |j	                  d       |j                  d| j                         t        rTdd l}|j                  dddddj                  t        j                               ddg|j                  |j                  	       |j                  dd
       |j                  dd
       |j                  d
dd

       |j                  ddd

       |j                  ddd

       t!        |t"        d      | _        | j$                  j'                  | j)                  | j$                        dd       | j$                  j'                  | j+                  | j$                        dd       | j$                  j'                  | j-                  | j$                        dd       | j$                  |d<   t/        |t0        dt2        d      }|j5                  | j7                  |             |j5                  | j9                  |             |j;                  ddd       t=        |d
ddddt>              | _         t        rjtC        |d tD        d!| jF                  "      | _$        tC        |d#tD        d!| jJ                  "      | _&        tC        |d$tD        d!| jN                  "      | _(        nltC        |d tD        d%d&| jF                  '      | _$        tC        |d#tD        d%d&| jJ                  '      | _&        tC        |d$tD        d%d&| jN                  '      | _(        | j@                  j;                  d
ddd()       | jH                  j;                  d
d
d*+       | jL                  j;                  d
dd*+       | jP                  j;                  d
dd*+       tS        | jT                        jW                  tY                      d,| _-        d,| _.        |r| j_                  |       | ja                  tb        tb        tb        d-d.       td        | _3        y )/NzPython turtle-graphics examplesWM_DELETE_WINDOWr   z/usr/bin/osascriptz-ez tell application "System Events"z>set frontmost of the first process whose unix id is {} to truezend tell)stderrstdoutr   )weightZ   )minsizer1   r
   r   )reliefborderwidthExamples)menulabel	underlineFontsizeHelpr7   r   z#ddd)orient	sashwidth
sashreliefbgr   news)row
columnspanstickyz --- z#ddf)r      r   )heighttextr?   fontr5   r4   z START z#00cc22)rF   rG   fgcommandz STOP z CLEAR whitez#fed)rF   rG   rH   disabledforegroundrI   )r   r   )rA   columnrC   padxew)rA   rL   rC   FzChoose example from menublack)4Tkrootturtle_roottitlewm_protocol_destroyr   
subprocessrunformatr$   getpidDEVNULLgrid_rowconfiguregrid_columnconfigureMenuRAISEDmBaradd_cascademakeLoadDemoMenumakeFontMenumakeHelpMenuPanedWindow
HORIZONTALSOLIDadd
makeTextFramemakeGraphFramegridLabelRIDGE
output_lblButtonbtnfont	startDemo	start_btnstopItstop_btnclearCanvas	clear_btnr   rF   insertfilterr   dirtyexitflagloadfile	configGUIDISABLEDSTARTUPstate)selffilenamerQ   rW   panes        r)   __init__zDemoWindow.__init__   s   *,$.	.D6<

45+T]]; 
NN,@ 66<fRYY[6Ij &--%-- 
 	
0 	
q+!!!A!.!!!R!:!!!R!:!!!R!:f!<			4#8#8#C$.! 	 	=		4#4#4TYY#?$.! 	 	=		4#4#4TYY#?$*a 	 	9yyV4
a&+8##D)*$$T*+		aAf	5ag&%<!',. #Dyw'0$..JDN"4hW&/FDM#Dyw'0D<L<LNDN $Dyw'.V,0NN<DN #4hW&-F+/;;8DM $Dyw'.6.2.>.>@DN 	
1V%H!D9

q48!D9499**>+;<

MM(#x817	<
    c                 L   | j                   j                         }| j                   j                         }| j                   j                  d| j                  |z
  z  | j                  z         | j                   j                  d| j                  |z
  z  | j                  z         y )Ng      ?)canvaswinfo_widthwinfo_heightxview_moveto	canvwidthyview_moveto
canvheight)r   eventcwidthcheights       r)   onResizezDemoWindow.onResize   sx    ((*++**,  dnnV&;!<T^^!KL  doog&=!>t!NOr   c                    t        |      x| _        }t        |dddd      x| _        }t	        |       t        |d      x| _        }|j                  |d<   |j                  t        t        	       t        |d
t              x| _        }|j                  |d<   |j                  t        t        	       |j                   |d<   |j                   |d
<   t#        t$              |d<   t&        rdnd}|j)                  d|z  | j*                         |j)                  d|z  | j*                         |j)                  d|z  | j,                         |j)                  d|z  | j,                         |j/                  d| j0                         |j/                  d| j,                         |j/                  d| j*                         |j                  t        t2        d       |S )NrF   r   none-   )namerM   wrapwidthvbar)r   rI   )sidefillhbar)r   r<   yscrollcommandxscrollcommandrG   CommandControlz
<%s-minus>z<%s-underscore>z
<%s-equal>z	<%s-plus>z<Control-MouseWheel>z<Control-Button-4>z<Control-Button-5>r   )r   r   expand)Frame
text_frameTextrF   r   	Scrollbarr   yviewpackLEFTYrf   r   xviewBOTTOMXsettupletxtfontr   bind_all
decrease_size
increase_sizebindupdate_mousewheelBOTH)r   rQ   r   rF   r   r   shortcuts          r)   ri   zDemoWindow.makeTextFrame   s   ',T{2*
a%+27 	7	DT$Zf==	D**Y		t!	$$ZfZPP	D**Y		vA	&!%
!%
W~V &9I

lX-t/A/AB

'(2D4F4FG

lX-t/A/AB

kH,d.@.@A		($*@*@A		&(:(:;		&(:(:;		t$q	1r   c                 
   |t         j                  _        d| _        d| _        t        j
                  |dd| j                  | j                        xt         j                  _        x| _        }|j                          |j                  j                  d| j                         d|j                  d<   t        j                         x| _
        }t         j                  j                  ||       |gt         j                   _        |S )Ni  i   iX  z<Configure>r   r5   )rR   _ScreenrS   r   r   ScrolledCanvas_canvasr   
adjustScrolls_rootwindowr   r   ScreenscreenTurtleScreenr   	RawTurtlescreens)r   rQ   r   r   s       r)   rj   zDemoWindow.makeGraphFrame   s    
  $8>8M8Mc39A 	A 	Av
t}}=()}%%}}.f$$VV4$*8 
r   c                 r    |t         d<   t        t               | j                  d<   d|z  | j                  d<   y )Nr   rG   zFont size %drF   )r   r   rF   rn   )r   sizes     r)   set_txtsizezDemoWindow.set_txtsize  s0    
!'N		&"04"7r   c                 V    | j                  t        t        d   dz
  t                     yNr   break)r   maxr   MINIMUM_FONT_SIZEr   dummys     r)   r   zDemoWindow.decrease_size
  #    WQZ!^->?@r   c                 V    | j                  t        t        d   dz   t                     yr   )r   minr   MAXIMUM_FONT_SIZEr   s     r)   r   zDemoWindow.increase_size  r   r   c                 p    |j                   dk  t         k(  r| j                         S | j                         S )Nr   )deltar   r   r   )r   r   s     r)   r   zDemoWindow.update_mousewheel  s4     
KK!OV,%%''%%''r   c                    t         rU| j                  j                  |       | j                  j                  |       | j                  j                  |       nx| j                  j                  ||t
        k(  rdnd       | j                  j                  ||t
        k(  rdnd       | j                  j                  ||t
        k(  rdnd       | j                  j                  ||       y )N)r~   z#d00z#fca)r~   r?   )rF   rH   )r   rr   configrt   rv   NORMALrn   )r   startstopcleartxtcolors         r)   r{   zDemoWindow.configGUI  s    NN!!!.MM  t ,NN!!!.NN!!/4VF 
" 
LMM  t.2fnF& 
! 
JNN!!/4VF 
" 
LCE2r   c                 |     t        |      }t               D ]"  }|f fd	}|j                  |dt        |       $ |S )Nc                 (    j                  |        y N)rz   )r(   r   s    r)   loadz)DemoWindow.makeLoadDemoMenu.<locals>.load,  s    

e$r   r   r8   r9   rG   rI   )r^   r*   add_commandmenufont)r   masterr7   r(   r   s   `    r)   rb   zDemoWindow.makeLoadDemoMenu(  sD    F|&(E  
%5A"*D 
 
: )
 r   c                 .    t        |      }|j                  d j                  t               |j                  d j                  t               |j                          t        D ]+  }|f fd	}|j                  t        |      dt        |       - |S )NzDecrease (C-'-'))r8   rI   rG   zIncrease (C-'+')c                 (    j                  |        y r   )r   )r   r   s    r)   resizez'DemoWindow.makeFontMenu.<locals>.resize;  s      &r   r   r   )r^   r   r   r   r   
add_separator
font_sizesstr)r   r   r7   r   r   s   `    r)   rc   zDemoWindow.makeFontMenu2  s    F|14;M;M& 	 	(14;M;M& 	 	(D  
'3t9"*F 
 
< 
 r   c                 z     t        |      }t        D ]%  \  }}||f fd	}|j                  |t        |       ' |S )Nc                 4    t        j                  | |       y r   )r   rQ   )
help_label	help_filer   s     r)   showz%DemoWindow.makeHelpMenu.<locals>.showE  s    $))Z;r   )r8   rG   rI   )r^   help_entriesr   r   )r   r   r7   r   r   r   s   `     r)   rd   zDemoWindow.makeHelpMenuA  sA    F|%1!J	 *i 
<:HdK &2 r   c                 `    | j                   r"| j                  j                          d| _         y y NF)rx   r   r   r   s    r)   
refreshCanvaszDemoWindow.refreshCanvasJ  s%    ::KKDJ r   c                 ,   | j                          dt        j                  _        d|z   }t	        |       t
        j                  |   | _        t        | j                  j                  d      5 }|j                         }d d d        | j                  j                  dd       | j                  j                  d       | j                  j                  |dz          | j!                  t"        t$        t$        dd       t&        | _        y # 1 sw Y   xY w)	NFzturtledemo.rz1.0endz# - a Python turtle graphics examplezPress start buttonred)ru   rR   r   _RUNNING
__import__sysmodulesmoduleopen__file__readrF   deleteinsertrQ   rT   r{   r   r|   READYr~   )r   r   modnamefcharss        r)   rz   zDemoWindow.loadfileO  s    ',$(*7kk'*
$++&&
,FFHE -		&		&		#HHIvx+U	4
 -
,s   .D

Dc                    | j                          d| _        dt        j                  _        | j                  t        t        t        dd       | j                  j                          | j                  j                  d       t        | _        	 | j                  j                         }|dk(  rt        | _        nt         | _        | j                  t         k(  r!| j                  t        t        t        |       y | j                  t        k(  r)d| _        | j                  t        t        t        dd       y y # t        j"                  $ r | j$                  Y y t         | _        d}Y w xY w)	NTzdemo running...rO   standard	EVENTLOOPzstopped!zuse mouse/keys or STOPr   )r   rx   rR   r   r   r{   r|   r   r   r   modeRUNNINGr~   r   mainEVENTDRIVENDONE
TerminatorrQ   ry   )r   results     r)   rq   zDemoWindow.startDemo^  s   
'+$x('	3$

	 [[%%'F$(
!
 ::NN68V!
#
ZZ;
& DMNN8VX3U
< '    	 yy DJF		 s   6D6 6E'
E'&E'c                     | j                          | j                  j                  d       | j                  j	                  d       | j                  t        t        t               y )Nall )cursor)r   r   _deleter   r   r{   r   r|   r   s    r)   ru   zDemoWindow.clearCanvas{  sE    E""%vx2r   c                     | j                   r8| j                          d| _         | j                  t        t        t        dd       dt
        j                  _        y )NFzSTOPPED!r   )ry   ru   r{   r   r|   rR   r   r   r   s    r)   rs   zDemoWindow.stopIt  sA    ==!DMNN68X%u
.',$r   c                 p    dt         j                  _        | j                  j	                          d | _        y r   )rR   r   r   rQ   destroyr   s    r)   rV   zDemoWindow._destroy  s'    ',$			r   r   )r
  blue)__name__
__module____qualname__r   r   ri   rj   r   r   r   r   r{   rb   rc   rd   r   rz   rq   ru   rs   rV    r   r)   r,   r,      s_    IXP8(8
(3


<:3-r   r,   c                  L    t               } | j                  j                          y r   )r,   rQ   mainloop)demos    r)   r  r    s    <DIIr   __main__))r   r   r$   tkinteridlelib.colorizerr   r   idlelib.percolatorr   idlelib.textviewr   rR   
turtledemoabout_turtledemoplatformidlelib.utilr
   pathdirnameabspathr   r&   r   r}   r   r  r  r  r   r   rp   r   r   r   r   r*   r   objectr,   r  r  r  r   r)   <module>r(     s   Tj  	  : ) & 
 2<<7*O
77??277??845		!
	
R 

*  
7
7
  )*FNN+K K\ zF r                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         

   CꨪÜ                   x    d Z ddlmZmZ ddlmZ  G d de      Zd Ze	dk(  r e       Z
 ee
        e        yy)	a        turtle-example-suite:

        tdemo_bytedesign.py

An example adapted from the example-suite
of PythonCard's turtle graphics.

It's based on an article in BYTE magazine
Problem Solving with Logo: Using Turtle
Graphics to Redraw a Design
November 1982, p. 118 - 134

-------------------------------------------

Due to the statement

t.delay(0)

in line 152, which sets the animation delay
to 0, this animation runs in "line per line"
mode as fast as possible.
    )Turtlemainloop)perf_counterc                   B    e Zd Zd Zd Zd Zd Zd Zd Zd Z	d Z
d	 Zy
)Designerc                 n   | j                          t        d      D ]{  }| j                  d|z         | j                          | j	                  | j                         |       | j                          | j
                  d|z         | j                  d       } | j                          | j                  |       | j                  d       | j                  d|z         | j                  d       | j                          | j                  d|z  d|       | j                         j                  d	       y )
N   g)P@H   $   g     8@   .   ga@T)uprangeforwarddownwheelpositionbackwardrightgotocenterpiece	getscreentracer)selfhomePosscaleis       ,/usr/lib/python3.12/turtledemo/bytedesign.pydesignzDesigner.design    s    	qALL'IIKJJt}}.GGIMM%%-(JJrN
  	
			'

2TE\"

3		eUE2%    c                 B   | j                  d       t        d      D ]  }| j                  ||        | j                          | j	                  d       t        d      D ]  }| j                  ||        | j	                  d       t        d      D ][  }| j                          | j                  d       | j
                  d|z         | j                          | j                  d|z         ] | j	                  d       | j                         j                          y )N6      r   r	   r
      )r   r   	pentpiecer   lefttripiecer   r   r   r   update)r   initposr   r   s       r   r   zDesigner.wheel2   s    

2qANN7E* 				"
qAMM'5) 		"
qAIIKJJrNLLe$GGIMM"u*%  	
		"
!r    c                 .   | j                         }| j                          | j                  d|z         | j                  d|z  |       | j	                          | j                  |       | j
                  |       | j                          | j                  d|z         | j                  d|z  |       | j	                          | j                  |       | j
                  |       | j                  d       | j                         j                          y )Ng      @g     ?@r
   )headingr   r   tripolyrr   r   
setheadingtripolylr&   r   r(   )r   r)   r   oldhs       r   r'   zDesigner.tripieceD   s    ||~		

cEk"

dUlE*			'		

cEk"

dUlE*			'		"
!r    c                 &   | j                         }| j                          | j                  d|z         | j                          t	        d      D ]'  }| j                  d|z         | j                  d       ) | j
                  d|z  d|       | j                          | j                  |       | j                  |       | j                  d|z         | j                          t	        d      D ]'  }| j                  d|z         | j                  d       ) | j                  d|z  d|       | j                          | j                  |       | j                  |       | j                  d       | j                         j                          y )N   r	      r
   K   )
r+   r   r   r   r   r   pentrr   r-   pentlr&   r   r(   )r   r)   r   r/   r   s        r   r%   zDesigner.pentpieceU   s&   ||~	R%Z 		qALLe$JJrN  	

2:r5)			'R%Z 		qALLe$JJrN  	

2:r5)			'		"
!r    c                     |d|z  k  ry | j                  |       | j                  |       | j                  |d|z  z
  ||       y N   gRQ?)r   r&   r5   r   sideangr   s       r   r5   zDesigner.pentlm   s@    1u9vT		#

43;'e4r    c                     |d|z  k  ry | j                  |       | j                  |       | j                  |d|z  z
  ||       y r7   )r   r   r4   r9   s       r   r4   zDesigner.pentrs   s@    1u9vT

3

43;'e4r    c                    |d|z  k  ry | j                  |       | j                  d       | j                  |dz         | j                  d       | j                  |dz         | j                  d       | j                  |dz  |       y Nr#   o   g{Gz?g?   g      ?)r   r   r,   r   r:   r   s      r   r,   zDesigner.tripolyry   so    1u9vT

3TD[!

3TCZ 

3

dSj%(r    c                    |d|z  k  ry | j                  |       | j                  d       | j                  |dz         | j                  d       | j                  |dz         | j                  d       | j                  |dz  |       y r>   )r   r&   r.   rA   s      r   r.   zDesigner.tripolyl   so    1u9vT		#TD[!		#TCZ 		#

dSj%(r    c                     | j                  |       | j                  |       |d|z  k  ry | j                  |d|z  z
  ||       y )Ng      @g333333?)r   r&   r   )r   sar   s       r   r   zDesigner.centerpiece   sA    Q1ecEk*Au5r    N)__name__
__module____qualname__r   r   r'   r%   r5   r4   r,   r.   r    r    r   r   r      s/    &$"$"""055))6r    r   c                  L   t               } | j                  d       | j                          | j                         j	                  d       | j                         j                  d       t
               }| j                  | j                         d       t
               }d||z
  z  S )Nr   r8   zruntime: %.2f sec.)	r   speed
hideturtler   delayr   clockr   r   )tatets      r   mainrR      sv    
AGGAJLLNKKMKKM	BHHQZZ\1	B2b5))r    __main__N)__doc__turtler   r   timer   rN   r   rR   rF   msgprintrI   r    r   <module>rY      sH   . $ &s6v s6j	* z
&C	#JJ r                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

   i                   j    d dl  dZd Zd Zd Zd Zd Zd Zd	 Zd
 Z	e
dk(  r e	         e        yy)
    )*P   c                     d| z  d| z
  z  S )N333333@    xs    '/usr/lib/python3.12/turtledemo/chaos.pyfr      s    q5!A#;    c                     d| | dz  z
  z  S )Nr      r   r	   s    r   gr      s    !Q$<r
   c                     d| z  d| z  | z  z
  S )Nr   r   r	   s    r   hr      s    q5Qq=r
   c                 0    t                t        | |       y N)penupgoto)r
   ys     r   jumptor      s    	GT!AYr
   c                 H    t        | |       t                t        ||       y r   )r   pendownr   )x1y1x2y2s       r   liner      s    
2rNIRLr
   c                  J    t        ddt        dz   d       t        dddd       y )Nr   r   皙皙?)r   Nr   r
   r   coosysr%      s"    Q!QD!Sr
   c                     t        |       |}t        d|       t                t        d       t	        t
              D ]$  } | |      }t
        |dz   |       t        d       & y )Nr      r   )pencolorr   r   dotranger$   r   )funstartcolorr
   is        r   plotr/       sN    UO
A
1aLIF
1X

a&QqSA r
   c                  6   t                t        ddt        dz   d       t        d       t	                t                t
        t        dd       t
        t        dd       t
        t        dd	       t        d
      D ]  } t        d| z  dt        dz   d        y)
Ng      r"   r   r#   r   gffffff?bluegreenredd   g      ?zDone!)resetsetworldcoordinatesr$   speed
hideturtler%   r/   r   r   r   r*   )ss    r   mainr:   +   su    	GT1Q3,	!HL
HD&D'D%
3ZCE$!S1 r
   __main__N)turtler$   r   r   r   r   r   r%   r/   r:   __name__mainloopr   r
   r   <module>r?      sP    
	 zFJ r
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

   1Mme                       d Z ddl ddlmZ dZdaddZd Zd Zd	 Zd
 Z	d Z
d Zd
 Zd Z
d Zedk(  r ed        e       Z ee        e        yy)z       turtle-example-suite:

           turtledemo/clock.py

Enhanced clock-program, showing date
and time
  ------------------------------------
   Press STOP to exit the program!
  ------------------------------------
    )*)datetime)TkFixedFont   boldNc                 n    t                t        |       t        |        t        |       t	                y )N)penuprightforwardleftpendown)distanzwinkels     '/usr/lib/python3.12/turtledemo/clock.pyjumpr      s"    	G	&MGLI    c                     t        | dz         t        d       t        |dz         t        d       t        |       t        d       t        |       t        d       t        |dz         y )Ngffffff?Z   g       @x   )fdrtlt)laengespitzes     r   handr      sM    vd{OrFvczNsGvJsGvJsGvczNr   c                     t                t        | dz         t                t        ||       t	                t               }t
        | |       y )Ng333333?)resetr   
begin_polyr   end_polyget_polyregister_shape)namer   r   	hand_forms       r   make_hand_shaper$   $   s:    	G&LJ
I4#r   c                     t                t        d       t        d      D ]R  }t        |        |dz  dk(  rt	        d       t        |  dz
         nt        d       t        |         t
        d       T y )N   <      r            )r   pensizeranger   r   dotr   )radiusis     r   	clockfacer1   -   sZ    	GAJ
2YVq5A:rF&F&M
1 r   c                     t         j                          t        j                         } | j                  at         j
                          t         j                  d       t         j                  t        |       dt               t         j                  d       t         j                  t        |       dt               t         j                  d       y )NA   )distancecenter)alignfont   U   )
writerclearr   nowdaycurrent_dayhomer   write	wochentagdtfontbackdatum)r<   s    r   display_date_timerE   :   s~    
LLN
,,.C''K
KKM
NNBN
LL3xfL=
KKK
LLs8&L9
NNBNr   c                     t        d       t        ddd       t        ddd       t        ddd       t        d	       t               at        j                  d       t        j
                  d
d       t               at        j                  d       t        j
                  dd
       t               at        j                  d       t        j
                  dd       t        t        t        fD ]7  } | j                  d       | j                  ddd       | j                  d       9 t                t               a
t        j                          t        j                          t        j                  d       t!                y )Nlogosecond_hand}   r)   minute_hands   	hour_handr      gray20gray80blue1red1blue3red3user   r*   r   r9   )moder$   r1   TurtlerH   shapecolorrJ   rL   
resizemode	shapesizespeedhtr:   pubkrE   )r   s    r   setupr`   F   s   LM3+MC,KR(
cN(Km$h)(Km$gv&I
OOK 
OOGV$[)3q!Q

1
 4 D
XF
IIK
IIK
IIbMr   c                 0    g d}|| j                            S )N)MondayTuesday	WednesdayThursdayFridaySaturdaySunday)weekday)trA   s     r   rA   rA   a   s    4IQYY[!!r   c                 n    g d}| j                   }|| j                  dz
     }| j                  }d|||fz  S )N)zJan.zFeb.zMar.zApr.MayJuneJulyzAug.zSep.zOct.zNov.zDec.rU   z%s %d %d)yearmonthr=   )zmonatjmrj   s        r   rD   rD   f   s>    
=E	A
aggkA	AAq	!!r   c                     t        j                         } | j                  | j                  dz  z   }| j                  |dz  z   }| j
                  |dz  z   }	 t
        d       t        j                  d|z         t        j                  d|z         t        j                  d|z         | j                  t        k7  r
t                t
        d       t        t        d       y # t         $ r Y y w xY w)Ngư>g      N@Fr+      Td   )r   todaysecondmicrosecondminutehourtracerrH   
setheadingrJ   rL   r=   r>   rE   ontimertick
Terminator)rj   sekunder{   stundes       r   r   r   n   s    Ahhx//G
XX
$F
VVfTk
!F

u
qy)qx(RY'55Ktc 

s   BC" "	C.-C.c                  X    t        d       t                t        d       t                y)NFT	EVENTLOOP)r}   r`   r    r   r   mainr      s    
5M	G
4LFr   __main__rG   )r   )__doc__turtler   rB   r>   r   r   r$   r1   rE   r`   rA   rD   r   r   __name__rV   msgprintmainloopr   r   r   <module>r      sw   	  	"	$
 6"
"
" zL
&C	#JJ	 r                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

   :-oq.                   r    d dl mZmZmZ  G d de      Zd Zd Zedk(  r e       Z e	e        e        yy)    )ScreenTurtlemainloopc                       e Zd Zd Zd Zy)ColorTurtlec                    t        j                  |        | j                  d       | j                  d       | j	                  ddd       | j                  d       g d| _        || _        || j                  |<   | j                  | j                         | j                  d       | j                  d       | j                          | j                  |d       | j                          | j                  d	       | j                          | j                  |       | j                  d
       | j!                  | j"                         y )Nturtleuser      
   )r   r   r   r   Z      gray25)r   __init__shape
resizemode	shapesizepensize_colorxcolorspeedleftpugotopdsetypencolorondragshiftselfr   ys      ,/usr/lib/python3.12/turtledemo/colormixer.pyr   zColorTurtle.__init__   s    

8q1RA

4;;

1
		"
			!A			!			!

hDJJ    c           	          | j                  t        dt        |d                   | j                         | j                  | j
                  <   | j
                  | j                         t                y )Nr   r   )r   maxminycorr   r   	fillcolor
setbgcolorr"   s      r%   r!   zColorTurtle.shift   sG    		#aAa/""iikDFFt{{#r&   N)__name__
__module____qualname__r   r!    r&   r%   r   r      s     *r&   r   c                      t         j                  t        j                         t        j                         t
        j                                y )N)screenbgcolorredr*   greenbluer0   r&   r%   r,   r,   "   s$    
NN388:uzz|TYY[9r&   c                  n   t               at        j                  d       t        j                  dddd       t	        dd      at	        dd      at	        dd      at                t               } | j                          | j                          | j                  dd	       | j                  d
dd
       y)Nr   g333333ӿr   g?g      ?r      gffffff?zDRAG!center)Arial   )bolditalic)alignfont	EVENTLOOP)r   r2   delaysetworldcoordinatesr   r4   r5   r6   r,   r   htr   r   write)writers    r%   mainrG   %   s    
XF
LLO
r4C0
a
C2Eq"DL
XF
IIK
IIK
KK$
LLx-KLLr&   __main__N)
r	   r   r   r   r   r,   rG   r-   msgprintr0   r&   r%   <module>rK      sE    , +& ::$ z
&C	#JJ r&                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             

   M&uj                       d Z ddlmZmZmZmZ ddlmZ ddlm	Z
 d Zd Zd Z
ddZd	 Zd
 Zd Zd Zd
 Zedk(  r e         e        yy)a4       turtlegraphics-example-suite:

             tdemo_forest.py

Displays a 'forest' of 3 breadth-first-trees
similar to the one in tree.
For further remarks see tree.py

This example is a 'breadth-first'-rewrite of
a Logo program written by Erich Neuwirth. See
http://homepage.univie.ac.at/erich.neuwirth/
    )Turtle	colormodetracermainloop	randrange)perf_counterc                 "    t        |  | dz         S )N   r   )ns    (/usr/lib/python3.12/turtledemo/forest.py	symRandomr      s    aR!    c           
      r    | D cg c]$  \  }}|t        |      z   |dt        |      z  z  f& c}}S c c}}w )Ng)\(?)r   )
branchlist	angledistsizedistangle
sizefactors        r
   	randomizer      sO     /9;.8*
 Ii((y2224.8; ; ;s   )3c                     t        |      D ]3  }| j                  t        |             | j                  d|z  |z         5 y )Ng      ?)rangeleftr   forward)tdistancepartsr   is        r
   randomfdr      s6    
5\	y#$			C(NE)+ r   c           	   #   J  K   |dkD  rg }g }t        t        | |            D ]  \  }	}
|	j                  ||z         |	j                  ddd|z  z
  t	        d      z   z
  dd|z  z
  t	        d      z   d       |	j                          t
        |	|||       d |
D ]b  \  }}|	j                  |       |j                  |	j                                |j                  t        |
||             |	j                  |       d  t        ||z  |dz
  ||||      D ]  }
d   y y w)Nr               r   )
listzippensizepencolorr   pendownr   r   appendcloner   righttree)tlistsizelevelwidthfactorbranchlistsr   r   lstbrsr   r   r   r   xs                 r
   r-   r-      s     
qy!#eK"89MAz
IItk)+
JJsR%Z/)B-?@b5j(9R=8
 
IIKQeY0G%/!zu


1779%

9ZHEF	 &0 : c4
?E!G[#+AJ+! s   D!D#c                    t        d       | j                          | j                  d       | j                          | j	                  d       | j                          | j
                  ||       | j                          y )Nr!   r   Z   )r   resetspeed
hideturtler   penupsetposr)   )r   r5   ys      r
   startr>   7   sP    
cNGGIGGAJLLNFF2JGGIHHQqMIIKr   c                 f    |j                          t        |dd       t        |gd| dg dg      }|S )N   i0P   皙?)-   gGz?)r   ?gQ?r:   r>   r-   r0   penr   s      r
   doit1rK   A   s5    NN	#r4seR&I%JLAHr   c                 f    |j                          t        |dd       t        |gd| dddgg      }|S )Niyi~x   rB   rC   rF   rH   rI   s      r
   doit2rN   G   s9    NN	#tTseS%J'@&ACAHr   c                 f    |j                          t        |dd       t        |gd| dg dg      }|S )N   id   rB   ))rD   gffffff?)r   g
ףp=
?)rG   rE   rH   rI   s      r
   doit3rR   M   s5    NN	#sCseS%'I&JLAHr   c                     t               } | j                          t        dd       t        dt        d            }t	        dt        d            }t        dt        d            }t
               }	 d}|||fD ]  }	 |j                           |dk(  rn$t        dd	       t
               }d
||z
  z  S #  |dz
  }Y DxY w)NK   r      r   )undobuffersize         
   zruntime: %.2f sec.)r   htr   rK   rN   rR   clock__next__)pusr   adonebs          r
   mainrd   T   s    ADDF
2aL
aq)*A
aq)*A
aq)*A
A
1QA


 
 19  1RL
A1Q3''
	s   ?B66B?__main__N)rZ   rX   )__doc__turtler   r   r   r   randomr   timer	   r\   r   r   r   r-   r>   rK   rN   rR   rd   __name__ r   r
   <module>rl      s^    7 6  &;
,
0


(, zFJ r                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

   	}Km                   v    d Z ddl ddlmZmZ  G d de      Zd Ze	dk(  r e       Z
 ee
        e        yy)	a&        turtle-example-suite:

        tdemo_fractalCurves.py

This program draws two fractal-curve-designs:
(1) A hilbert curve (in a box)
(2) A combination of Koch-curves.

The CurvesTurtle class and the fractal-curve-
methods are taken from the PythonCard example
scripts for turtle-graphics.
    )*)sleepperf_counterc                       e Zd Zd Zd Zd Zy)CurvesTurtlec                    |dk(  ry | j                  |dz         | j                  ||dz
  |        | j                  |       | j                  |dz         | j                  ||dz
  |       | j                  |       | j                  ||dz
  |       | j                  |dz         | j                  |       | j                  ||dz
  |        | j                  |dz         y )Nr   Z      )lefthilbertforwardright)selfsizelevelparitys       //usr/lib/python3.12/turtledemo/fractalcurves.pyr   zCurvesTurtle.hilbert   s    A:		&2+T519vg.T

6B;T519f-TT519f-

6B;TT519vg. 	
		&2+    c                    dd l }d|z  |j                  |j                  |z        z  }| j                          | j	                  |       | j                          | j
                  dd|dz
  z  |z  z
         t        |      D ])  }| j                  |||       | j
                  d|z         + | j                  dd|dz
  z  |z  z
         | j                          | j                  |       | j                          y )Nr         r	   ih  )mathsinpipufdpdrtrangefractalltbk)r   nradlevdirr   edgeis           r   
fractalgonzCurvesTurtle.fractalgon/   s     3w$''A+..		rQU|a'()qALLsC(GGC!G  	
rQU|a'()		r   c                 r   |dk  r| j                  |       y | j                  |dz  |dz
  |       | j                  d|z         | j                  |dz  |dz
  |       | j                  d|z         | j                  |dz  |dz
  |       | j                  d|z         | j                  |dz  |dz
  |       y )Nr
      <   x   )r   r    r!   r   )r   distdepthr&   s       r   r    zCurvesTurtle.fractalB   s    19GGDMTAXuqy#.STAXuqy#.c	TAXuqy#.STAXuqy#.r   N)__name__
__module____qualname__r   r)   r     r   r   r   r      s    
2&
/r   r   c                     t               } | j                          | j                  d       | j                          | j	                         j                  dd       | j
                          d}| j                  d|z  d|z         | j                          t               }| j                  d       | j                          | j                  |       | j                  |dd       | j                  |       t        d      D ]-  }| j                  d       | j                  |d	|d
z  z   z         / | j
                          t        d
      D ]$  }| j                  |       | j!                  d       & | j                          t        d      D ]-  }| j                  |d|d
z  z   z         | j!                  d       / | j#                          t               }d
||z
  z  }t%        d       | j                          | j                  d       | j                          | j	                         j                  dd       t               }| j'                  dd       | j                          | j)                  dddd       | j#                          | j                          | j'                  d       | j)                  dddd       | j#                          t               }|d||z
  z  z
  }|S )Nr   r
      iiredr+   r	   @   r      B   zHilbert: %.2fsec. blackblue      zKoch: %.2fsec.)r   resetspeedht	getscreentracerr   setposr   clock	fillcolor
begin_fillr   r   r   r!   r   end_fillr   colorr)   )ftr   tar(   tbress         r   mainrN   N   s+   	BHHJHHQKEEGLLN!AEEGDIIc$hD!EEGwBLLMMOEE$KJJtQ EE$K
1X
b	
dBqsFm  EEG
1X
d
b	  EEG
1X
dBqsFm
b	  KKMwB2b5)C	!HHHJHHQKEEGLLN!AwBHHWfMMOMM!S!QKKMMMOHHUOMM!S!R KKMwB2&&CJr   __main__N)
__doc__turtletimer   r   rE   Penr   rN   r0   msgprintmainloopr3   r   r   <module>rW      sG     -;/3 ;/z7r 

&C	#JJ r                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     

   pƺg                   \    d Z ddl d Zd Zd Zedk(  r e       Z ee        e        yy)a         turtle-example-suite:

        xtx_lindenmayer_indian.py

Each morning women in Tamil Nadu, in southern
India, place designs, created by using rice
flour and known as kolam on the thresholds of
their homes.

These can be described by Lindenmayer systems,
which can easily be implemented with turtle
graphics and Python.

Two examples are shown here:
(1) the snake kolam
(2) anklets of Krishna

Taken from Marcia Ascher: Mathematics
Elsewhere, An Exploration of Ideas Across
Cultures

    )*c                 f    t        |      D ]"  }d}| D ]  }||j                  ||      z   } |} $ | S )N )rangeget)seqreplacementRulesninewseqelements         -/usr/lib/python3.12/turtledemo/lindenmayer.pyreplacer      sC    
1XG.2277CCF 	 
 J    c                 v    | D ]
  }	  ||            y # t         $ r 	 t        ||   |       n#  Y nxY wY 4w xY w)N)	TypeErrordraw)commandsrulesbs      r   r   r   &   sJ    
	E!HJ   	
U1Xu%
		s   
	8.8288c                     d } d }d }| ||dd}ddi}d}t        ||d	      }t                t        d	       t        d
d       t	                t                t
        d       t                t        ||       dd
l	m
}  |d	       d }d }	d }
||	|
d}ddd}d}
t                t        d       t        d	d       t	                t        d       t        |
|d	      }t        ||       t        d
       y)Nc                      t        d       y N-   )right r   r   rzmain.<locals>.r7   s	    
b	r   c                      t        d       y r   )leftr   r   r   lzmain.<locals>.l:   s	    Rr   c                      t        d       y )Ng      @)forwardr   r   r   fzmain.<locals>.f=   s	    r   zf+f+f--f--f+f+f)-+r#   r   r   zb+f+b--f--b+f+bz
b--f--b--f      r      )sleepc                  2    t        d       t        dd       y )Nred
   Z   )colorcircler   r   r   Azmain.<locals>.AV   s    
er"
r   c                      ddl m}  t        d       d | d      z  }t        |       t	        |d       t        |       y )Nr   )sqrtblack      i  )mathr2   r.   r"   r/   )r2   r    s     r   Bzmain.<locals>.BZ   s0    
g
d1gI
q#
r   c                  0    t        d       t        d       y )Ngreenr,   )r.   r"   r   r   r   Fzmain.<locals>.Fb   s    
gr   )ar   r#   afbfa	afbfbfbfa)r;   r   fbfbfbfbr   zDone!)r   resetspeedtracerhtupbackwarddownr   timer)   r   )r   r    r#   snake_rulessnake_replacementRulessnake_startdrawingr)   r0   r7   r:   
krishna_ruleskrishna_replacementRules
krishna_starts                 r   mainrN   1   s     aQ,=>K!#45Kk#91=G	G	!H
1QKDDSMF+	!H q)M&-[BM	G	!H
1QKDHm%=qAG- 
1Ir   __main__N)	__doc__turtler   r   rN   __name__msgprintmainloopr   r   r   <module>rV      sB   4 AF Z
&C	#JJ r                                                                                                                                                                                                                                                                                                                                                

   gJG^_                       d Z ddl  G d de      Z G d de      Zd Zd Zd	 Ze	d
k(  r e       Z
 ee
        e        yy)a         turtle-example-suite:

         tdemo_minimal_hanoi.py

A minimal 'Towers of Hanoi' animation:
A tower of 6 discs is transferred from the
left to the right peg.

An imho quite elegant and concise
implementation using a tower class, which
is derived from the built-in type list.

Discs are turtles with shape "square", but
stretched to rectangles by shapesize()
 ---------------------------------------
       To exit press STOP button
 ---------------------------------------
    )*c                       e Zd Zd Zy)Discc                     t         j                  | dd       | j                          | j                  d|dz  d       | j	                  |dz  dd|dz  z
         | j                          y )	NsquareF)shapevisibleg      ?   g      @r      )Turtle__init__pu	shapesize	fillcolorst)selfns     //usr/lib/python3.12/turtledemo/minimal_hanoi.pyr
   z
Disc.__init__   sV    He<	sAcE1%qtQ!B$'	    N)__name__
__module____qualname__r
    r   r   r   r      s    r   r   c                   "    e Zd ZdZd Zd Zd Zy)Towerz-Hanoi tower, a subclass of built-in type listc                     || _         y)z-create an empty tower. x is x-position of pegN)x)r   r   s     r   r
   zTower.__init__    s	    r   c                     |j                  | j                         |j                  ddt        |       z  z          | j	                  |       y )Nij"   )setxr   setylenappendr   ds     r   pushz
Tower.push#   s5    	tvv	tBs4yL !Ar   c                 R    t         j                  |       }|j                  d       |S )N   )listpopr!   r$   s     r   r*   z	Tower.pop'   s    HHTN	sr   N)r   r   r   __doc__r
   r&   r*   r   r   r   r   r      s    3r   r   c                     | dkD  rBt        | dz
  |||       |j                  |j                                t        | dz
  |||       y y )Nr   r   )hanoir&   r*   )r   from_with_to_s       r   r-   r-   ,   sD    1u
ac5#u%
ac5%% 
r   c                      t        d d       t                	 t        dt        t        t
               t
        ddd       y # t        $ r Y y w xY w)Nspace   zpress STOP button to exitcenterCourier   boldalignfont)onkeyclearr-   t1t2t3write
Terminatorr   r   r   playrC   2   sG    	$w	G

aR
)#:	< 

s   (A 	A
A
c                  6   t                t                t        dd       t        d      at        d      at        d      at        ddd      D ]   } t        j                  t        |              " t        ddd	
       t        t        d       t                y)
Nr   ii   r3   zpress spacebar to start gamer4   r5   r9   r2   	EVENTLOOP)htpenupgotor   r>   r?   r@   ranger&   r   rA   r<   rC   listen)is    r   mainrN   <   su    D%'44=	tB	qB	sB
1Qr]
Q  

(68	$
Hr   __main__N)
r+   turtler   r   r)   r   r-   rC   rN   r   msgprintmainloopr   r   r   <module>rT      sX   $ 6 D &
  Z
&C	#JJ r                                                                                                                            

   N                   D   d Z ddlZddlZddlZdZdZdZdZedz  Zeedz  d	z  edz  d
z  z   z  Z	dZ
dZd
Zd Z
d Zd Z G d de      Z G d dej$                        Z G d de      Z G d de      Z G d de      Zd Zedk(  r e         ej2                          yy)z      turtle-example-suite:

            tdemo_nim.py

Play nim against the computer. The player
who takes the last stick is the winner.

Implements the model-view-controller
design pattern.
    Ni  i                    )?   r	   r   )      r   )r   r   r
   c                  >    t        j                  t        t              S N)randomrandint	MINSTICKS	MAXSTICKS     %/usr/lib/python3.12/turtledemo/nim.py	randomrowr      s    >>)Y//r   c                     | d   | d   z  | d   z  }|dk(  rt        |       S t        d      D ]  }| |   |z  }|| |   k  s||f}|c S  y )Nr      r      )
randommoverange)statexoredzsmoves        r   computerzugr    !   sd    !HuQx%(*Ez%  
1X!Hua=q6DK	 r   c                     t        |       }	 t        j                  dd      }| |   |dkD  kD  rn#t        j                  |dkD  | |   dz
        }||fS )Nr   r   r   )maxr   r   )r   mr   rands       r   r   r   +   s]    E
A
NN1Q8q1u  >>!a%q!,Dd7Nr   c                   *    e Zd Zd Zd Zd Zd Zd Zy)NimModelc                     || _         y r
   )game)selfr(   s     r   __init__zNimModel.__init__6   s	    	r   c                 X   | j                   j                  t        j                  t        j                  fvry t               t               t               g| _        d| _        d | _        | j                   j                  j                          t        j                  | j                   _        y )Nr   )r(   r   NimCREATEDOVERr   sticksplayerwinnerviewsetupRUNNINGr)   s    r   r3   zNimModel.setup9   sg    99??3;;"99 {IK=		++		r   c                    | j                   |   }|| j                   |<   | j                  j                  j                  |||| j                         | j                         rUt        j                  | j                  _        | j                  | _	        | j                  j                  j                          y | j                  dk(  r9d| _        t        | j                         \  }}| j                  ||       d| _        y y )Nr   r   )
r/   r(   r2   notify_mover0   	game_overr,   r.   r   r1   notify_overr    r   )r)   rowcol	maxspaltes       r   r   z
NimModel.moveB   s    KK$	C		""3YD>>!hhDIIO++DKIINN&&(
[[A
DK"4;;/HCIIc3DK	 r   c                 $    | j                   g dk(  S )N)r   r   r   )r/   r5   s    r   r8   zNimModel.game_overP   s    {{i''r   c                 N    | j                   |   |k  ry | j                  ||       y r
   )r/   r   r)   r:   r;   s      r   r7   zNimModel.notify_moveS   s$    ;;ss"		#sr   N)__name__
__module____qualname__r*   r3   r   r8   r7   r   r   r   r&   r&   5   s    &(r   r&   c                       e Zd Zd Zd Zd Zy)Stickc                    t         j                  j                  | d       || _        || _        || _        | j
                  ||      \  }}| j                  d       | j                  t        dz  t        dz         | j                  d       | j                          | j                  ||       | j                  d       | j                          y )NFvisiblesquareg      $@g      4@r   white)turtleTurtler*   r:   r;   r(   coordsshape	shapesizeHUNITWUNITspeedpugotocolor
showturtle)r)   r:   r;   r(   xys         r   r*   zStick.__init__Z   s    

tU3	{{3$1

8uTz5:.

1
			!A

7r   c                     t        |d      \  }}dd|z  z   d|z  z   t        z  }dd|z  z   t        z  }|t        dz  z
  t        dz  z   t        dz  |z
  t        dz  z
  fS )Nr   r   r   r   )divmodrP   rO   SCREENWIDTHSCREENHEIGHT)r)   r:   r;   packet	remainderrV   rW   s          r   rL   zStick.coordsh   sq    "3N	
f_q9}
,5
S[E!;!##eqj0,!2Ca2G%ST*2TTTr   c                     | j                   j                  t        j                  k7  ry | j                   j                  j                  | j                  | j                         y r
   )r(   r   r,   r4   
controllerr7   r:   r;   )r)   rV   rW   s      r   makemovezStick.makemoven   s;    99??ckk)		((488<r   N)r@   rA   rB   r*   rL   r`   r   r   r   rD   rD   Y   s    U=r   rD   c                   2    e Zd Zd ZddZd Zd Zd Zd Zy)	NimViewc                 ~   || _         |j                  | _        |j                  | _        | j                  j                  d       | j                  j	                  d       | j                  j                  d       t
        j                  d      | _        | j                  j                          | j                  j                  d       i | _        t        d      D ]2  }t        t              D ]  }t        |||      | j                  ||f<     4 | j                  d       | j                  j	                  d       y )	Nr
   F)   rd   r
   rF   r   r   z... a moment please ...T)r(   screenmodel	colormodetracerbgcolorrJ   rK   writerrR   rQ   r/   r   r   rD   display)r)   r(   r:   r;   s       r   r*   zNimView.__init__u   s    	kkZZ
c"5!O,mmE2!8CY'*/S$*?S#J' (  	
./4 r   Nc                 (   | j                   j                  d       | j                  j                          |`| j                  j	                  dt
         dz  dz          | j                  j
                  d       | j                  j                  |dd       | j                  j	                  dt
         dz  d	z          | j                  j
                  d
       | j                  j                  |dd       | j                   j                  d       y )
NFr   r   0   redcenter)Courier   bold)alignfont   black)rp      rr   T)re   rh   rj   clearrS   r[   pencolorwrite)r)   msg1msg2s      r   rk   zNimView.display   s    5!KKQ,! 3b 89KK  'KKd(9NOlNa/"45W%$h5JK4 r   c                     | j                   j                  d       t        d      D ]M  }t        | j                  j                  |         D ]&  }| j                  ||f   j                  t               ( O t        d      D ]N  }t        | j                  j                  |   t              D ]"  }| j                  ||f   j                  d       $ P | j                  d       | j                   j                  d       y )NFr   rI   *Your turn! Click leftmost stick to remove.T)	re   rh   r   rf   r/   rT   SCOLORr   rk   r?   s      r   r3   z
NimView.setup   s    5!8CTZZ..s34S#J'--f5 5  8CTZZ..s3Y?S#J'--g6 @  	
AB4 r   c                    |dk(  r8t         }t        ||      D ]"  }| j                  ||f   j                  |       $ y | j	                  d       t        j                  d       | j	                  d       t        }t        |dz
  |dz
  d      D ]7  }t        j                  d       | j                  ||f   j                  |       9 | j	                  d       y )	Nr   z ... thinking ...         g      ?z ... thinking ... aaah ...r   g?r~   )HCOLORr   r/   rT   rk   timesleepCOLOR)r)   r:   r;   r<   r0   farber   s          r   r7   zNimView.notify_move   s    Q;E3	*S!H%++E2 + 
LL56JJsOLL56E9Q;Ar2

3S!H%++E2 3 
LLEFr   c                 x    | j                   j                  j                  dk(  rd}nd}| j                  d|       y )Nr   zCongrats. You're the winner!!!z"Sorry, the computer is the winner.z2To play again press space bar. To leave press ESC.)r(   rf   r1   rk   )r)   r|   s     r   r9   zNimView.notify_over   s1    99??!!Q&3D7DI4Pr   c                     | j                   j                  t        j                  k(  r| j                  j                          y y r
   )r(   r   r,   r.   re   rx   r5   s    r   rx   z
NimView.clear   s+    99??chh&KK 'r   r
   )	r@   rA   rB   r*   rk   r3   r7   r9   rx   r   r   r   rb   rb   t   s"    !"
!	!
GQ r   rb   c                       e Zd Zd Zd Zy)
NimControllerc                 l   || _         |j                  j                  | _        d| _        | j                  j	                         D ]  }|j                  |j                          | j                   j                  j                  | j                   j                  j                  d       | j                   j                  j                  | j                   j                  j                  d       | j                   j                  j                  d       | j                   j                  j                          y )NFspaceEscapezPress space bar to start game)r(   r2   r/   BUSYvaluesonclickr`   re   onkeyrf   r3   rx   rk   listen)r)   r(   sticks      r   r*   zNimController.__init__   s    	ii&&	[['')EMM%..) *		tyy44g>		tyy~~33X>		>?		!r   c                     | j                   ry d| _         | j                  j                  j                  ||       d| _         y )NTF)r   r(   rf   r7   r?   s      r   r7   zNimController.notify_move   s2    99			##C-	r   N)r@   rA   rB   r*   r7   r   r   r   r   r      s    	"r   r   c                       e Zd ZdZdZdZd Zy)r,   r   r   r   c                     t         j                  | _        || _        t	        |       | _        t
        |       | _        t        |       | _	        y r
   )
r,   r-   r   re   r&   rf   rb   r2   r   r_   )r)   re   s     r   r*   zNim.__init__   s6    [[
d^
DM	'-r   N)r@   rA   rB   r-   r4   r.   r*   r   r   r   r,   r,      s    GGD.r   r,   c                      t        j                         } | j                  d       | j                  t        t
               t
        |       }y)Nstandard	EVENTLOOP)rJ   Screenmoder3   rZ   r[   r,   )
mainscreennims     r   mainr      s5    JOOJ[,/

j/Cr   __main__)__doc__rJ   r   r   rZ   r[   r   r   rO   rP   r   r   r   r   r    r   objectr&   rK   rD   rb   r   r,   r   r@   mainloopr   r   r   <module>r      s   	  
 
		a2-Q!0CCD		0!v !H=FMM =6A f A HF *	.& 	. zFFOO r                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          

   
pEIw                   `    d Z ddl ddZddZd Zedk(  r e       Z ee        e        yy)	ap         turtle-example-suite:

            tdemo_paint.py

A simple  event-driven paint program

- left mouse button moves turtle
- middle mouse button changes color
- right mouse button toggles between pen up
(no line drawn when the turtle moves) and
pen down (line is drawn). If pen up follows
at least two pen-down moves, the polygon that
includes the starting point is filled.
 -------------------------------------------
 Play around by clicking into the canvas
 using all three mouse buttons.
 -------------------------------------------
          To exit press STOP button
 -------------------------------------------
    )*c                 p    t               d   rt                t                y t                t	                y )Npendown)penend_fillupdown
begin_fillxys     '/usr/lib/python3.12/turtledemo/paint.pyswitchupdownr      s     
uY

    c                 N    t         dd  t         d d z   a t        t         d          y )N   r   )colorscolorr   s     r   changecolorr       s$    
ABZr

"F	&)r   c                      t        d       t        d       t        d       t        d       g dat        t        d          t
                t        t        d       t        t        d       t        t        d       y	)
Ncircleuserg      ?   )redgreenblueyellowr   r      	EVENTLOOP)
shape
resizemode	shapesizewidthr   r   r   
onscreenclickgotor    r   r   mainr'   %   sV    	(Ov
bM	!H-F	&)N$q+a ,q!r   __main__N)r   r   )	__doc__turtler   r   r'   __name__msgprintmainloopr&   r   r   <module>r/      s@   ( 
 z
&C	#JJ r                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            

   *Ӓ                   @    d Z ddl d Zedk(  r e         e        yy)z       turtle-example-suite:

              tdemo_peace.py

A simple drawing suitable as a beginner's
programming example. Aside from the
peacecolors assignment and the for loop,
it only uses turtle commands.
    )*c                     d} t                t                t                t        dd       t	        d       | D ]X  }t        |       t
                t        d       t                t        d       t        d       t        d       t        d       Z t	        d       t        d	       t        d
d       t
                t        d       t        d       t        d
       t                t        d       t        d       t        d       t
                t        d       t                t        d       t        d       t
                t        d       t                t        d
d       y)N)red3orangeyellow	seagreen4orchid4
royalblue1dodgerblue4ii=F   i  Z   B      whiter   iV   iT     -   i,  zDone!)resetScreenupgotowidthcolordownforwardbackwardleftrightcircle)peacecolorspcolors     '/usr/lib/python3.12/turtledemo/peace.pymainr#      s    0K 
G
HDdO	"I
f


R
b	  
"I	'N4LF
3KHCLDICL	"IFCLDSMHFCLD3K    __main__N)__doc__turtler#   __name__mainloop r$   r"   <module>r+      s.    +Z zFJ r$                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  

   
o+                       d Z ddl ddlmZmZ ddlmZmZ dZ	d edez  dz        z  Z
d	 Zd
 Zd Z
d Zdd
Zd Zd Zd Zd ZddeddfdZefdZd Zedk(  r e       Z e        yy)a         xturtle-example-suite:

          xtx_kites_and_darts.py

Constructs two aperiodic penrose-tilings,
consisting of kites and darts, by the method
of inflation in six steps.

Starting points are the patterns "sun"
consisting of five kites and "star"
consisting of five darts.

For more information see:
 http://en.wikipedia.org/wiki/Penrose_tiling
 -------------------------------------------
    )*)cospi)perf_countersleepgP/7?      
   c                     t         | z  }t        d       t        |        t        d       t        |       t        d       t        |       t        d       t        |        t        d       y )N$   l      fltfdrtlfls     )/usr/lib/python3.12/turtledemo/penrose.pykiter      J    	
QBrFqEsGrFrFrFsGqEsG    c                     t         | z  }t        d       t        |        t        d       t        |       t        d       t        |       t        d       t        |        t        d       y )Nr   r   r   r   s     r   dartr   %   r   r   c                    |dk(  rEt               \  }}t        t                     t        |d      t        |d      }}}dt        |||f<   y t
        | z  }t
        d       t        ||dz
         t        |        t        d       t        ||dz
         t
        d       t        | t        z         t        d       t        ||dz
         t
        d       t        |        t        d	       t        ||dz
         t
        d       y )
Nr   r	   Tr      r            )posintheadingroundtiledictr   r   inflatedartr   r   inflatekitedr   npxpyhxyr   s           r   r(   r(   1   s    AvBgi.%1+uR{a1 !Aa	
QBrFAaCqEsGAaCrFqsGsGAaCrFqEsGAaCrFr   c                    |dk(  rEt               \  }}t        t                     t        |d      t        |d      }}}dt        |||f<   y t
        | z  }t
        ||dz
         t        d       t        |        t        d       t        ||dz
         t        d       t        | t        z         t        d       t        ||dz
         t        |        t        d	       y )
Nr   r	   Fr   r   r!   6   ~   r   )r"   r#   r$   r%   r&   r   r(   r   r   r   r'   r)   r*   s           r   r'   r'   G   s    AvBgi.%1+uR{a1!!Aa	
QBAaCrFqEsGAaCrFqsGsGAaCqEsGr   c                 *   t                | t        |z  z  } t        | dz  | dz  |       t        D ]a  }|\  }}}t	        ||       t        |       t        |   rt
        d       t        dd       nt
        d       t        dd       t                c y )Ng      Y@r   black)r         ?r   r   )r6   r   r   )	clearr   	shapesizer&   setpos
setheadingshapecolorstamp)r   r+   thkr.   r/   r0   s          r   drawr@   Z   s{    	G	AqDA
agqw#
1aq!1
A;&M'<(&M'<(
 r   c                 R    t        d      D ]  }t        | |       t        d        y N   H   )ranger(   r   r   r+   is      r   sunrH   j   !    
1XAq
2 r   c                 R    t        d      D ]  }t        | |       t        d        y rB   )rE   r'   r   rF   s      r   starrK   o   rI   r   c                      t        d       t                t        d       t                t	        dt                      t                t
        d       t                t	        dt                      t        d       y )Nr   d   r   r   r   )tracer
begin_polyr   end_polyregister_shapeget_polyr    r   r   
makeshapesrT   t   sJ    
1ILIJ68:&LIJ68:&
1Ir   c                  j    t                t                t                t                t	        d       y )Nuser)resethtpurT   
resizemoderS   r   r   startr[      s    	GDDLvr         )r   r   c                 d   t        |       t        d       i at        d        || |       t	        | ||       t        d       t        t        D cg c]  }t        |   s
| c}      }t        t        D cg c]  }t        |   r
| c}      }t
        d||||z   fz         y c c}w c c}w )Nr   r   z"%d kites and %d darts = %d pieces.)gotor:   r&   rN   r@   lenprint)r   r+   funstartposr>   r/   nknds           r   testrf      s    NqMH
1I1IArN
1I	
1AXa[a
1	2B	
5A!a
5	6B	
."b"R%
@A 2
5s   B(!B(9B-B-c                     t                t        d      D ]<  }t               }t        d||        t               }||z
  }|dk  s/t	        d|z
         > y )N   i,  r   )r[   rE   clockrf   r   )rb   rG   abts        r   demorm      sJ    	G
1XGS!SG
Eq5!a%L
 r   c                     t        d       t        ddd       t        t               t	        d       t        t
               t
        d       t        dd       t
        ddd       t        d	d
d       t        d
dd       y)Nlogog333333?r   r   r5   i8gffffff?r   zPlease wait...center)zArial Blackr   bold)alignfontiX  rh   )F   u   )rc   Done)
modebgcolorrm   rH   r   rK   pencolorr_   writerf   rS   r   r   mainr{      sg    LCaI	!HJW4LSQ	
:<a)$r   __main__N)r   )__doc__turtlemathr   r   timer   ri   r   r   r)   r   r   r(   r'   r@   rH   rK   rT   r[   rf   rm   r{   __name__msgmainlooprS   r   r   <module>r      s       -AbDG

,& 


 !u B  
 z
&CJ r                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

   w82F                   ~    d Z ddlmZmZmZmZ dZ G d de      Z	 G d de      Z
d Zed	k(  r e         e        y
y
)a         turtle-example-suite:

        tdemo_planets_and_moon.py

Gravitational system simulation using the
approximation method from Feynman-lectures,
p.9-8, using turtlegraphics.

Example: heavy central body, light planet,
very light moon!
Planet has a circular orbit, moon a stable
orbit around the planet.

You can hold the movement temporarily by
pressing the left mouse button with the
mouse over the scrollbar of the canvas.

    )ShapeTurtlemainloopVec2D   c                       e Zd Zd Zd Zd Zy)GravSysc                 .    g | _         d| _        d| _        y )Nr   g{Gz?)planetstdt)selfs    1/usr/lib/python3.12/turtledemo/planet_and_moon.py__init__zGravSys.__init__   s        c                 F    | j                   D ]  }|j                           y )N)r   init)r   ps     r   r   zGravSys.init   s    A
FFH r   c                     t        d      D ]B  }| xj                  | j                  z
  c_        | j                  D ]  }|j	                           D y )Ni'  )ranger   r
   r   step)r   ir   s      r   startz
GravSys.start    s9    uAFFdggF\\ " r   N)__name__
__module____qualname__r   r   r    r   r   r	   r	      s    r   r	   c                   $    e Zd Zd Zd Zd Zd Zy)Starc                    t        j                  | |       | j                          || _        | j	                  |       || _        |j                  j                  |        || _        | j                  d       | j                          y )N)shapeuser)r   r   penupmsetposvr   appendgravSys
resizemodependown)r   r$   xr&   r(   r!   s         r   r   z
Star.__init__'   s`    E*

At$r   c                     | j                   j                  }| j                         | _        | j                  d|z  | j                  z  z   | _        y )N      ?)r(   r
   accar&   r   r
   s     r   r   z	Star.init1   s8    
\\__#b&-'r   c                     t        dd      }| j                  j                  D ]Q  }|| k7  s	|j                         | j                         z
  }|t        |j
                  z  t
        |      dz  z  |z  z
  }S |S )Nr      )Vecr(   r   posGr$   abs)r   r/   planetr&   s       r   r.   zStar.acc5   si    !Hll**F~JJL+ajQ*A-- + r   c                    | j                   j                  }| j                  | j                         || j                  z  z          | j                   j
                  j
                  |       dk7  r7| j                  | j                  | j                   j
                  d                | j                         | _
        | j                  || j                  z  z   | _        y )Nr   )r(   r
   r%   r4   r&   r   index
setheadingtowardsr.   r/   r0   s     r   r   z	Star.step<   s    
\\__DHHJDFF*+<<%%d+q0OODLL)=)=a)@AB"TVV)#r   N)r   r   r   r   r   r.   r   r   r   r   r   r   &   s    	($r   r   c                     t               } | j                          | j                         j                  dd       | j	                          | j                          | j
                  d       | j                  d       | j                          | j                  dd       | j                          | j                         }| j                          | j                  dd       | j                          | j                         }t        d      }|j                  |d       |j                  |d       | j                         j                  d|       | j                         j                  d	d       t               }t!        d
t#        dd      t#        dd      |d      }|j%                  d
       |j'                  d       |j                          t!        dt#        dd      t#        dd      |d      }|j)                  d       |j'                  d       t!        d	t#        dd      t#        dd      |d      }|j)                  d       |j'                  d       |j+                          |j-                          y)Nr      Z      compoundorangebluer7      i@B g      circleyellowg?i0        greeng?   i'  r-   zDone!)r   reset	getscreentracerhtpufdlt
begin_polyrD   end_polyget_polyr   addcomponentregister_shaper	   r   r3   color	shapesizepencolorr   r   )sm1m2planetshapegssunearthmoons           r   mainra   F   s   AGGIKKM1DDFDDFDDGDDHLLNHHQJJL	
BLLNHHQsOJJL	
B
#KR)R'KKM  ;7KKM1 
B
wAa#a+r8
<CIIhMM#FFHC
C#JH=E	NN7	OOC3s1:s1Sz2x8DMM&NN3GGIHHJr   __main__N)
__doc__turtler   r   r   r   r3   r5   objectr	   r   ra   r   r   r   r   <module>rf      sO   $ 9 8f $6 $@%N zFJ r                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 

   a}                   p    d Z ddlmZmZmZ ddlmZmZ d Z	d Z
edk(  r e
       Z e
e        e        yy)aF        turtle-example-suite:

          tdemo_wikipedia3.py

This example is
inspired by the Wikipedia article on turtle
graphics. (See example wikipedia1 for URLs)

First we create (ne-1) (i.e. 35 in this
example) copies of our first turtle p.
Then we let them perform their steps in
parallel.

Followed by a complete undo().
    )ScreenTurtlemainloop)perf_countersleepc                 l   | g}t        d|      D ]9  }| j                         }|j                  d|z         |j                  |       |} ; t        |      D ][  }t	        |dz  |z
        |dz  z  }|D ]=  }|j                  d|z         |j                  d|z
  d|       |j
                  |       ? ] y )N   g     v@g       @gffffff?r   )rangeclonertappendabspencolorfd)pnesz
turtlelistiqcts           )/usr/lib/python3.12/turtledemo/rosette.pymn_eckr      s    J
1R[
GGI	U2X!
	 
 2Y3qM2b5! A
DDbM
JJqs1Q
DDH 	     c                  b   t               } | j                  d       t               }|j                  d       |j	                          |j                  d       |j
                  d       | j                  dd       t               }t        |dd       t               }||z
  }t        d       t               }t        d | j                         D              rF| j                         D ]  }|j                           t        d | j                         D              rFt               }d	||z   |z
  z  S )
Nblackr   red   $      r	   c              3   <   K   | ]  }|j                           y w)N)undobufferentries).0r   s     r   	<genexpr>zmain.<locals>.<genexpr>7   s     
9[a!!#[s   zruntime: %.3f sec)r   bgcolorr   speed
hideturtler   pensizetracerclockr   r   anyturtlesundo)sr   atetz1r   s         r   mainr3   $   s    AIIghAGGAJLLNJJuIIaLHHRN	B
1b"	B	BB	!H	B


9QYY[
9
9A
FFH  
9QYY[
9
9 
B"R%(++r   __main__N)__doc__turtler   r   r   timer   r+   r   r   r3   __name__msgprint r   r   <module>r<      sA    , + -",4 z
&C	#JJ r                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  

   6)LP                   R    d Z ddl d Zd Zedk(  r e e               e        yy)aF        turtle-example-suite:

         tdemo_round_dance.py

(Needs version 1.1 of the turtle module that
comes with Python 3.1)

Dancing turtles have a compound shape
consisting of a series of triangles of
decreasing size.

Turtles march along a circle while rotating
pairwise in opposite direction, with one
exception. Does that breaking of symmetry
enhance the attractiveness of the example?

Press any key to stop the animation.

Technically: demonstrates use of compound
shapes, transformation of shapes as well as
cloning turtles. The animation is
controlled through update().
    )*c                      da y )NF)running     -/usr/lib/python3.12/turtledemo/round_dance.pystopr	      s    Gr   c                     t                t        d       t        d       t        d       d} d}d}d}t	        d      }t        d	      D ]F  }t
        |       t               }|| z  }|| z  }t        |        |j                  ||d
d|z
  fd       H t        d|       t
        d       t        d       t                t        d
d       g }t        d      D ]O  }t        d       t        d       t        d       t                |dz  d
k(  s7|j!                  t#                      Q t%                dat)        t*               t-                d}t&        rvd}	|D ]>  }
|
j                  d       |
j                  d       |
j                  |	       |	d
kD  rdnd}	@ |dk  rt/        d       t
        |       |dz  }t                t&        rvy)Ngray10Ftriangleg}Rc?gy!"@      compound
   g      ?blackmultitrir   i8            T   gGz?zDONE!)clearscreenbgcolortracershapeShaperange	shapesize
get_shapepolytiltaddcomponentregister_shapepusetposfdltupdateappendclonehomer   
onkeypressr	   listenright)fphiscshipdancerscstadancers              r   mainr:      s   MH
5M	*
A
C	A	A	z	B
2Y!?	Q	QcT

AtQqS>73
  :r"
aL	*D
1dOG
3Z
1R
1r6Q;NN57#
  	FGt
H	
B

FIIaLIIaLKKOAv1B	 
 8!HbM%KB  r   __main__N)__doc__turtler	   r:   __name__printmainloopr   r   r   <module>rA      s7   0 3j Z	$&MJ r                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      

   XNFO                       d Z ddl ddlZ G d de      Z G d de      Zd Zd	 Zd
 Z	d Z
d Zdd
Zd Z
d Zd Zd Zd Zd Zd ZdZdZedk(  r e       Z e        yy)a  

         sorting_animation.py

A minimal sorting algorithm animation:
Sorts a shelf of 10 blocks using insertion
sort, selection sort and quicksort.

Shelves are implemented using builtin lists.

Blocks are turtles with shape "square", but
stretched to rectangles by shapesize()
 ---------------------------------------
       To exit press space button
 ---------------------------------------
    )*Nc                   $    e Zd Zd Zd Zd Zd Zy)Blockc                     || _         t        j                  | dd       | j                          | j	                  |dz  dd       | j                  d       | j
                          y )NsquareF)shapevisibleg      ?   black)sizeTurtle__init__pu	shapesize	fillcolorst)selfr   s     1/usr/lib/python3.12/turtledemo/sorting_animate.pyr   zBlock.__init__   sM    	He<	tcz3*w	    c                 &    | j                  d       y )Nredr   r   s    r   glowz
Block.glow    s    ur   c                 &    | j                  d       y )Nr   r   r   s    r   unglowzBlock.unglow#   s    wr   c                 8    dj                  | j                        S )NzBlock size: {0})formatr   r   s    r   __repr__zBlock.__repr__&   s     ''		22r   N)__name__
__module____qualname__r   r   r   r    r   r   r   r      s     3r   r   c                   0    e Zd Zd Zd Zd Zd Zd Zd Zy)Shelfc                      || _         d| _        y)z.create a shelf. y is y-position of first blockijN)yx)r   r'   s     r   r   zShelf.__init__,   s    r   c                     |j                         \  }}}|dz  dz  }|j                  | j                  |z          |j                  | j                  dt        |       z  z          | j
                  |       y )Nr
      "   )r   setyr'   setxr(   lenappend)r   dwidth_y_offsets        r   pushz
Shelf.push1   s]    kkmq!19r>	tvv !	tvvSY&'Ar   c                 f    | |d  D ])  }|j                         \  }}|j                  |dz
         + y Nr+   posr-   r   ibxposr2   s        r   _close_gap_from_izShelf._close_gap_from_i9   1    abAeegGD!
FF4"9 r   c                 f    | |d  D ])  }|j                         \  }}|j                  |dz          + y r6   r7   r9   s        r   _open_gap_from_izShelf._open_gap_from_i>   r>   r   c                     t         j                  | |      }|j                          |j                  d       | j	                  |       |S )N   )listpopr   r,   r=   )r   keyr;   s      r   rD   z	Shelf.popC   s9    HHT3		ss#r   c                 *   | j                  |       t        j                  | ||       |j                  | j                  d|z  z          |j                         \  }}}|dz  dz  }|j
                  | j                  |z          |j                          y )Nr+   r
   r*   )	r@   rC   insertr-   r(   r   r,   r'   r   )r   rE   r;   r1   r2   r3   s         r   rG   zShelf.insertJ   su    c"D#q!	tvvS !kkmq!19r>	tvv !	
r   N)	r    r!   r"   r   r4   r=   r@   rD   rG   r#   r   r   r%   r%   *   s     


r   r%   c                 *   t        |       }t        d|      D ]y  }|}|dkD  rO| |   j                  | |dz
     j                  k  r-|dz
  }|dkD  r#| |   j                  | |dz
     j                  k  r-| j                  || j	                  |             { y )N   r   r.   ranger   rG   rD   )shelflengthr:   holes       r   isortrO   T   s    
ZF
1f
Qh58==5?+?+??!8D Qh58==5?+?+??
T599Q<(	 
 r   c                     t        |       }t        d|dz
        D ]a  }|}t        |dz   |      D ]$  }| |   j                  | |   j                  k  s#|}& ||k7  sA| j                  || j	                  |             c y )Nr   rI   rJ   )rL   rM   jiminr:   s        r   ssortrS   ]   sx    
ZF
1fqj
!q1uf%AQx}}uT{/// & 19LLEIIdO,
 "r   c                 @   | |   }| j                  || j                  |             |}t        ||      D ]E  }| |   j                  |j                  k  s | j                  || j                  |             |dz   }G | j                  || j                  |             |S NrI   )rG   rD   rK   r   )rL   leftrightpivot_indexpivotstore_indexr:   s          r   	partitionr[   g   s    +E	LL		+./K
4
8==5::%LLeiil3%/K   
LLeii./r   c                 p    ||k  r1|}t        | |||      }t        | ||dz
         t        | |dz   |       y y rU   )r[   qsort)rL   rV   rW   rX   pivot_new_indexs        r   r]   r]   r   sE    e|#E4D
eT?Q./
e_q(%0	 r   c                     t                t                t        t        d            } t	        j
                  |        t
        |       D ]f  \  }}t        |t        t                    D ]E  }t        |   j                  |dz   k(  st        j                  |t        j                  |             G h t        t               t        t        d       t                y )N
   rI   line)disable_keysclearrC   rK   randomshuffle	enumerater.   sr   rG   rD   	show_text
instructions1
instructions2enable_keys)targetr:   trQ   s       r   	randomizero   y   s    N	G
%)_F
NN6&!1q#a&!AtyyAE!AEE!H% " " m
m!$Mr   c                 H    d|z  }t        dd|z
         t        | dd       y )Nr*   r   icenter)Courier   bold)alignfont)gotowrite)textrb   s     r   ri   ri      s&    
9D4$;	$h%<=r   c                      t                t                t        d       t        t               t                t        t
               t        t        d       t                y )NzSelection SortrI   ra   )rc   rd   ri   rS   rh   rj   rk   rl   r#   r   r   start_ssortr{      8    N	G
	!H	G
m
m!$Mr   c                      t                t                t        d       t        t               t                t        t
               t        t        d       t                y )NzInsertion SortrI   ra   )rc   rd   ri   rO   rh   rj   rk   rl   r#   r   r   start_isortr~      r|   r   c                      t                t                t        d       t        t        dt        t              dz
         t                t        t               t        t        d       t                y )N	Quicksortr   rI   ra   )	rc   rd   ri   r]   rh   r.   rj   rk   rl   r#   r   r   start_qsortr      sD    N	G
k	!QA
	G
m
m!$Mr   c                  h    t        d      ad} | D ]   }t        j                  t        |             " y )Ni8)
   r
      	   rI      r`            )r%   rh   r4   r   )valsr:   s     r   
init_shelfr      s*    
dA*D
	uQx r   c                  d    t        d d       t        d d       t        d d       t        d d       y )Nrh   r:   qr)onkeyr#   r   r   rc   rc      s*    	$	$	$	$r   c                      t        t        d       t        t        d       t        t        d       t        t        d       t        t
        d       y )Nr:   rh   r   r   space)r   r~   r{   r   ro   byer#   r   r   rl   rl      s4    	+s	+s	+s	)S	#wr   c                      t               j                          t                t                t	                t        t               t        t        d       t                t                y)NrI   ra   	EVENTLOOP)
	getscreenclearscreenhtpenupr   ri   rj   rk   rl   listenr#   r   r   mainr      s=    
KD%'L
m
m!$M
Hr   zApress i for insertion sort, s for selection sort, q for quicksortz spacebar to quit, r to randomize__main__)r   )__doc__turtlere   r
   r   rC   r%   rO   rS   r[   r]   ro   ri   r{   r~   r   r   rc   rl   r   rj   rk   r    msgmainloopr#   r   r   <module>r      s      
3F 3((D (T-	1>
 T
2
Z
&CJ r                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      

   \Ŵ6                   n    d Z ddlmZmZ ddlmZ d Zd Zd Z	e
dk(  r e	       Z ee        e        yy)	a        turtle-example-suite:

             tdemo_tree.py

Displays a 'breadth-first-tree' - in contrast
to the classical Logo tree drawing programs,
which use a depth-first-algorithm.

Uses:
(1) a tree-generator, where the drawing is
quasi the side-effect, whereas the generator
always yields None.
(2) Turtle-cloning: At each branching point
the current pen is cloned. So in the end
there are 1024 turtles.
    )Turtlemainloop)perf_counterc              #   (  K   |dkD  rg }| D ]g  }|j                  |       |j                         }|j                  |       |j                  |       |j	                  |       |j	                  |       i t        |||z  ||      D ]  }d  yyw)z plist is list of pens
    l is length of branch
    a is half of the angle between 2 branches
    f is factor by which branch is shortened
    from level to level.   N)forwardcloneleftrightappendtree)plistlaflstpqxs           &/usr/lib/python3.12/turtledemo/tree.pyr
   r
      s      	1uA
IIaL	A
FF1I
GGAJJJqMJJqM
  c1Q31%AJ & 
s   BBc                  l   t               } | j                  d        | j                          | j                  d       | j	                         j                  dd       | j
                  d       | j                          | j                  d       | j                          t        | gddd      }|D ]  } y )Nr      Z   i.   A   gffffff?)r   
setundobuffer
hideturtlespeed	getscreentracerr
   penupr   pendownr
   )r   tr   s      r   maketreer$   '   s    AOODLLNGGAJKKMAFF2JGGIIIdOIIKaS#r6"A
     c                  N    t               } t                t               }d|| z
  z  S )Nzdone: %.2f sec.)clockr$   )r   bs     r   mainr)   5   s$    gAJgA!$$r%   __main__N)
__doc__turtler   r   timer   r'   r
   r$   r)   __name__msgprint r%   r   <module>r2      sC     $ &$
% z
&C	#JJ r%                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

   a4/                   ^    d Z ddlmZmZmZ d Zedk(  r e         ej                          yy)zturtledemo.two_canvases

Use TurtleScreen and RawTurtle to draw on two
distinct canvases in a separate window. The
new window must be separately closed in
addition to pressing the STOP button.
    )TurtleScreen	RawTurtleTKc                     t        j                         } t        j                  | ddd      }t        j                  | ddd      }|j                          |j                          t	        |      }|j                  ddd       t	        |      }|j                  ddd       t
        |      }t
        |      }|j                  dd	       |j                  d
       |j                  dd       |j                  d
       ||fD ]$  }|j                  d
       |j                  d       & |j                  d       ||fD ]  }|j                           t        d      D ]-  }||fD ]$  }|j                  d       |j                  d       & / ||fD ]D  }|j                          |j                  d       |j                          |j!                  d       F y)Ni,     z#ddffff)widthheightbgz#ffeeee333333?   red)r   r   r      blue)r   r   r   turtle$         2   H   6   	EVENTLOOP)r   TkCanvaspackr   bgcolorr   colorr   shapelt
begin_fillrangefdend_fillpubk)	rootcv1cv2s1s2pqtis	            ./usr/lib/python3.12/turtledemo/two_canvases.pymainr/      sw   
557D
))DCI
>C
))DCI
>CHHJHHJ	c	BJJtT1	c	BJJq$"
A"
AGGE?#GGAJGGFO$GGAJ
qS		R  DDI
T	 
1XAA
DDH
DDH   qS	

	R		R	      __main__N)__doc__r   r   r   r   r/   __name__mainloop r0   r.   <module>r6      s7    / .&R zFBKKM r0                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          

   oUr                   F    d Z ddl d Zd Zedk(  r e         e        yy)z       turtle-example-suite:

            tdemo_yinyang.py

Another drawing suitable as a beginner's
programming example.

The small circles are drawn by the circle
command.

    )*c                    t        d       t        d|       t                t        | dz  d       t        | d       t	        d       t        |  dz  d       t                t	        d       t
                t        | dz         t        d       t                t        ||       t                t        | dz         t                t	        d       t
                t        | dz         t                t	        d       y )N   blackg       @   Z   gffffff?g333333?)widthcolor
begin_fillcircleleftend_fillupforwardrightdownbackward)radiuscolor1color2s      )/usr/lib/python3.12/turtledemo/yinyang.pyyinr      s    	!H	'6L
6"9c
63I
F72:sJHDF4K	"IF	&&L
6$;JHDVD[FH    c                  `    t                t        ddd       t        ddd       t                y)N   r   whitezDone!)resetr   ht r   r   mainr    (   s'    	GWgWgDr   __main__N)__doc__turtler   r    __name__mainloopr   r   r   <module>r&      s2   
 
0 zFJ r                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        #!/usr/bin/env python3
"""      turtle-example-suite:

        tdemo_bytedesign.py

An example adapted from the example-suite
of PythonCard's turtle graphics.

It's based on an article in BYTE magazine
Problem Solving with Logo: Using Turtle
Graphics to Redraw a Design
November 1982, p. 118 - 134

-------------------------------------------

Due to the statement

t.delay(0)

in line 152, which sets the animation delay
to 0, this animation runs in "line per line"
mode as fast as possible.
"""

from turtle import Turtle, mainloop
from time import perf_counter as clock

# wrapper for any additional drawing routines
# that need to know about each other
class Designer(Turtle):

    def design(self, homePos, scale):
        self.up()
        for i in range(5):
            self.forward(64.65 * scale)
            self.down()
            self.wheel(self.position(), scale)
            self.up()
            self.backward(64.65 * scale)
            self.right(72)
        self.up()
        self.goto(homePos)
        self.right(36)
        self.forward(24.5 * scale)
        self.right(198)
        self.down()
        self.centerpiece(46 * scale, 143.4, scale)
        self.getscreen().tracer(True)

    def wheel(self, initpos, scale):
        self.right(54)
        for i in range(4):
            self.pentpiece(initpos, scale)
        self.down()
        self.left(36)
        for i in range(5):
            self.tripiece(initpos, scale)
        self.left(36)
        for i in range(5):
            self.down()
            self.right(72)
            self.forward(28 * scale)
            self.up()
            self.backward(28 * scale)
        self.left(54)
        self.getscreen().update()

    def tripiece(self, initpos, scale):
        oldh = self.heading()
        self.down()
        self.backward(2.5 * scale)
        self.tripolyr(31.5 * scale, scale)
        self.up()
        self.goto(initpos)
        self.setheading(oldh)
        self.down()
        self.backward(2.5 * scale)
        self.tripolyl(31.5 * scale, scale)
        self.up()
        self.goto(initpos)
        self.setheading(oldh)
        self.left(72)
        self.getscreen().update()

    def pentpiece(self, initpos, scale):
        oldh = self.heading()
        self.up()
        self.forward(29 * scale)
        self.down()
        for i in range(5):
            self.forward(18 * scale)
            self.right(72)
        self.pentr(18 * scale, 75, scale)
        self.up()
        self.goto(initpos)
        self.setheading(oldh)
        self.forward(29 * scale)
        self.down()
        for i in range(5):
            self.forward(18 * scale)
            self.right(72)
        self.pentl(18 * scale, 75, scale)
        self.up()
        self.goto(initpos)
        self.setheading(oldh)
        self.left(72)
        self.getscreen().update()

    def pentl(self, side, ang, scale):
        if side < (2 * scale): return
        self.forward(side)
        self.left(ang)
        self.pentl(side - (.38 * scale), ang, scale)

    def pentr(self, side, ang, scale):
        if side < (2 * scale): return
        self.forward(side)
        self.right(ang)
        self.pentr(side - (.38 * scale), ang, scale)

    def tripolyr(self, side, scale):
        if side < (4 * scale): return
        self.forward(side)
        self.right(111)
        self.forward(side / 1.78)
        self.right(111)
        self.forward(side / 1.3)
        self.right(146)
        self.tripolyr(side * .75, scale)

    def tripolyl(self, side, scale):
        if side < (4 * scale): return
        self.forward(side)
        self.left(111)
        self.forward(side / 1.78)
        self.left(111)
        self.forward(side / 1.3)
        self.left(146)
        self.tripolyl(side * .75, scale)

    def centerpiece(self, s, a, scale):
        self.forward(s); self.left(a)
        if s < (7.5 * scale):
            return
        self.centerpiece(s - (1.2 * scale), a, scale)

def main():
    t = Designer()
    t.speed(0)
    t.hideturtle()
    t.getscreen().delay(0)
    t.getscreen().tracer(0)
    at = clock()
    t.design(t.position(), 2)
    et = clock()
    return "runtime: %.2f sec." % (et-at)

if __name__ == '__main__':
    msg = main()
    print(msg)
    mainloop()
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        