[0O@s%dZdZddlZddlZddlZddlZddlZddlZddl m Z m Z m Z ddl mZddlmZddd d d d d ddg Zddddddddddddddddd d!d"d#d$d%d&d'd(d)d*d+d,d-d.gZd/d0d1d2d3d4d5d6d7d8d9d:d;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}gOZd~dgZeeeedgZdd0d3d@dMdQdUd[d]dbdcdedfdqdvdydzgZiddz6dd6dd6dd6dd6dd6dd6dd6dd6dd6ddk6ddW6ddA6dda6dd6dd6dd6dd6dd)6dd6ZddZddZyeeWnedYnXGdddeZddZddZddZfddZGdddej Z!ee!ej"dGdddej#Z$ej"Z"Gddde%Z&Gddde'Z(Gddde'Z)Gddde%Z*Gddde%Z+Gddde&Z,Gddde%Z-Gddde%Z.Gddde%Z/Gdd d e.e-Z0e0Z1dd Z2Gddde,Z3Gdd d e0Z4e4Z5ddZ6ddZ7ddd~Z8ddZ9edZ:ye:dkrCe9e:nWn4e;k reede:Ynede:YnXddZ<ddZ=ddZ>xeD]Z?e<e@de?\ZAZBeAdkredeAeBqndie?d6eAd6eBd6ZCeDeCe>e@de?je@e?_qWxeD]Z?e<e@de?\ZAZBeAdkredeAeBq@ndie?d6eAd6eBd6ZCeDeCe=e@de?je@e?_q@WeEZFeGdkr!ddZHddZIddZJeIeJeKndS)a Turtle graphics is a popular way for introducing programming to kids. It was part of the original Logo programming language developed by Wally Feurzig and Seymour Papert in 1966. Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25), and it rotates in-place 25 degrees clockwise. By combining together these and similar commands, intricate shapes and pictures can easily be drawn. ----- turtle.py This module is an extended reimplementation of turtle.py from the Python standard distribution up to Python 2.5. (See: http://www.python.org) It tries to keep the merits of turtle.py and to be (nearly) 100% compatible with it. This means in the first place to enable the learning programmer to use all the commands, classes and methods interactively when using the module from within IDLE run with the -n switch. Roughly it has the following features added: - Better animation of the turtle movements, especially of turning the turtle. So the turtles can more easily be used as a visual feedback instrument by the (beginning) programmer. - Different turtle shapes, gif-images as turtle shapes, user defined and user controllable turtle shapes, among them compound (multicolored) shapes. Turtle shapes can be stretched and tilted, which makes turtles very versatile geometrical objects. - Fine control over turtle movement and screen updates via delay(), and enhanced tracer() and speed() methods. - Aliases for the most commonly used commands, like fd for forward etc., following the early Logo traditions. This reduces the boring work of typing long sequences of commands, which often occur in a natural way when kids try to program fancy pictures on their first encounter with turtle graphics. - Turtles now have an undo()-method with configurable undo-buffer. - Some simple commands/methods for creating event driven programs (mouse-, key-, timer-events). Especially useful for programming games. - A scrollable Canvas class. The default scrollable Canvas can be extended interactively as needed while playing around with the turtle(s). - A TurtleScreen class with methods controlling background color or background image, window and canvas size and other properties of the TurtleScreen. - There is a method, setworldcoordinates(), to install a user defined coordinate-system for the TurtleScreen. - The implementation uses a 2-vector class named Vec2D, derived from tuple. This class is public, so it can be imported by the application programmer, which makes certain types of computations very natural and compact. - Appearance of the TurtleScreen and the Turtles at startup/import can be configured by means of a turtle.cfg configuration file. The default configuration mimics the appearance of the old turtle module. - If configured appropriately the module reads in docstrings from a docstring dictionary in some different language, supplied separately and replaces the English ones by those read in. There is a utility function write_docstringdict() to write a dictionary with the original (English) docstrings to disc, so it can serve as a template for translations. Behind the scenes there are some features included with possible extensions in mind. These will be commented and documented elsewhere. z-turtle 1.1b- - for Python 3.1 - 4. 5. 2009N)isfilesplitjoin)deepcopy) simpledialogScrolledCanvas TurtleScreenScreen RawTurtleTurtleRawPenPenShapeVec2Daddshapebgcolorbgpicbye clearscreen colormodedelay exitonclick getcanvas getshapeslistenmainloopmodenuminputonkey onkeypress onkeyrelease onscreenclickontimerregister_shape resetscreen screensizesetupsetworldcoordinates textinputtitletracerturtlesupdate window_height window_widthbackbackward begin_fill begin_polybkcircleclear clearstamp clearstampsclonecolordegreesdistancedotdownend_fillend_polyfd fillcolorfillingforwardget_polygetpen getscreen get_shapepoly getturtlegotoheading hideturtlehomehtisdown isvisibleleftltonclickondrag onreleasepdpenpencolorpendownpensizepenuppospositionpuradiansrightreset resizemodertseth setheadingsetpos setposition settiltangle setundobuffersetxsetyshape shapesizeshapetransform shearfactor showturtlespeedststamptilt tiltangletowards turtlesizeundoundobufferentriesupwidthwritexcorycorwrite_docstringdictdone Terminatorg?g?heighti canvwidthi, canvheight leftright topbottomstandardg? iundobuffersizeclassicblacknoresizeTvisibleZenglishlanguageturtle exampleturtlescreen examplescreenzPython Turtle GraphicsF using_IDLEcCst|d}|j}WdQXi}x|D]}|j}| s1|jdr_q1ny|jd\}}Wntd||fw1YnX|j}|j}|d krt|}n6y+d |krt|}n t|}WnYnX|||)TKFrame__init__winfo_toplevelZ _rootwindowrzrrrrCanvasZSUNKEN_canvasZ ScrollbarZxviewZ HORIZONTALhscrollZyviewvscrollZ configuresetZ rowconfigureZcolumnconfiguregridr`bindonResize)rZmasterrzrrrrrrrOs,  $$$ zScrolledCanvas.__init__Nc Cs|r||_n|r$||_n|r6||_n|jjd|d|j d|j d|jd|jdf|jjd|j|jd|j|jjd|j|jd|j|j dS)zZ!d?d@Z"dAdBZ#dCdDZ$d d d dEdFZ%d S)GTurtleScreenBasezProvide the basic graphics functionality. Interface between Tkinter and turtle.py. To port turtle.py to some different graphics toolkit a corresponding TurtleScreenBase class has to be implemented. cCs&tjdddd}|j|S)z$return a blank image object rzrr)r PhotoImageblank)Zimgrrr _blankimages zTurtleScreenBase._blankimagecCstjd|S)z`return an image object containing the imagedata from a gif-file named filename. file)rr)rrrr_imageszTurtleScreenBase._imagecCs||_t|tr3|jj}|jj}nat|jjd}t|jjd}|jjd| d| d|d|df||_||_d|_|_ dS)Nrzrrrg?) cvrrrrrr rxscaleyscale)rr"whrrrrs  1  zTurtleScreenBase.__init__cCs|jjdddddS)zy|jj|}d}Wntjk r9d}YnX|S)zCCheck if the string color is a legal Tkinter color string. TF)r"Z winfo_rgbrZTclError)rr9Zrgbokrrr_iscolorstring8s   zTurtleScreenBase._iscolorstringcCs@|dk r,|jjd||jn|jjdSdS)zVSet canvas' backgroundcolor if color is not None, else return backgroundcolor.Nr)r"rr5r )rr9rrr_bgcolorBs  zTurtleScreenBase._bgcolorc Cs|\}}||j}||j}idd6dd6dd6}|jj|d| d|d ||d |d |} |jj| \} } } } |jj| | dfS) zWrite txt at pos in canvas with specified font and color. Return text item and x-coord of right bottom corner of text's bounding box.swrPrcenterZser_rtextanchorrfont)r#r$r"Z create_textr r,)rr[txtalignr?rWrrr>r3Zx0Zy0Zx1Zy1rrr_writeKs   ' zTurtleScreenBase._writercs\dkr&jj|d|n2fdd}jj|d|||dS)zBind fun to mouse-click event on turtle. fun must be a function with two arguments, the coordinates of the clicked point on the canvas. num, the number of the mouse-button defaults to 1 Nz csKjj|jjjj|j j}}||dS)N)r"canvasxrr#canvasyrr$)rrr)funrrreventfunfs!z+TurtleScreenBase._onclick..eventfun)r" tag_unbindtag_bind)rr3rEnumaddrFr)rErr_onclick]s zTurtleScreenBase._onclickcs\dkr&jj|d|n2fdd}jj|d|||dS)agBind fun to mouse-button-release event on turtle. fun must be a function with two arguments, the coordinates of the point on the canvas where mouse button is released. num, the number of the mouse-button defaults to 1 If a turtle is clicked, first _onclick-event will be performed, then _onscreensclick-event. NzcsKjj|jjjj|j j}}||dS)N)r"rCrr#rDrr$)rrr)rErrrrFxs!z-TurtleScreenBase._onrelease..eventfun)r"rGrH)rr3rErIrJrFr)rErr _onreleasels zTurtleScreenBase._onreleasecs\dkr&jj|d|n2fdd}jj|d|||dS)aqBind fun to mouse-move-event (with pressed mouse button) on turtle. fun must be a function with two arguments, the coordinates of the actual mouse position on the canvas. num, the number of the mouse-button defaults to 1 Every sequence of mouse-move-events on a turtle is preceded by a mouse-click event on that turtle. Nzc sZyKjj|jjjj|j j}}||WnYnXdS)N)r"rCrr#rDrr$)rrr)rErrrrFs !z*TurtleScreenBase._ondrag..eventfun)r"rGrH)rr3rErIrJrFr)rErr_ondrags zTurtleScreenBase._ondragcsVdkr#jjd|n/fdd}jjd|||dS)aGBind fun to mouse-click event on canvas. fun must be a function with two arguments, the coordinates of the clicked point on the canvas. num, the number of the mouse-button defaults to 1 If a turtle is clicked, first _onclick-event will be performed, then _onscreensclick-event. Nz csKjj|jjjj|j j}}||dS)N)r"rCrr#rDrr$)rrr)rErrrrFs!z1TurtleScreenBase._onscreenclick..eventfun)r"r r)rrErIrJrFr)rErr_onscreenclicks zTurtleScreenBase._onscreenclickcsSdkr&|jjd|dn)fdd}|jjd||dS)z`Bind fun to key-release event of key. Canvas must have focus. See method listen Nzcs dS)Nr)r)rErrrFsz0TurtleScreenBase._onkeyrelease..eventfun)r"r r)rrErrFr)rEr _onkeyreleases zTurtleScreenBase._onkeyreleasecsdkrH|dkr.|jjddq|jjd|dnKfdd}|dkr||jjd|n|jjd||dS)zIf key is given, bind fun to key-press event of key. Otherwise bind fun to any key-press. Canvas must have focus. See method listen. Nz z cs dS)Nr)r)rErrrFsz.TurtleScreenBase._onkeypress..eventfun)r"r r)rrErrFr)rEr _onkeypresss   zTurtleScreenBase._onkeypresscCs|jjdS)z=Set focus on canvas (in order to collect key-events) N)r"r)rrrr_listenszTurtleScreenBase._listencCs6|dkr|jj|n|jj||dS)z?Install a timer, which calls fun after t milliseconds. rN)r"Z after_idler6)rrEtrrr_ontimers zTurtleScreenBase._ontimercCs|jjddd|S)z0Create and return image item on canvas. rimage)r"Z create_image)rrTrrr _createimageszTurtleScreenBase._createimagecCsN|\}}|jj|||j| |jf|jj|d|dS)zZConfigure image item as to draw image object at position (x,y) on canvas) rTN)r"r*r#r$ itemconfig)rr3r[rTrrrrr _drawimages (zTurtleScreenBase._drawimagecCs*|jj|d||jj|dS)zConfigure image item as to draw image object at center of canvas. Set item to the first item in the displaylist, so it will be drawn below any other item .rTN)r"rVZ tag_lower)rr3rTrrr _setbgpicszTurtleScreenBase._setbgpiccCs|jj|S)zQReturn 'line' or 'polygon' or 'image' depending on type of item. )r"r)rr3rrr_typeszTurtleScreenBase._typecsA|jj|fddtdtdD}|S)a returns list of coordinate-pairs of points of item Example (for insiders): >>> from turtle import * >>> getscreen()._pointlist(getturtle().turtle._item) [(0.0, 9.9999999999999982), (0.0, -9.9999999999999982), (9.9999999999999982, 0.0)] >>> cs)g|]}||d fqS)rr).0i)r/rr s z/TurtleScreenBase._pointlist..rr)r"r*rangelen)rr3plr)r/r _pointlists+zTurtleScreenBase._pointlistcCs#|jjd||||fdS)Nr)r"r)rsrx1sry1srx2sry2rrr_setscrollregionsz!TurtleScreenBase._setscrollregionc Cs|jj}x|D]}t|jj|}g}xR|r|dd\}}|j|||j|||dd}q=W|jj||qWdS)Nr)r"Zfind_allrr*r)) rZ xscalefactorZ yscalefactorrr3Z coordinatesZ newcoordlistrrrrr_rescales  zTurtleScreenBase._rescalecCst|jts"|j|jfS||koD|koDdknr_|jj|jjfS|dk rw||_n|dk r||_n|jj|||dS)zaResize the canvas the turtles are drawing on. Does not alter the drawing window. N)rr"rrrr`)rrrrrrr_resizes'    zTurtleScreenBase._resizecCs`|jj}|dkr+|jd}n|jj}|dkrV|jd}n||fS)z; Return the width and height of the turtle window. rrzr)r"rr)rrzrrrr _window_sizes  zTurtleScreenBase._window_sizecCstjdS)a{Starts event loop - calling Tkinter's mainloop function. No argument. Must be last statement in a turtle graphics program. Must NOT be used if a script is run from within IDLE in -n mode (No subprocess) - for interactive use of turtle graphics. Example (for a TurtleScreen instance named screen): >>> screen.mainloop() N)rr)rrrrr s zTurtleScreenBase.mainloopcCstj||S)aPop up a dialog window for input of a string. Arguments: title is the title of the dialog window, prompt is a text mostly describing what information to input. Return the string input If the dialog is canceled, return None. Example (for a TurtleScreen instance named screen): >>> screen.textinput("NIM", "Name of first player:") )rZ askstring)rr)promptrrrr(/s zTurtleScreenBase.textinputc Cs"tj||d|d|d|S)aPop up a dialog window for input of a number. Arguments: title is the title of the dialog window, prompt is a text mostly describing what numerical information to input. default: default value minval: minimum value for imput maxval: maximum value for input The number input must be in the range minval .. maxval if these are given. If not, a hint is issued and the dialog remains open for correction. Return the number input. If the dialog is canceled, return None. Example (for a TurtleScreen instance named screen): >>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000) Z initialvalueZminvalueZmaxvalue)rZaskfloat)rr)ridefaultZminvalZmaxvalrrrr>szTurtleScreenBase.numinput)&rrrr staticmethodrr!rr(r0r1r2r4r5r7r9r:rBrKrLrMrNrOrPrQrSrUrWrXrYr`rerfrgrhrr(rrrrrrsH                   rc@seZdZdZdS)rzWill be raised in TurtleScreen.update, if _RUNNING becomes False. This stops execution of a turtle graphics script. Main purpose: use in the Demo-Viewer turtle.Demo.py. N)rrrrrrrrrYs c@seZdZdZdS)TurtleGraphicsErrorzSome TurtleGraphics Error N)rrrrrrrrrlbs rlc@s4eZdZdZdddZdddZdS)rzData structure modeling shapes. attribute _type is one of "polygon", "image", "compound" attribute _data is - depending on _type a poygon-tuple, an image or a list constructed using the addcomponent method. NcCs||_|dkr6t|trt|}qny|dkrt|tr|jjdrt|rtj |}qqn%|dkrg}nt d|||_ dS)NpolygonrTz.gifcompoundzThere is no shape type %s) rYrrrrlowerendswithrrr!rl_data)rZtype_datarrrrns   !  zShape.__init__cCsW|jdkr%td|jn|dkr:|}n|jj|||gdS)a-Add component to a shape of type compound. Arguments: poly is a polygon, i. e. a tuple of number pairs. fill is the fillcolor of the component, outline is the outline color of the component. call (for a Shapeobject namend s): -- s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue") Example: >>> poly = ((0,0),(10,-5),(0,10),(-10,-5)) >>> s = Shape("compound") >>> s.addcomponent(poly, "red", "blue") >>> # .. add more components and then use register_shape() rnz Cannot add component to %s ShapeN)rYrlrqr))rpolyrr'rrr addcomponent~s   zShape.addcomponent)rrrrrrtrrrrrgs c@sdeZdZdZdddZdddZdd Zd d Zd d ZddZ dS)Tbufferz5Ring buffer used as undobuffer for RawTurtle objects.rcCs2||_dgg||_d|_d|_dS)NrFr)bufsizebufferptrcumulate)rrvrrrrs  zTbuffer.__init__NcCsb|dkr9xFt|jD]}dg|j|>> screen.clear() Note: this method is not available as function. rrallrrrrrrrN)rrr)rrrr4rU_bgpic _bgpicname_tracing_updatecounter_turtlesrrRrrrr _pen)rbtnrrrrr5s          zTurtleScreen.clearNcCs|dkr|jS|j}|dkr>td|n||_|d kr|j|j d|j d|jd|jdd|_|_n|jdS) agSet turtle-mode ('standard', 'logo' or 'world') and perform reset. Optional argument: mode -- on of the strings 'standard', 'logo' or 'world' Mode 'standard' is compatible with turtle.py. Mode 'logo' is compatible with most Logo-Turtle-Graphics. Mode 'world' uses userdefined 'worldcoordinates'. *Attention*: in this mode angles appear distorted if x/y unit-ratio doesn't equal 1. If mode is not given, return the current mode. Mode Initial turtle heading positive angles ------------|-------------------------|------------------- 'standard' to the right (east) counterclockwise 'logo' upward (north) clockwise Examples: >>> mode('logo') # resets turtle heading to north >>> mode() 'logo' NrlogoworldzNo turtle-graphics-mode %srg?)rr r )rr ) rrorlrerrr#r$r`)rrrrrr s     zTurtleScreen.modecCs|jdkr"|jdnt||}t||}|j\}}|j|d|d|j|j} } |j||_|j||_||j} | |j} |j| } |j| }|j| | | ||j |j| |j| |j dS)asSet up a user defined coordinate-system. Arguments: llx -- a number, x-coordinate of lower left corner of canvas lly -- a number, y-coordinate of lower left corner of canvas urx -- a number, x-coordinate of upper right corner of canvas ury -- a number, y-coordinate of upper right corner of canvas Set up user coodinat-system and switch to mode 'world' if necessary. This performs a screen.reset. If mode 'world' is already active, all drawings are redrawn according to the new coordinates. But ATTENTION: in user-defined coordinatesystems angles may appear distorted. (see Screen.mode()) Example (for a TurtleScreen instance named screen): >>> screen.setworldcoordinates(-10,-0.5,50,1.5) >>> for _ in range(36): ... left(10) ... forward(0.5) r N) rrrhr%r#r$rrrerfr,)rZllxZllyZurxZuryZxspanZyspanZwxZwyZ oldxscaleZ oldyscalerarbrcrdrrrr',s    z TurtleScreen.setworldcoordinatescCs|dkrO|jjdr<td|j|}qptddn!t|trptd|}n||j|>> screen.register_shape("triangle", ((5,-3),(0,5),(-5,-3))) Nz.gifrTz"Bad arguments for register_shape. zUse help(register_shape)rm)rorprr!rlrrr)rnamerkrrrr#Ss  zTurtleScreen.register_shapec CsOt|dkr|d}nt|trf|j|sI|dkrM|Stdt|ny|\}}}Wntdt|YnX|jdkrdd|||fD\}}}nd|kod kno"d|kod kno"d|ko d kns>td t|nd |||fS) aReturn color string corresponding to args. Argument may be a string or a tuple of three numbers corresponding to actual colormode, i.e. in the range 0<=n<=colormode. If the argument doesn't represent a color, an error is raised. rrrzbad color string: %szbad color arguments: %sg?cSs g|]}td|qS)go@)round)rZrrrrr\s z*TurtleScreen._colorstr..zbad color sequence: %sz #%02x%02x%02x)r^rrr9rlr)rr9rgbrrr _colorstrvs  (TzTurtleScreen._colorstrcsjdsStdkrAfddd D}nHtdkryfd dddD}ntd tfd d|DS) Nrrcs-g|]#}t||ddqS)rr)r)rZr[)cstrrrr\s z'TurtleScreen._color..rrrrcs'g|]}dt|dqS)r)r)rZr&)rrrr\s zbad colorstring: %scs!g|]}|jdqS)r)r)rZr)rrrr\s )rrr)rr^rlr)rrr/r)rrr_colors&zTurtleScreen._colorcCsS|dkr|jS|dkr1t||_n|dkrOt||_ndS)aqReturn the colormode or set it to 1.0 or 255. Optional argument: cmode -- one of the values 1.0 or 255 r, g, b values of colortriples have to be in range 0..cmode. Example (for a TurtleScreen instance named screen): >>> screen.colormode() 1.0 >>> screen.colormode(255) >>> pencolor(240,160,80) Ng?r)rrr)rZcmoderrrrs    zTurtleScreen.colormodecCs2x+|jD] }|j|j|jq WdS)zReset all Turtles on the Screen to their initial state. No argument. Example (for a TurtleScreen instance named screen): >>> screen.reset() N)r_setmoderr`)rrrrrr`szTurtleScreen.resetcCs|jS)zReturn the list of turtles on the screen. Example (for a TurtleScreen instance named screen): >>> screen.turtles() [] )r)rrrrr+szTurtleScreen.turtlescGsO|r|j|}nd}|j|}|dk rK|j|}n|S)aSet or return backgroundcolor of the TurtleScreen. Arguments (if given): a color string or three numbers in the range 0..colormode or a 3-tuple of such numbers. Example (for a TurtleScreen instance named screen): >>> screen.bgcolor("orange") >>> screen.bgcolor() 'orange' >>> screen.bgcolor(0.5,0,0.5) >>> screen.bgcolor() '#800080' N)rr:r)rr r9rrrrs zTurtleScreen.bgcolorcCsc|dkr|jSt||_d|_|dk rIt||_n|jr_|jndS)aeTurns turtle animation on/off and set delay for update drawings. Optional arguments: n -- nonnegative integer delay -- nonnegative integer If n is given, only each n-th regular screen update is really performed. (Can be used to accelerate the drawing of complex graphics.) Second arguments sets delay value (see RawTurtle.delay()) Example (for a TurtleScreen instance named screen): >>> screen.tracer(8, 25) >>> dist = 2 >>> for i in range(200): ... fd(dist) ... rt(90) ... dist += 2 Nr)rrrrr,)rnrrrrr*s    zTurtleScreen.tracercCs&|dkr|jSt||_dS)z Return or set the drawing delay in milliseconds. Optional argument: delay -- positive integer Example (for a TurtleScreen instance named screen): >>> screen.delay(15) >>> screen.delay() 15 N)rr)rrrrrrs zTurtleScreen.delaycCsRtjsdt_tn|jdkrN|jd7_|j|j;_ndS)zIncrement update counter.TrrN)r_RUNNINGZ _RUNNNINGrrr)rrrr _incrementudcs    zTurtleScreen._incrementudccCsT|j}d|_x(|jD]}|j|jqW||_|jdS)z'Perform a TurtleScreen update. TN)rr+ _update_data _drawturtler5)rtracingrRrrrr,s    zTurtleScreen.updatecCs|jdS)z Return the width of the turtle window. Example (for a TurtleScreen instance named screen): >>> screen.window_width() 640 r)rh)rrrrr.szTurtleScreen.window_widthcCs|jdS)z Return the height of the turtle window. Example (for a TurtleScreen instance named screen): >>> screen.window_height() 480 r)rh)rrrrr-%szTurtleScreen.window_heightcCs|jS)zReturn the Canvas of this TurtleScreen. No argument. Example (for a Screen instance named screen): >>> cv = screen.getcanvas() >>> cv )r")rrrrr.s zTurtleScreen.getcanvascCst|jjS)zReturn a list of names of all currently available turtle shapes. No argument. Example (for a TurtleScreen instance named screen): >>> screen.getshapes() ['arrow', 'blank', 'circle', ... , 'turtle'] )sortedrr)rrrrr:s zTurtleScreen.getshapesrcCs|j|||dS)aBind fun to mouse-click event on canvas. Arguments: fun -- a function with two arguments, the coordinates of the clicked point on the canvas. num -- the number of the mouse-button, defaults to 1 Example (for a TurtleScreen instance named screen) >>> screen.onclick(goto) >>> # Subsequently clicking into the TurtleScreen will >>> # make the turtle move to the clicked point. >>> screen.onclick(None) N)rN)rrErrJrrrrREszTurtleScreen.onclickcCsg|dkr1||jkrS|jj|qSn"||jkrS|jj|n|j||dS)amBind fun to key-release event of key. Arguments: fun -- a function with no arguments key -- a string: key (e.g. "a") or key-symbol (e.g. "space") In order to be able to register key-events, TurtleScreen must have focus. (See method listen.) Example (for a TurtleScreen instance named screen): >>> def f(): ... fd(50) ... lt(60) ... >>> screen.onkey(f, "Up") >>> screen.listen() Subsequently the turtle can be moved by repeatedly pressing the up-arrow key, consequently drawing a hexagon N)rremover)rO)rrErrrrrVs  zTurtleScreen.onkeycCss|dkr1||jkr_|jj|q_n.|dk r_||jkr_|jj|n|j||dS)aBind fun to key-press event of key if key is given, or to any key-press-event if no key is given. Arguments: fun -- a function with no arguments key -- a string: key (e.g. "a") or key-symbol (e.g. "space") In order to be able to register key-events, TurtleScreen must have focus. (See method listen.) Example (for a TurtleScreen instance named screen and a Turtle instance named turtle): >>> def f(): ... fd(50) ... lt(60) ... >>> screen.onkeypress(f, "Up") >>> screen.listen() Subsequently the turtle can be moved by repeatedly pressing the up-arrow key, or by keeping pressed the up-arrow key. consequently drawing a hexagon. N)rrr)rP)rrErrrrrts  zTurtleScreen.onkeypresscCs|jdS)aSet focus on TurtleScreen (in order to collect key-events) No arguments. Dummy arguments are provided in order to be able to pass listen to the onclick method. Example (for a TurtleScreen instance named screen): >>> screen.listen() N)rQ)rxdummyydummyrrrrs zTurtleScreen.listenrcCs|j||dS)aInstall a timer, which calls fun after t milliseconds. Arguments: fun -- a function with no arguments. t -- a number >= 0 Example (for a TurtleScreen instance named screen): >>> running = True >>> def f(): ... if running: ... fd(50) ... lt(60) ... screen.ontimer(f, 250) ... >>> f() # makes the turtle marching around >>> running = False N)rS)rrErRrrrr"szTurtleScreen.ontimercCsb|dkr|jS||jkr;|j||j|>> screen.bgpic() 'nopic' >>> screen.bgpic("landscape.gif") >>> screen.bgpic() 'landscape.gif' N)rrr!rXr)rZpicnamerrrrs  zTurtleScreen.bgpiccCs|j|||S)aResize the canvas the turtles are drawing on. Optional arguments: canvwidth -- positive integer, new width of canvas in pixels canvheight -- positive integer, new height of canvas in pixels bg -- colorstring or color-tuple, new backgroundcolor If no arguments are given, return current (canvaswidth, canvasheight) Do not alter the drawing window. To observe hidden parts of the canvas use the scrollbars. (Can make visible those parts of a drawing, which were outside the canvas before!) Example (for a Turtle instance named turtle): >>> turtle.screensize(2000,1500) >>> # e.g. to search for an erroneously escaped turtle ;-) )rg)rrrrrrrr%szTurtleScreen.screensize)%rrrrrrrr5rr'r#rrrr`r+rr*rrr,r.r-rrrRrrrr"rr%r!r$rrr rrrrrsD & " '#       c@seZdZdZieddd6eddd6eddd6ZdZdZdZed d Z d d Z d ddZ ddZ dddZ ddZddZddZddZddZdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd d+d,Zd-d.Zd/d0Zd1d2Zd d3d4Zd d5d6Zd7d8Zd9d:Z d d d;d<Z!dd=d>Z"d d d?d@Z#d dAdBZ$eZ%eZ&eZ'eZ(eZ)eZ*eZ+eZ,e Z-d S)C TNavigatorzRNavigation part of the RawTurtle. Implements methods for turtle movement. g?grr r rrcCs[|j|_|j|_||_d|_|jd|_|j|tj |dS)N) DEFAULT_ANGLEOFFSET _angleOffsetDEFAULT_ANGLEORIENT _angleOrientr undobufferr:rrr`)rrrrrrs       zTNavigator.__init__cCs)tdd|_tj|j|_dS)zXreset turtle to its initial values Will be overwritten by parent class gN)r _positionrSTART_ORIENTATIONr_orient)rrrrr`szTNavigator.resetNcCsj|dkr|jS|dkr#dS||_|d krMd|_d|_n|jd|_d |_dS) z:Set turtle-mode to 'standard', 'world' or 'logo'. Nrr r rrg@)standardzlogoworld)r(r)r)rr!r# _fullcircle)rrrrrrs      zTNavigator._setmodecCsB||_d||_|jdkr1d|_n |d|_dS)z+Helper function for degrees() and radians()ihrrg@N)r* _degreesPerAUrr!)r fullcirclerrr_setDegreesPerAUs    zTNavigator._setDegreesPerAUgv@cCs|j|dS)a> Set angle measurement units to degrees. Optional argument: fullcircle - a number Set angle measurement units, i. e. set number of 'degrees' for a full circle. Dafault value is 360 degrees. Example (for a Turtle instance named turtle): >>> turtle.left(90) >>> turtle.heading() 90 Change angle measurement unit to grad (also known as gon, grade, or gradian and equals 1/100-th of the right angle.) >>> turtle.degrees(400.0) >>> turtle.heading() 100 N)r-)rr,rrrr:szTNavigator.degreescCs|jdtjdS)a Set the angle measurement units to radians. No arguments. Example (for a Turtle instance named turtle): >>> turtle.heading() 90 >>> turtle.radians() >>> turtle.heading() 1.5707963267948966 rN)r-rr)rrrrr^4s zTNavigator.radianscCs%|j|j|}|j|dS)z)move turtle forward by specified distanceN)r%r'_goto)rr;Zenderrr_goBszTNavigator._gocCs&||j9}|jj||_dS)z=Turn turtle counterclockwise by specified angle if angle > 0.N)r+r'r)rrrrr_rotateGs zTNavigator._rotatecCs ||_dS)zmove turtle to position end.N)r%)rendrrrr.LszTNavigator._gotocCs|j|dS)aMove the turtle forward by the specified distance. Aliases: forward | fd Argument: distance -- a number (integer or float) Move the turtle forward by the specified distance, in the direction the turtle is headed. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 0.00) >>> turtle.forward(25) >>> turtle.position() (25.00,0.00) >>> turtle.forward(-75) >>> turtle.position() (-50.00,0.00) N)r/)rr;rrrrCPszTNavigator.forwardcCs|j| dS)aMove the turtle backward by distance. Aliases: back | backward | bk Argument: distance -- a number Move the turtle backward by distance ,opposite to the direction the turtle is headed. Do not change the turtle's heading. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 0.00) >>> turtle.backward(30) >>> turtle.position() (-30.00, 0.00) N)r/)rr;rrrr/gszTNavigator.backcCs|j| dS)aTurn turtle right by angle units. Aliases: right | rt Argument: angle -- a number (integer or float) Turn turtle right by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on mode. (See this.) Example (for a Turtle instance named turtle): >>> turtle.heading() 22.0 >>> turtle.right(45) >>> turtle.heading() 337.0 N)r0)rrrrrr_{szTNavigator.rightcCs|j|dS)aTurn turtle left by angle units. Aliases: left | lt Argument: angle -- a number (integer or float) Turn turtle left by angle units. (Units are by default degrees, but can be set via the degrees() and radians() functions.) Angle orientation depends on mode. (See this.) Example (for a Turtle instance named turtle): >>> turtle.heading() 22.0 >>> turtle.left(45) >>> turtle.heading() 67.0 N)r0)rrrrrrPszTNavigator.leftcCs|jS)zReturn the turtle's current location (x,y), as a Vec2D-vector. Aliases: pos | position No arguments. Example (for a Turtle instance named turtle): >>> turtle.pos() (0.00, 240.00) )r%)rrrrr[s zTNavigator.poscCs |jdS)z Return the turtle's x coordinate. No arguments. Example (for a Turtle instance named turtle): >>> reset() >>> turtle.left(60) >>> turtle.forward(100) >>> print turtle.xcor() 50.0 r)r%)rrrrr|s zTNavigator.xcorcCs |jdS)a  Return the turtle's y coordinate --- No arguments. Example (for a Turtle instance named turtle): >>> reset() >>> turtle.left(60) >>> turtle.forward(100) >>> print turtle.ycor() 86.6025403784 r)r%)rrrrr}s zTNavigator.ycorcCs<|dkr"|jt|n|jt||dS)atMove turtle to an absolute position. Aliases: setpos | setposition | goto: Arguments: x -- a number or a pair/vector of numbers y -- a number None call: goto(x, y) # two coordinates --or: goto((x, y)) # a pair (tuple) of coordinates --or: goto(vec) # e.g. as returned by pos() Move turtle to an absolute position. If the pen is down, a line will be drawn. The turtle's orientation does not change. Example (for a Turtle instance named turtle): >>> tp = turtle.pos() >>> tp (0.00, 0.00) >>> turtle.setpos(60,30) >>> turtle.pos() (60.00,30.00) >>> turtle.setpos((20,80)) >>> turtle.pos() (20.00,80.00) >>> turtle.setpos(tp) >>> turtle.pos() (0.00,0.00) N)r.r)rrrrrrrIs zTNavigator.gotocCs!|jdd|jddS)a$Move turtle to the origin - coordinates (0,0). No arguments. Move turtle to the origin - coordinates (0,0) and set its heading to its start-orientation (which depends on mode). Example (for a Turtle instance named turtle): >>> turtle.home() rN)rIrd)rrrrrLs zTNavigator.homecCs!|jt||jddS)aSet the turtle's first coordinate to x Argument: x -- a number (integer or float) Set the turtle's first coordinate to x, leave second coordinate unchanged. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 240.00) >>> turtle.setx(10) >>> turtle.position() (10.00, 240.00) rN)r.rr%)rrrrrriszTNavigator.setxcCs!|jt|jd|dS)aSet the turtle's second coordinate to y Argument: y -- a number (integer or float) Set the turtle's first coordinate to x, second coordinate remains unchanged. Example (for a Turtle instance named turtle): >>> turtle.position() (0.00, 40.00) >>> turtle.sety(-10) >>> turtle.position() (0.00, -10.00) rN)r.rr%)rrrrrrjszTNavigator.setycCs|dk rt||}nt|tr6|}n9t|trTt|}nt|tro|j}nt||jS)aReturn the distance from the turtle to (x,y) in turtle step units. Arguments: x -- a number or a pair/vector of numbers or a turtle instance y -- a number None None call: distance(x, y) # two coordinates --or: distance((x, y)) # a pair (tuple) of coordinates --or: distance(vec) # e.g. as returned by pos() --or: distance(mypen) # where mypen is another turtle Example (for a Turtle instance named turtle): >>> turtle.pos() (0.00, 0.00) >>> turtle.distance(30,40) 50.0 >>> pen = Turtle() >>> pen.forward(77) >>> turtle.distance(pen) 77.0 N)rrrrr%abs)rrrr[rrrr;$s   zTNavigator.distancecCs|dk rt||}nt|tr6|}n9t|trTt|}nt|tro|j}n||j\}}ttj||dtjdd}||j }|j |j ||j S)aCReturn the angle of the line from the turtle's position to (x, y). Arguments: x -- a number or a pair/vector of numbers or a turtle instance y -- a number None None call: distance(x, y) # two coordinates --or: distance((x, y)) # a pair (tuple) of coordinates --or: distance(vec) # e.g. as returned by pos() --or: distance(mypen) # where mypen is another turtle Return the angle, between the line from turtle-position to position specified by x, y and the turtle's start orientation. (Depends on modes - "standard" or "logo") Example (for a Turtle instance named turtle): >>> turtle.pos() (10.00, 10.00) >>> turtle.towards(0,0) 225.0 Ngf@rgv@) rrrrr%r ratan2rr+r!r#r*)rrrr[resultrrrruDs   * zTNavigator.towardscCs_|j\}}ttj||dtjdd}||j}|j|j||jS)z Return the turtle's current heading. No arguments. Example (for a Turtle instance named turtle): >>> turtle.left(67) >>> turtle.heading() 67.0 gf@rgv@) r'r rr3rr+r!r#r*)rrrr4rrrrJgs * zTNavigator.headingcCsK||j|j}|j}||d||d}|j|dS)aSet the orientation of the turtle to to_angle. Aliases: setheading | seth Argument: to_angle -- a number (integer or float) Set the orientation of the turtle to to_angle. Here are some common directions in degrees: standard - mode: logo-mode: -------------------|-------------------- 0 - east 0 - north 90 - north 90 - east 180 - west 180 - south 270 - south 270 - west Example (for a Turtle instance named turtle): >>> turtle.setheading(90) >>> turtle.heading() 90 g@N)rJr#r*r0)rZto_anglerfullrrrrdvs zTNavigator.setheadingc Cs|jr+|jjdgd|j_n|j}|dkrO|j}n|dkrt||j}dttdt|dd|}nd||}d |}d |tj |tj d |j }|d kr| | | }}}n|j } |j } |d kr:|j d d n |jd |j|xHt|D]:} |j||j||jd |j|qaW|j| |d kr|j | | n|j||jrd |j_ndS)a Draw a circle with given radius. Arguments: radius -- a number extent (optional) -- a number steps (optional) -- an integer Draw a circle with given radius. The center is radius units left of the turtle; extent - an angle - determines which part of the circle is drawn. If extent is not given, draw the entire circle. If extent is not a full circle, one endpoint of the arc is the current pen position. Draw the arc in counterclockwise direction if radius is positive, otherwise in clockwise direction. Finally the direction of the turtle is changed by the amount of extent. As the circle is approximated by an inscribed regular polygon, steps determines the number of steps to use. If not given, it will be calculated automatically. Maybe used to draw regular polygons. call: circle(radius) # full circle --or: circle(radius, extent) # arc --or: circle(radius, extent, steps) --or: circle(radius, steps=6) # 6-sided polygon Example (for a Turtle instance named turtle): >>> turtle.circle(50) >>> turtle.circle(120, 180) # semicircle seqTNr g@gM@g?g?g@gf@rF)r$rzryrpr*r2rminrrrr+_tracerr7r0r]r/) rradiusZextentstepsrpZfracr%Zw2lZtrZdlr[rrrr4s>     . )            zTNavigator.circlecCsdS)z/dummy method - to be overwritten by child classNr)rrrrrrpszTNavigator.speedcCsdS)z/dummy method - to be overwritten by child classNr)rarrrrr9szTNavigator._tracercCsdS)z/dummy method - to be overwritten by child classNr)rrrrrr7szTNavigator._delay).rrrrrr&Z DEFAULT_MODEr r"rr`rr-r:r^r/r0r.rCr/r_rPr[r|r}rIrLrirjr;rurJrdr4rpr9r7r@r3r0rbrQr\rerfrcrrrrrsZ             #    #  Arc@sNeZdZdZedddZededddZd d d Zd d d ZddZ ddZ ddZ d ddZ ddZ ddZddZddZddZd d!Zd d"d#Zd$d%d&Zd$d'd(d)Zd*d+Zd,d-ZeZe Ze Ze Ze ZeZeZd S).TPenzFDrawing part of the RawTurtle. Implements drawing properties. racCs#||_d|_tj|dS)N) _resizemoder$r>_reset)rrarrrrs  z TPen.__init__rWrAcCsgd|_d|_||_||_d|_d|_d|_d|_d|_d|_ d|_ dS)NrTr?)rArA)rArBrBrA) _pensize_shown _pencolor _fillcolor_drawing_speed_stretchfactor _shearfactor_tilt _shapetrafo _outlinewidth)rrWrArrrr@s          z TPen._resetNcCsB|dkr|jS|j}|dkr>|jd|ndS)azSet resizemode to one of the values: "auto", "user", "noresize". (Optional) Argument: rmode -- one of the strings "auto", "user", "noresize" Different resizemodes have the following effects: - "auto" adapts the appearance of the turtle corresponding to the value of pensize. - "user" adapts the appearance of the turtle according to the values of stretchfactor and outlinewidth (outline), which are set by shapesize() - "noresize" no adaption of the turtle's appearance takes place. If no argument is given, return current resizemode. resizemode("user") is called by a call of shapesize with arguments. Examples (for a Turtle instance named turtle): >>> turtle.resizemode("noresize") >>> turtle.resizemode() 'noresize' Nautouserrra)rNzuserr)r?rorV)rZrmoderrrras    zTPen.resizemodecCs'|dkr|jS|jd|dS)a!Set or return the line thickness. Aliases: pensize | width Argument: width -- positive number Set the line thickness to width or return it. If resizemode is set to "auto" and turtleshape is a polygon, that polygon is drawn with the same line thickness. If no argument is given, current pensize is returned. Example (for a Turtle instance named turtle): >>> turtle.pensize() 1 >>> turtle.pensize(10) # from here on lines of width 10 are drawn NrY)rCrV)rrzrrrrYs z TPen.pensizecCs!|js dS|jdddS)zPull the pen up -- no drawing when moving. Aliases: penup | pu | up No argument Example (for a Turtle instance named turtle): >>> turtle.penup() NrXF)rGrV)rrrrrZ/s z TPen.penupcCs!|jr dS|jdddS)zPull the pen down -- drawing when moving. Aliases: pendown | pd | down No argument. Example (for a Turtle instance named turtle): >>> turtle.pendown() NrXT)rGrV)rrrrrX=s z TPen.pendowncCs|jS)aReturn True if pen is down, False if it's up. No argument. Example (for a Turtle instance named turtle): >>> turtle.penup() >>> turtle.isdown() False >>> turtle.pendown() >>> turtle.isdown() True )rG)rrrrrNKs z TPen.isdowncCsidd6dd6dd6dd6d d 6}|d kr<|jS||krU||}n7d |kold knrtt|}nd}|jd|d S)a Return or set the turtle's speed. Optional argument: speed -- an integer in the range 0..10 or a speedstring (see below) Set the turtle's speed to an integer value in the range 0 .. 10. If no argument is given: return current speed. If input is a number greater than 10 or smaller than 0.5, speed is set to 0. Speedstrings are mapped to speedvalues in the following way: 'fastest' : 0 'fast' : 10 'normal' : 6 'slow' : 3 'slowest' : 1 speeds from 1 to 10 enforce increasingly faster animation of line drawing and turtle turning. Attention: speed = 0 : *no* animation takes place. forward/back makes turtle jump and likewise left/right make the turtle turn instantly. Example (for a Turtle instance named turtle): >>> turtle.speed(3) rZfastestrZfastrnormalrZslowrZslowestNg?g%@rp)rHrr rV)rrpZspeedsrrrrpZs)   z TPen.speedcGs|rt|}|dkr/|d}}n4|dkrJ|\}}n|dkrc|}}n|j|}|j|}|jd|d|n"|j|j|j|jfSdS)aReturn or set the pencolor and fillcolor. Arguments: Several input formats are allowed. They use 0, 1, 2, or 3 arguments as follows: color() Return the current pencolor and the current fillcolor as a pair of color specification strings as are returned by pencolor and fillcolor. color(colorstring), color((r,g,b)), color(r,g,b) inputs as in pencolor, set both, fillcolor and pencolor, to the given value. color(colorstring1, colorstring2), color((r1,g1,b1), (r2,g2,b2)) equivalent to pencolor(colorstring1) and fillcolor(colorstring2) and analogously, if the other input format is used. If turtleshape is a polygon, outline and interior of that polygon is drawn with the newly set colors. For mor info see: pencolor, fillcolor Example (for a Turtle instance named turtle): >>> turtle.color('red', 'green') >>> turtle.color() ('red', 'green') >>> colormode(255) >>> color((40, 80, 120), (160, 200, 240)) >>> color() ('#285078', '#a0c8f0') rrrrrWrAN)r^rrVrrErF)rr r<ZpcolorZfcolorrrrr9s      z TPen.colorcGsO|r;|j|}||jkr(dS|jd|n|j|jSdS)aZ Return or set the pencolor. Arguments: Four input formats are allowed: - pencolor() Return the current pencolor as color specification string, possibly in hex-number format (see example). May be used as input to another color/pencolor/fillcolor call. - pencolor(colorstring) s is a Tk color specification string, such as "red" or "yellow" - pencolor((r, g, b)) *a tuple* of r, g, and b, which represent, an RGB color, and each of r, g, and b are in the range 0..colormode, where colormode is either 1.0 or 255 - pencolor(r, g, b) r, g, and b represent an RGB color, and each of r, g, and b are in the range 0..colormode If turtleshape is a polygon, the outline of that polygon is drawn with the newly set pencolor. Example (for a Turtle instance named turtle): >>> turtle.pencolor('brown') >>> tup = (0.2, 0.8, 0.55) >>> turtle.pencolor(tup) >>> turtle.pencolor() '#33cc8c' NrW)rrErVr)rr r9rrrrWs z TPen.pencolorcGsO|r;|j|}||jkr(dS|jd|n|j|jSdS)a] 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) NrA)rrFrVr)rr r9rrrrAs zTPen.fillcolorcCs|jdddS)zMakes the turtle visible. Aliases: showturtle | st No argument. Example (for a Turtle instance named turtle): >>> turtle.hideturtle() >>> turtle.showturtle() shownTN)rV)rrrrros zTPen.showturtlecCs|jdddS)aYMakes 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() rQFN)rV)rrrrrK szTPen.hideturtlecCs|jS)zReturn 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 )rD)rrrrrO s zTPen.isvisiblecKsi |jd6|jd6|jd6|jd6|jd6|jd6|jd6|jd6|jd 6|j d 6|j d 6}|p}|s|St |t r|}ni}|j |i}x|D]}||||>> 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} rQrXrWrArYrpra stretchfactorrnr'rsrVFTN)rDrGrErFrCrHr?rIrJrMrKrdictr,r$rzrr_newLinerrrrrrLr5)rrVZpendictZ_pdpZ_p_bufrZnewLineZsfZscxZscyZshfsacarrrrV s/                                    $ %#zTPen.penTcCsdS)z/dummy method - to be overwritten by child classNr)rusePosrrrrT sz TPen._newLineFcCsdS)z/dummy method - to be overwritten by child classNr)rr|Zforcedrrrr5 sz TPen._updatecCsdS)z/dummy method - to be overwritten by child classNr)rr rrrr sz TPen._colorcCsdS)z/dummy method - to be overwritten by child classNr)rr rrrr szTPen._colorstr)rrrrrrr@rarYrZrXrNrpr9rWrArorKrOrVrTr5rrrzryr]rUr=rqrMrrrrr>s8     & . % $    r>c@s.eZdZdZddZddZdS) _TurtleImagez6Helper class: Datatype to store Turtle attributes cCs#||_d|_|j|dS)N)rrY _setshape)rr shapeIndexrrrr s  z_TurtleImage.__init__cs_|j||_|jdko6j|jknr?dS|jdkocj|jknrldS|jdkrj|jn3|jdkrx!|jD]}j|qWnj|j|_|jdkrj|_nf|jdkr#jjdj|_n8|jdkr[fddj|jD|_ndS)NrmrTrnrcsg|]}jqSr)r()rZr3)rrrr\ s z*_TurtleImage._setshape..)zimagezpolygon) rr[rYrr4_itemr(rUrq)rr[r3r)rrrZ s&  ))z_TurtleImage._setshapeN)rrrrrrZrrrrrY s  rYc@seZdZdZgZdedededddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ ddddZddZddZddZddZdd d!Zdddd"d#Zdd$d%Zd&d'Zdd(d)Zd*d+Zddddd,d-Zd.d/Zd0d1Zd2d3d4Zd5d6Zd7d8Zd9d:Zd;d<Z dd=d>Z!d?d@Z"dAdBZ#dCdDZ$dEdFdGZ%dHdIZ&dJdKZ'dLdMZ(ddNdOZ)dPdQZ*d2dRdodVdWZ+dXdYZ,dZd[Z-d\d]Z.d^d_Z/d`daZ0e0Z1ddbdcZ2ddddedfZ3ddddgdhZ4ddddidjZ5dkdlZ6dmdnZ7eZ8dS)pr zvAnimation part of the RawTurtle. Puts RawTurtle upon a TurtleScreen and provides tools for its animation. NrkrrcCst|tr||_nt|trX|tjkrLtjj|n||_nzt|ttfrxbtjD]"}|j |krw||_PqwqwWt||_tjj|jnt d||j}t j ||j tj ||jj||j|_t|||_d|_d|_d|_|_||_d|_|j|_|jg|_|jg|_g|_||_t ||_!|j"dS)Nzbad canvas argument %sF)#r_Screenrrr screensr)rrr"rlrrrr>rr1drawingLineItemrYr_poly _creatingPoly _fillitem _fillpathrD_hidden_from_screencurrentLineItemr% currentLiner stampItems_undobuffersizerur$r5)rZcanvasrkrrrrrrr s@           zRawTurtle.__init__cCs<tj|tj||j|j|jdS)aDelete 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 N)rr`r>r@_clearrr5)rrrrr` s     zRawTurtle.resetcCs7|dks|dkr$d|_nt||_dS)aSet 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) Nr)r$ru)rsizerrrrh s zRawTurtle.setundobuffercCs |jdkrdS|jjS)zReturn count of entries in the undobuffer. No argument. Example (for a Turtle instance named turtle): >>> while undobufferentries(): ... undo() Nr)r$r})rrrrrx+ s zRawTurtle.undobufferentriescCsd|_|_x!|jD]}|jj|qW|jj|_g|_|jrn|jj |j n|jg|_|j |j |j dS)zDelete all of pen's drawingsN)rbrcrrr4r1rerfrGr)r%r7rhrh)rr3rrrri8 s   zRawTurtle._clearcCs|j|jdS)agDelete 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() N)rir5)rrrrr5F s zRawTurtle.clearcCsd|jj|jjdkr#dSt|jdkr`|jj|j|j|j|jndS)Nrr) rrrr^rfr2rerErC)rrrrrU s  zRawTurtle._update_datacCs|j}|jdkrdS|jdkr\|j|j|j|j|jnG|j|jdkrx|jD]}|jqW|jndS)z&Perform a Turtle-data update. rNr) rrrrr5r7rrr+)rrrRrrrr5] s     zRawTurtle._updatecCs|jj||S)amTurns 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 )rr*)rZflagrrrrr9o szRawTurtle._tracercCs|jj|S)N)rr)rr rrrr szRawTurtle._colorcCs|jj|S)N)rr)rr rrrr szRawTurtle._colorstrc Cst|tr|Sy|\}}}Wntdt|YnX|jjdkrdd|||fD\}}}nd|kodknod|kodknod|kodknstdt|nd|||fS) z,Convert colortriples to hexstrings. zbad color arguments: %sg?cSs g|]}td|qS)go@)r )rZrrrrr\ s z!RawTurtle._cc..rrzbad color sequence: %sz #%02x%02x%02x)rrrlrr)rr rrrrrr_cc s(Tz RawTurtle._cccsC|j|j|j|j}d|_d|_t|}|_||_|_t|jj|_jj|j |jjj }|dkrj |j_ nl|dkrj j dj|j_ n>|dkr&fddj |jjjD|j_ nj|_|j|S)aCreate 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() NrmrTrrncsg|]}jqSr)r()rZr3)rrrr\ s z#RawTurtle.clone..)rrTrGrrrYr[rr)rrYr(r\rUrqr1rer5)rrqttyper)rrr8 s,          " # zRawTurtle.clonecCs\|dkr|jjS||jjkr>td|n|jj||jdS)aSet 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' NzThere is no shape named %s)rr[rrrlrZr5)rr rrrrk s   zRawTurtle.shapecCs||ko"|ko"dknrF|j\}}|||jfS|dks^|dkrmtdn|dk r|dkr||f}q||f}n+|dk r|jd|f}n |j}|dkr|j}n|jddd|d|dS)aOSet/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) Nrz(stretch_wid/stretch_len must not be zerorarOrRr')rIrMrlrV)rZ stretch_widZ stretch_lenr'rRrrrrl s '      zRawTurtle.shapesizecCs-|dkr|jS|jddd|dS)aSet 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 NrarOrn)rJrV)rZshearrrrrn s zRawTurtle.shearfactorcCsK| |j|j}|tjddtj}|jddd|dS)aIRotate 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). Examples (for a Turtle instance named turtle): >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.settiltangle(45) >>> stamp() >>> turtle.fd(50) >>> turtle.settiltangle(-45) >>> stamp() >>> turtle.fd(50) gf@rrarOrsN)r+r#rrrV)rrrsrrrrg szRawTurtle.settiltanglecCsK|dkr:|j dtj|j}||j|jS|j|dS)aSet 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). Deprecated since Python 3.1 Examples (for a Turtle instance named turtle): >>> turtle.shape("circle") >>> turtle.shapesize(5,2) >>> turtle.tilt(45) >>> turtle.tiltangle() Ngf@)rKrrr#r+r*rg)rrrsrrrrt3 s zRawTurtle.tiltanglecCs|j||jdS)aRotate 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) N)rgrt)rrrrrrsM szRawTurtle.tiltcCs||ko-|ko-|ko-dknr9|jS|j\}}}}|dk rc|}n|dk rx|}n|dk r|}n|dk r|}n||||dkrtdn||||f|_tj| |dtj} tj| tj| } } | || || || || || || || |f\} } }}| |f|_| ||_| |_ |j dddS)aSet 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) Nrz0Bad shape transform matrix: must not be singularrrarO) rLrlrr3rrrrIrJrKrV)rt11t12t21t22Zm11Zm12Zm21Zm22ZalfarVrWZa11Za12Za21Za22rrrrm` s,2    0  zRawTurtle.shapetransformcs|j|j\|j\tjj}dt||\fdd|DS)zlComputes transformed polygon shapes from a shape according to current position and heading. g?csQg|]G\}}||j ||jfqSr)r#r$)rZrr)e0e1p0p1rrrr\ s z(RawTurtle._polytrafo..)rr%r'rr$r#r2)rrser)rrrsrtrurr _polytrafo s zRawTurtle._polytrafocCsE|jj|jj}|jdkrA|j|j|jdkSdS)a@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)) rmrnN)rrrr[rY _getshapepolyrq)rrkrrrrG s zRawTurtle.get_shapepolyFcs|jdks|r-|j\nY|jdkrstd|jd}|dd|f\n|jdkr|Stfdd|DS) z`Calculate transformed shape polygon according to resizemode and shapetransform. rOrNrg@rrcs:g|]0\}}||||fqSrr)rZrr)rnrorprqrrr\ s z+RawTurtle._getshapepoly..)r?rLmaxrCr)rrmrnr<r)rnrorprqrrx s!zRawTurtle._getshapepolyc Csd|j}|j|jj}|j}|jj}|jr|jdkr|jdkrd|_ |j }|dkr|j dkrd}n$|j dkr|j }n |j }|j|j|}|j|j}}|j||d|d|d |d d q`|d kr-|j||j|q`|d kr`xt||D]m\} \} }}|j|j| d } |j| | d|j|d|j|d |j d d qIWq`n|j rdS|dkr|j|dddne|d kr!|j||j|jdj n6|d krWx'|D]} |j| dddq4Wnd |_ dS)zpManages the correct rendering of the turtle with respect to its shape, resizemode, stretch and tilt etc.rFrmrrrNrr'rzr.TrTrnNrrrrrrrr)rzr{r|rrrrrr)r}r~r)rrrr[rYr\rDrrrdrqr?rCrMrwrxrFrEr0rWr%ziprk) rrrkrmZtitemtshaper%fcocr3rsrrrr sF   '        %)     zRawTurtle._drawturtlec Cs|j}|j|jj}|j}|j}|dkr|j}|jdkr^d}n$|jdkry|j}n |j }|j |j |}|j |j }}|j||d|d|d|dd n|d kr |jd }|j||j|n|d krg}x'|D]} |j} |j| q%Wt|}xt||D]m\} \} }}|j |j | d } |j| | d|j|d|j|d|j dd qdWn|jj||jjd |f|S)aStamp 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) rmrrrNrr'rzr.TrTrrnrr)rrrr[rYrqr(r?rCrMrwrxrFrEr0rUrWr%r)rrrkrgr$rz) rrrkrmrstitemr%rrelementr3rsrrrrr s>             %&zRawTurtle.stampcCs||jkret|trBx1|D]}|jj|q%Wn|jj||jj|nd|f}|j}||jkrdS|jj|}|jj|||j kr|j d|j |_ n|jj |j d|j dgdS)z9does the work for clearstamp() and clearstamps() rrNr) rgrrrr4rr$rwindexrxrvinsert)rstampidZsubitemr3Zbufrrrr _clearstamp s   zRawTurtle._clearstampcCs|j||jdS)aDDelete 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) N)rr5)rrrrrr6 s zRawTurtle.clearstampcCs|dkr"|jdd}n5|dkrD|jd|}n|j|d}x|D]}|j|q^W|jdS)aDelete 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() Nr)rgrr5)rrZtoDeleter3rrrr7, s   zRawTurtle.clearstampsc Csr|j|j|jt|jtf}|j}d|j|||j|j dd|j |j|j ddff}|j r|j j |n|j}|jr|jdkr||}|d|jd|d|jd}dt|ddd|j|j}|d |} xtd|D]s} | dkrOd } nd } || | |_|jr|j|j||jf|j|j| n|jq4W|jr|j|jdd d d|jqn|jr|j j|nt|jtr|jj|n||_|jrB|jj|nt|j dkrd|jn|jdS)zMove the pen to the point end, thereby drawing a line if pen is down. All other methods for turtle movement depend on this one. goNrrrg?rg?g?TFrrrz*rrrr)rr)rGrErCrrcrrr%rerfr`rr$rzrHrr#r$rr]r2r_r5r)rar`r^rT) rr1go_modesrZ undo_entrystartdiffdiffsqnhopsdeltarr.rrrr.H sR    (*          zRawTurtle._gotocs|\}}}}|\}}}} |\} } } |jt|j|dkretdn| |_| |_| ddgkrd} n|} j| | d| d|fdd|jD}x+|D]#}j||jj |qW|}|j r2j d kr2||}|dj d |d j d }d t|dd d |j |j }|d |}x{td |D]j}|d krd}nd}||||_|rj|j||jf|||n|jqW|r2j|jdddd|q2n||_|jrt|jdkri|jjn|jgkrd|_d|_qn| r|jgkrd|_tdq|jdk r|jjqn|jdS)z)Reverse a _goto. Used for undo() g?z$undogoto: HALLO-DA-STIMMT-WAS-NICHT!rrrrzcs7g|]-}|krj|dkr|qS)r)rY)rZr[)rrrrr\ s z'RawTurtle._undogoto..rrrg?g?TFNzUnwahrscheinlich in _undogoto!)rr)rrrrrr)rr)rr2r%rrerfr2rr4rrHrr#r$rr]r_r5rar^r`r{rc)rentryoldnewrZcoodataZdrawingZpcZpsrBZcLIZcLr_ZusepcZtodeleter[rrrrrrr.r)rrr _undogoto} sb        (*         zRawTurtle._undogotocCs|jr(|jjd||jfn||j9}|jj|}|jj}|dkr|jdkrd|j}dtt ||}d||}x6t |D]%}|jj||_|j qWn||_|j dS)z&Turns pen clockwise by angle. rotrrg@g?N) r$rzr+r'rrrrHrr2r]r5)rrZ neworientrZanglevelr;rrrrrr0 s     zRawTurtle._rotateTcCst|jdkrb|jj|j|j|j|j|jj|_|jj |jn|jj|jddg|_|r|j g|_ndS)zCloses current line item and starts a new one. Remark: if current line became too long, animation performance (via _drawline) slowed down considerably. rr.TN) r^rfrr2rerErCr1rr)r%)rrXrrrrT s zRawTurtle._newLinecCst|jtS)aReturn 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) )rrcr)rrrrrB s zRawTurtle.fillingcCs|js4|jj|_|jj|jn|jg|_|j|j rr|j j d|jfn|j dS)a 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() beginfillN) rBrr(rbrr)r%rcrTr$rzr5)rrrrr1 s   zRawTurtle.begin_fillcCs|jrt|jdkrk|jj|j|jd|j|jrk|jjd|jfqknd|_|_|j ndS)a 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() rrdofillN) rBr^rcrr0rbrFr$rzr5)rrrrr> s   zRawTurtle.end_fillc Gs|stt|ttfrF|j|}|jt|jd}q|j}|s|jt|jd}qn7|dkr|jt|jd}n|j|}t|jdr |jj |j ||}|j j ||j r|j jd|fqn|j}|j rD|j jdgd|j _nzT|jdkrf|jn|j|j||j||jdWd|j|X|j rd |j _ndS) aDraw 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) rN_dotr<r6TrNrF)rrrrrCryrEhasattrrrr%rr)r$rzrVryrarMrXrYrWrC)rrjr9r3rVrrrr< s:          z RawTurtle.dotcCs`|jj|j||||j\}}|jj||jr\|jjd|fn|S)z)Performs the writing for write() wri)rrBr%rErr)r$rz)rr@rAr?r3r1rrrrBG s  zRawTurtle._writerPArialrrPcCs|jr+|jjdgd|j_n|jt||j|}|rw|j\}}|j||n|jrd|j_ndS)aWrite 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) r6TFN)r$rzryrBrror[re)rargZmoverAr?r1rrrrrr{Q s ! zRawTurtle.writecCs|jg|_d|_dS)aStart 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() TN)r%r`ra)rrrrr2n s zRawTurtle.begin_polycCs d|_dS)a7Stop 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() FN)ra)rrrrr?| s zRawTurtle.end_polycCs |jdk rt|jSdS)zReturn the lastly recorded polygon. No argument. Example (for a Turtle instance named turtle): >>> p = turtle.get_poly() >>> turtle.register_shape("myFavouriteShape", p) N)r`r)rrrrrD s zRawTurtle.get_polycCs|jS)aReturn 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 >>> ts.bgcolor("pink") )r)rrrrrF szRawTurtle.getscreencCs|S)aUReturn the Turtleobject itself. No argument. Only reasonable use: as a function to return the 'anonymous turtle': Example: >>> pet = getturtle() >>> pet.fd(50) >>> pet >>> turtles() [] r)rrrrrH szRawTurtle.getturtlecCs|jj|S)zDSet delay value which determines speed of turtle animation. )rr)rrrrrr7 szRawTurtle._delayrcCs-|jj|jj||||jdS)aBind 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. num -- 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 N)rrKrr\r5)rrErrJrrrrR szRawTurtle.onclickcCs-|jj|jj||||jdS)aBind 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. num -- 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. N)rrLrr\r5)rrErrJrrrrT szRawTurtle.onreleasecCs#|jj|jj|||dS)aBind 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. num -- 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). N)rrMrr\)rrErrJrrrrS szRawTurtle.ondragcCs|jdkrdS|dkrV|\}}|j| ||j|jj}n>|dkr||d}|j|n|dkr|j|n|dkr|d}|jj||jj |n|dkr |d}|jj |dd d d d n|d krd|d}d|_ |_ ||jkr|jj||jj |qn0|d krt j||d|jjndS)z2Does the main part of the work for undo() Nrrrrrrr<rrrr'rrV)zwrizdotrrrrrr)rrr)r$r0r+r{r6rrr4rrr0rbrcr>rV)ractionrrrZdegPAUZdummyrr3rrr_undos8            zRawTurtle._undocCs|jdkrdS|jj}|d}|dd}|dkrxG|r~|j}|j|d|ddqKWn|j||dS)aundo (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() ... Nrrr6)r$r{r)rr3rrrrrrrw&s    %zRawTurtle.undo)rrznormal)9rrrrr^rrr`rhrxrir5rr5r9rrrkr8rkrlrnrgrtrsrmrwrGrxrrrrr6r7r.rr0rTrBr1r>r<rBr{r2r?rDrFrHrEr7rRrTrSrrwrvrrrrr sp %          ((  (  ( -   5 A    0     cCs%tjdkrtt_ntjS)zReturn the singleton screen object. If none exists at the moment, create a new one and return it, else return the existing one.N)r _screenr]rrrrr Isc@seZdZdZdZedZddZededededd d Zd d Z d dZ ddZ ddZ dS)r]Nr)cCstjdkrKtt_|_|jjtj|jj|jntjdkrtd}td}td}td}td}td}|jj |||||jj t_t j |tj|j ||||ndS)Nrzrrrrr)r]_rootrr)_titler_destroyrrrrrrr&)rrzrrrrrrrrrWs      z_Screen.__init__rzrrrcCst|jdsdS|jj}|jj}t|trld|koZdknrl||}n|dkr||d}nt|trd|kodknr||}n|dkr||d}n|jj|||||jdS)a  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 rNrrr)rrrrrrrr,)rrzrrrr;Zshrrrr&ms+  +  z _Screen.setupcCs/tjdk r"tjj|n|t_dS)aqSet 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!") N)r]rr)r)rZ titlestringrrrr)s z _Screen.titlecCsV|j}|tjkr?dt_dt_dt_dt_ndt_|jdS)NT) rr]r rrrrrr)rrootrrrrs      z_Screen._destroycCs|jdS)z~Shut the turtlegraphics window. Example (for a TurtleScreen instance named screen): >>> screen.bye() N)r)rrrrrsz _Screen.byec s[fdd}j|tdr-dSy tWntk rVtdYnXdS)alGo 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() csjdS)z&Screen.bye() with two dummy-parametersN)r)rr)rrrexitGracefullysz+_Screen.exitonclick..exitGracefullyrNr)rRrrAttributeErrorexit)rrr)rrrs    z_Screen.exitonclick) rrrrrrrrr&r)rrrrrrrr]Qs   '  r]c@sCeZdZdZdZdZedededddZdS)r zRawTurtle 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. Nrkrrc CsGtjdkrtt_ntj|tjd|d|d|dS)Nrkrr)r rr r r)rrkrrrrrrs zTurtle.__init__)rrrrrrrrrrrrr s cCs%tjdkrtt_ntjS)z5Create the 'anonymous' turtle if not already present.N)r rrrrr_getpensrcCs%tjdkrtt_ntjS)z-Create a TurtleScreen if not already present.N)r rr rrrr _getscreensrZturtle_docstringdictc CsBi}x+tD]#}d|}t|j||.py It is intended to serve as a template for translation of the docstrings into different languages. z_Screen.zTurtle.z%s.pyr%cSs/g|]%}|jddtkr|qS)rr)r _alias_list)rZrrrrr\s z'write_docstringdict..zdocsdict = { Nrz%s : z """%s """, z """%s """ z} rr) _tg_screen_functionsrr_tg_turtle_functionsrrrr{reprclose)rdocsdict methodnamerrrrrrr~s$        c Csqdi|jd6}t|}|j}x>|D]6}y||t|_Wq3td|Yq3Xq3WdS)zRead 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. z!turtle_docstringdict_%(language)srzBad docstring-entry: %sN)ro __import__rrrr)Zlangmodnamemodulerrrrrread_docstringss   rzCannot find docsdict forz;Unknown Error when trying to import %s-docstring-dictionaryc CsBd}}tj|j\}}}|dd}|dd}|jpQg}dd|D}dgt|t||}ddt||D} |dk r| jd||jd|n|dk r| jd||jd|nd j| }d |}d j|}d |}||fS) a?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. rrNcSsg|]}d|fqS)z=%rr)rZrrrrr\Hs z"getmethparlist..cSs g|]\}}||qSrr)rZrZdfltrrrr\Js *z**z, z(%s))inspectZgetargs__code__ __defaults__r^rr)r) obZdefTextZcallTextr ZvarargsZvarkwZitems2ZrealArgsZdefaultsZitems1rrrgetmethparlist8s& !    rcCseddl}|dkrdStd}|jd|d}|jd|}|jd|}|S)z>>>>>z6def %(key)s%(pl1)s: return _getscreen().%(key)s%(pl2)srpl1pl2zTurtle.z3def %(key)s%(pl1)s: return _getpen().%(key)s%(pl2)s__main__cCstrtntdS)N)rNr]rUrrrr switchpens  rcCsttdttdttdxtdD]}|dkr\tnx(tdD]}tdt dqiW|dkrt dt nttd tq@Wtd t d td tt dtdt dtdt d tt dd t dd t dx<tdD].}tdt dtdt dqRWtdtx<tdD].}tdt dtdt dqWt dS)zDemo of old turtle.py - moduleTdrrrr ZZmaroonrrrFZ startstartrredrN)r`r*ryr0r=rzr]r1rCrPr9r>r_r{)r[rrrrdemo1sX                             rcCsLtdttdttddtddd}tdx(tdD]}tt |dqXWt dxt rt qWt tdtd d}td tdtd xtd-d D]}|dkrttd d|dd|nx(tdD]}t|tdq+Wt|d7}tdttddqWtdttdtdttddtdtx?tdD]1}t ddtdtdtdqWttdttdttdt}|jdt}|jd|jd|j |jd|jd|j|jdd|jd|j|jd|jdd|jd |jdtt|d}x|j|dkr|jd|jd|j|j||jd|d dkr|j |j tn|d7}qW|j d!d"d.d%d&|jd'|jdd(d)}t!j"d x!t r|j |j qW|jd|j d*d"d/|j#|dd,S)0zDemo of some new features.rrrg@rrzwait a moment...rZgreenrrrx FrrZyellowr2rrNi(rZblueZorangeg @g333333?r zCAUGHT! r?rboldrAr_rcSsttdS)N)rr)rrrrrbabaszdemo2..babaz Click me!CourierNr)zArialrr)rrr)$rprqrYrdrur;rbr]rr4r{rxrwr`rQrrWr1rAr@r>r]rUr9rkrHrar rPryrIr=rrtimeZsleeprR)r:rZlaenger[Ztrirr|rrrrdemo2s                                                     r)LrZ_verZtkinterrrrrrros.pathrrrcopyrrZ _tg_classesrrZ _tg_utilities__all__rrrrrrrrrrrrrrrrobjectr Exceptionrrlrrurrr>rYr r r r]r r rrr~rZ _LANGUAGE ImportErrorrrrrrrrZdefstrrrrrrrrrrrrres               4 c  /&,y   "          &   &   5 c