U e5dd1O@s6dZdZddlZddlZddlZddlZddlZddlZddl 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;dd?d@dAdBdCdDdEdFdGdHdIdJdKdLdMdNdOdPdQdRdSdTdUdVdWdXdYdZd[d\d]d^d_d`dadbdcdddedfdgdhdidjdkdldmdndodpdqdrdsdtdudvdwdxdydzd{d|d}gOZd~dgZeeeedgZdd0d3d@dMdQdUd[d]dbdcdedfdqdvdydzgZdddddddddddddddddddddZddZddZz eeWnek r edYnXGdddeZddZddZdZdddZ Gdddej!Z"e e"ej#dGdddej$Z%ej#Z#Gddde&Z'GdddeZ(GdddeZ)Gddde&Z*Gddde&Z+Gddde'Z,Gddde&Z-Gddde&Z.Gddde&Z/Gdd d e.e-Z0e0Z1dd Z2Gddde,Z3Gdd d e0Z4e4Z5ddd~Z6ddZ7edZ8ze8dkrre7e8Wn@e9k rede8Yn"ek rede8YnXddZ:ddÄZ;ddńZe>ee3dde<e>ee4dde;e?Z@eAdkr2ddτZBddфZCddӄZDeCeDeEdS)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 Terminator?g?ii,standard? iclassicblacknoresizeTZenglishturtlescreenzPython Turtle GraphicsF)rzheight canvwidth canvheight leftright topbottomrrrundobuffersizerkrWrAravisiblelanguage exampleturtle examplescreenr) using_IDLEc Cst|d}|}W5QRXi}|D]}|}|r&|drBq&z|d\}}Wn(tk r|td||fYq&YnX|}|}|dkrt|}n4zd|krt|}nt |}Wntk rYnX|||<q&|S)z/Convert content of config-file into dictionary.r#=zBad line in config-file %s: %s)TrueFalseNonez''z"".) open readlinesstrip startswithr ValueErrorprintevalfloatint)filenamefZcfglinescfgdictlinekeyvaluer/usr/lib64/python3.8/turtle.py config_dicts0      rcCsd}i}i}t|rt|}d|kr0d|d}ztt\}}t||}Wntk rbd}YnXt|rtt|}t|t|dS)a@Read config-files, change configuration-dict accordingly. If there is a turtle.cfg file in the current working directory, read it from there. If this contains an importconfig-value, say 'myway', construct filename turtle_mayway.cfg else use turtle.cfg and read it from the import-directory, where turtle.py is located. Update configuration dictionary first according to config-file, in the import directory, then according to config-file in the current working directory. If no config-file is found, the default configuration is used. z turtle.cfgZ importconfigz turtle_%s.cfgN)rrr__file__r Exception_CFGr,)rZ default_cfgZcfgdict1Zcfgdict2headtailZ cfg_file2rrr readconfigs     rz"No configfile read, reason unknownc@s`eZdZdZddZddZddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ dS)raA 2 dimensional vector class, used as a helper class for implementing turtle graphics. May be useful for turtle graphics programs also. Derived from tuple, so a vector is a tuple! Provides (for a, b vectors, k number): a+b vector addition a-b vector subtraction a*b inner product k*a and a*k multiplication with scalar |a| absolute value of a a.rotate(angle) rotation cCst|||fSN)tuple__new__)clsxyrrrrsz Vec2D.__new__cCs"t|d|d|d|dSNrrselfotherrrr__add__sz Vec2D.__add__cCsDt|tr*|d|d|d|dSt|d||d|Sr) isinstancerrrrr__mul__s  z Vec2D.__mul__cCs2t|tst|tr.t|d||d|StSr)rrrrNotImplementedrrrr__rmul__szVec2D.__rmul__cCs"t|d|d|d|dSrrrrrr__sub__sz Vec2D.__sub__cCst|d |d Srrrrrr__neg__sz Vec2D.__neg__cCs|dd|dddS)Nrrrrrrrr__abs__ sz Vec2D.__abs__cCsjt|d |d}|tjd}t|t|}}t|d||d||d||d|S)z.rotate self counterclockwise by angle rrf@)rmathpicossin)rangleZperpcsrrrrotate sz Vec2D.rotatecCs|d|dfSrrrrrr__getnewargs__szVec2D.__getnewargs__cCsd|S)Nz (%.2f,%.2f)rrrrr__repr__szVec2D.__repr__N)__name__ __module__ __qualname____doc__rrrrrrrrrrrrrrrs cCsTt|j}||D]}t||q|jD]\}}t|tjkr0|||<q0dS)#helper function for Scrolled CanvasN) list __bases__reverse __methodDict__dict__itemstypetypes FunctionType)r_dictZbaseListZ_superrrrrrr!s  rcCsi}t|||S)r)rkeys)rrrrr __methods+s rzTdef %(method)s(self, *args, **kw): return self.%(attribute)s.%(method)s(*args, **kw)rc Csi}t||i}t|}|D]B}|dddksd|dddksd||ksd||krXq"||||<q"|D]D\}} || d} t|trt||d} t| | t||| |qndS)Nr_)methodfunc)rZ attribute) rrrrrstr __stringBodyexecsetattr) Z fromClassZtoClassZtoPartZexcludeZ_dict_1rZmfcZexrrdZ execStringrrr__forwardmethods5s  0    rc@sdeZdZdZdddZddd Zd d Zd d ZddZddZ ddZ ddZ ddZ ddZ dS)rzModeled after the scrolled canvas class from Grayons's Tkinter book. Used as the default canvas, which pops up automatically when using turtle graphics functions or the Turtle class. ^Xc Cs0tjj||||d||_|||_|_|||_|_d|_ tj ||||j tj dd|_ tj ||j jtjd|_tj ||j jd|_|j j|jj|jjd|jdd dd |jdd dd |j jd |d ddd d d d |jjd |d dd d d d d |jjd |d d dd d d d ||jd |jdS)N)rzrwhiter)rzrbgZreliefZ borderwidth)commandZorient)r)ZxscrollcommandZyscrollcommandrr)ZweightZminsizenewsZpadxZin_ZpadyrowcolumnZrowspanZ columnspanZstickyz )TKFrame__init__winfo_toplevelZ _rootwindowrzrrrrCanvasZSUNKEN_canvasZ ScrollbarZxviewZ HORIZONTALhscrollZyviewvscrollZ configuresetZ rowconfigureZcolumnconfiguregridr`bindonResize)rmasterrzrrrrrrrPsN    zScrolledCanvas.__init__NcCs|r ||_|r||_|r||_|jj||j d|j d|jd|jdfd|jd|j|jd|j|jd|j|jd|j| dS)zZ d?d@Z!dAdBZ"dCdDZ#dPdEdFZ$d S)QTurtleScreenBasezProvide 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. cCstjdd|jd}||S)z$return a blank image object r)rzrr)r PhotoImagecvblank)rZimgrrr _blankimageszTurtleScreenBase._blankimagecCstj||jdS)z`return an image object containing the imagedata from a gif-file named filename. )filer)rr-r.)rrrrr_imageszTurtleScreenBase._imagecCs||_t|tr"|jj}|jj}nJt|jd}t|jd}|jj| d| d|d|dfd||_||_d|_|_ dS)Nrzrrrr) r.rrrrrrr xscaleyscale)rr.whrrrrs  *zTurtleScreenBase.__init__cCs|jjddddS)zcs:j|jjj|j j}}||dSrr.canvasxrr4canvasyrr5rrrfunrrreventfunesz+TurtleScreenBase._onclick..eventfunr.Z tag_unbindZtag_bindrrHr_numaddr`rr^r_onclick\szTurtleScreenBase._onclickcsDdkrj|d|n$fdd}j|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. Nzcs:j|jjj|j j}}||dSrrZr]r^rrr`wsz-TurtleScreenBase._onrelease..eventfunrarbrr^r _onreleaseks zTurtleScreenBase._onreleasecsDdkrj|d|n$fdd}j|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. NzcsTz:j|jjj|j j}}||Wntk rNYnXdSr)r.r[rr4r\rr5rr]r^rrr`sz*TurtleScreenBase._ondrag..eventfunrarbrr^r_ondrag~s zTurtleScreenBase._ondragcs@dkrjd|n"fdd}jd|||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. NrYcs:j|jjj|j j}}||dSrrZr]r^rrr`sz1TurtleScreenBase._onscreenclick..eventfunr.rr)rr_rcrdr`rr^r_onscreenclicks zTurtleScreenBase._onscreenclickcs>dkr|jd|dnfdd}|jd||dS)z`Bind fun to key-release event of key. Canvas must have focus. See method listen Nzcs dSrrrr_rrr`sz0TurtleScreenBase._onkeyrelease..eventfunrhrr_rr`rrkr _onkeyreleases zTurtleScreenBase._onkeyreleasecsndkr4|dkr |jddqj|jd|dn6fdd}|dkrX|jd|n|jd||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 dSrrrjrkrrr`sz.TurtleScreenBase._onkeypress..eventfunrhrlrrkr _onkeypresss zTurtleScreenBase._onkeypresscCs|jdS)z=Set focus on canvas (in order to collect key-events) N)r.rrrrr_listenszTurtleScreenBase._listencCs(|dkr|j|n|j||dS)z?Install a timer, which calls fun after t milliseconds. rN)r.Z after_idlerKrr_trrr_ontimerszTurtleScreenBase._ontimercCs|jjdd|dS)z0Create and return image item on canvas. rimage)r.Z create_image)rrtrrr _createimageszTurtleScreenBase._createimagecCs<|\}}|j|||j| |jf|jj||ddS)zZConfigure image item as to draw image object at position (x,y) on canvas) rsN)r.r?r4r5 itemconfig)rrHr[rtrrrrr _drawimages zTurtleScreenBase._drawimagecCs |jj||d|j|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 .rsN)r.rvZ tag_lower)rrHrtrrr _setbgpicszTurtleScreenBase._setbgpiccCs |j|S)zQReturn 'line' or 'polygon' or 'image' depending on type of item. )r.rrGrrr_typeszTurtleScreenBase._typecs.|j|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.0irBrr sz/TurtleScreenBase._pointlist..rr)r.r?rangelen)rrHplrr}r _pointlists zTurtleScreenBase._pointlistcCs|jj||||fddS)Nr3)r.r )rsrx1sry1srx2sry2rrr_setscrollregionsz!TurtleScreenBase._setscrollregionc Cs||j}|D]h}t|j|}g}|rd|dd\}}|||||||dd}q&|jj|f|qdS)Nr)r.Zfind_allrr?r>) rZ xscalefactorZ yscalefactorrrHZ coordinatesZ newcoordlistrrrrr_rescales zTurtleScreenBase._rescalecCszt|jts|j|jfS||kr6|kr6dkrJnn|jj|jjfS|dk rX||_|dk rf||_|j|||dS)zaResize the canvas the turtles are drawing on. Does not alter the drawing window. N)rr.rrrr`rrrr_resizes  "zTurtleScreenBase._resizecCs@|j}|dkr|jd}|j}|dkr8|jd}||fS)z; Return the width and height of the turtle window. rrzr)r.rr)rrzrrrr _window_sizes    zTurtleScreenBase._window_sizecCs|jjdS)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)r.Ztkrrrrrrs zTurtleScreenBase.mainloopcCstj|||jdS)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:") )parent)rZ askstringr.)rr)promptrrrr(.s zTurtleScreenBase.textinputcCstj||||||jdS)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 input 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 initialvalueZminvalueZmaxvaluer)rZaskfloatr.)rr)rdefaultZminvalZmaxvalrrrr=s  zTurtleScreenBase.numinput)NNNF)NNNF)N)rN)rN)rN)rN)N)NNN)NNN)%rrrrr0r2rr:rCrDrErIrJrMrOrPrXrerfrgrirmrnrorrrurwrxryrrrrrrr(rrrrrr,sT            r,c@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. NrrrrrrrrrYsc@seZdZdZdS)TurtleGraphicsErrorzSome TurtleGraphics Error Nrrrrrrbsrc@s$eZdZdZdddZdddZdS) 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. NcCsz||_|dkr"t|trpt|}nN|dkrVt|trp|drpt|rpt |}n|dkrdg}n t d|||_ dS)Npolygonrt.gifcompoundzThere is no shape type %s) ryrrrrlowerendswithrrr2r_data)rZtype_datarrrrns     zShape.__init__cCs:|jdkrtd|j|dkr$|}|j|||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() rz Cannot add component to %s ShapeN)ryrrr>)rpolyr"r9rrr addcomponent~s zShape.addcomponent)N)N)rrrrrrrrrrrgs c@sDeZdZdZdddZdddZdd Zd d Zd d ZddZ dS)Tbufferz5Ring buffer used as undobuffer for RawTurtle objects.rcCs$||_dgg||_d|_d|_dS)NrF)bufsizebufferptrcumulate)rrrrrrszTbuffer.__init__NcCsD|dkr&t|jD]}dg|j|<qn||_dgg||_d|_dS)Nr)rrrr)rrr|rrrr`s z Tbuffer.resetcCsF|jdkrB|js0|jd|j|_||j|j<n|j|j|dSr)rrrrr>rGrrrpushs  z Tbuffer.pushcCsJ|jdkrF|j|j}|dkr"dSdg|j|j<|jd|j|_|SdSr)rrrrGrrrpops  z Tbuffer.popcCs|j|jdgSr)rrcountrrrr nr_of_itemsszTbuffer.nr_of_itemscCst|jdt|jS)N )rrrrrrrrszTbuffer.__repr__)r)N) rrrrrr`rrrrrrrrrs   rc@s"eZdZdZdZedededfddZdd Zd=d d Zd dZ d>ddZ ddZ ddZ d?ddZ ddZddZddZd@ddZdAdd Zd!d"Zd#d$Zd%d&Zd'd(Zd)d*Zd+d,ZdBd.d/Zd0d1ZdCd2d3ZdDd4d5ZdEd7d8ZdFd9d:ZdGd;d<ZeZ eZ!eZ"e Z#eZ$d S)HrzProvides screen oriented methods like setbg etc. Only relies upon the methods of TurtleScreenBase and NOT upon components of the underlying graphics toolkit - which is Tkinter in this case. Trrrc Cst||tddtddtddtddtddtddtd|d |_d d i|_||_||_td |_ g|_ | t j d kr|}|ddddd|ddddddS)Nr)rrrrr))r))rr)) )))rr))r)rr)rrrr)r)r)rr)rr)rr)rr)rr)rr)rr)rr)rr)r)Q#@Q@)Gz. @Q@)rr)rrr)Qr)Qr)Gz. r)Q#rr)rr)rr)rr)rr)gg$)rr)rr)rr)rr))rr)rr)rr)rr))rGz)rg'@)rr)rr)rrr)rrrt)Zarrowrr4ZsquareZtrianglerr/nopicrrdarwinZwmZ attributesrz-topmost10)r,rrr0_shapes_bgpics_mode _delayvaluer _colormode_keysr5sysplatformrZcall)rr.rrrZ rootwindowrrrrs&     zTurtleScreen.__init__cCstd|_td|_|d|d|_d|_d|_d|_g|_ | dd D]}| d |qP| d |j d d D]}|d || d |qzd t_d S) aqDelete all drawings and all turtles from the TurtleScreen. No argument. Reset empty TurtleScreen to its initial state: white background, no backgroundimage, no eventbindings and tracing on. Example (for a TurtleScreen instance named screen): >>> screen.clear() Note: this method is not available as function. rrallrrrrr)rrN)rrrrIru_bgpic _bgpicname_tracing_updatecounter_turtlesrrRrrrr _pen)rbtnrrrrr5s       zTurtleScreen.clearNcCs||dkr|jS|}|dkr*td|||_|dkrp||j d|j d|jd|jdd|_|_|dS)ahSet turtle-mode ('standard', 'logo' or 'world') and perform reset. Optional argument: mode -- one 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 %s)rrrr) rrrrrrr4r5r`rrrrrr s  zTurtleScreen.modecCs|dkr|dt||}t||}|\}}||d|d|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) rN) rrrr%r4r5rrrrr,)rZllxZllyZurxZuryZxspanZyspanZwxZwyZ oldxscaleZ oldyscalerrrrrrrr'-s            z TurtleScreen.setworldcoordinatescCsT|dkr2|dr(td||}qFtdnt|trFtd|}||j|<dS)aAdds a turtle shape to TurtleScreen's shapelist. Arguments: (1) name is the name of a gif-file and shape is None. Installs the corresponding image shape. !! Image-shapes DO NOT rotate when turning the turtle, !! so they do not display the heading of the turtle! (2) name is an arbitrary string and shape is a tuple of pairs of coordinates. Installs the corresponding polygon shape (3) name is an arbitrary string and shape is a (compound) Shape object. Installs the corresponding compound shape. To use a shape, you have to issue the command shape(shapename). call: register_shape("turtle.gif") --or: register_shape("tri", ((0,0), (10,10), (-10,10))) Example (for a TurtleScreen instance named screen): >>> screen.register_shape("triangle", ((5,-3),(0,5),(-5,-3))) Nrrtz;Bad arguments for register_shape. Use help(register_shape)r)rrrr2rrrr)rnamerkrrrr#Ts   zTurtleScreen.register_shapec Cst|dkr|d}t|trD||s0|dkr4|Stdt|z|\}}}Wn(ttfk rztdt|YnX|jdkrdd|||fD\}}}d|krd krnn.d|krd krnnd|krd ksntd t|d |||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: %sbad color arguments: %srcSsg|]}td|qSgo@roundr{rrrrr~sz*TurtleScreen._colorstr..bad color sequence: %s #%02x%02x%02x)rrrrOr TypeErrorrr)rr9rgbrrr _colorstrws   FzTurtleScreen._colorstrcsxdsStdkr.fdddD}n4tdkrVfddddD}n td tfd d |DS) Nrrcs"g|]}t||ddqS)rrrrzcstrrrr~sz'TurtleScreen._color..)rrrrcsg|]}dt|dqS)rr)r{r7rrrr~srzbad colorstring: %sc3s|]}|jdVqdS)rN)r)r{rrrr sz&TurtleScreen._color..)rrrr)rrrBr)rrr_colors    zTurtleScreen._colorcCs8|dkr|jS|dkr"t||_n|dkr4t||_dS)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) Nrr)rrr)rZcmoderrrrs  zTurtleScreen.colormodecCs$|jD]}||j|qdS)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`s  zTurtleScreen.resetcCs|jS)zReturn the list of turtles on the screen. Example (for a TurtleScreen instance named screen): >>> screen.turtles() [] )rrrrrr+szTurtleScreen.turtlescGs4|r||}nd}||}|dk r0||}|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)rrPrrrr9rrrrs   zTurtleScreen.bgcolorcCsB|dkr|jSt||_d|_|dk r0t||_|jr>|dS)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)rrrLrrrrs zTurtleScreen.delaycCs<tjsdt_t|jdkr8|jd7_|j|j;_dS)zIncrement update counter.TrrN)r_RUNNINGrrrrrrr _incrementudc s  zTurtleScreen._incrementudccCs<|j}d|_|D]}||q||_|dS)z'Perform a TurtleScreen update. TN)rr+ _update_data _drawturtlerJ)rtracingrqrrrr,s  zTurtleScreen.updatecCs |dS)z Return the width of the turtle window. Example (for a TurtleScreen instance named screen): >>> screen.window_width() 640 rrrrrrr.szTurtleScreen.window_widthcCs |dS)z Return the height of the turtle window. Example (for a TurtleScreen instance named screen): >>> screen.window_height() 480 rrrrrrr-&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|jS)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'] )sortedrrrrrrr;s zTurtleScreen.getshapesrcCs||||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. btn -- 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)rirr_rrdrrrrRFszTurtleScreen.onclickcCsF|dkr ||jkr6|j|n||jkr6|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>rmrr_rrrrrWs    zTurtleScreen.onkeycCsN|dkr ||jkr>|j|n|dk r>||jkr>|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>rnrrrrrus   zTurtleScreen.onkeypresscCs |dS)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)ro)rxdummyydummyrrrrs zTurtleScreen.listenrcCs|||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)rrrprrrr"szTurtleScreen.ontimercCsF|dkr|jS||jkr(|||j|<||j|j|||_dS)aFSet background image or return name of current backgroundimage. Optional argument: picname -- a string, name of a gif-file or "nopic". If picname is a filename, set the corresponding image as background. If picname is "nopic", delete backgroundimage, if present. If picname is None, return the filename of the current backgroundimage. Example (for a TurtleScreen instance named screen): >>> screen.bgpic() 'nopic' >>> screen.bgpic("landscape.gif") >>> screen.bgpic() 'landscape.gif' N)rrr2rxr)rZpicnamerrrrs  zTurtleScreen.bgpiccCs||||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 ;-) )rrrrrr%szTurtleScreen.screensize)N)N)N)NN)N)rN)N)NN)r)N)NNN)%rrrrrrrr5rr'r#rrrr`r+rr*rrr,r.r-rrrRrrrr"rr%r!r$rrr rrrrrsH ( "' #              c@sTeZdZdZeddeddedddZdZdZdZefdd Z d d Z dBd dZ ddZ dCddZ ddZddZddZddZddZddZd d!Zd"d#Zd$d%Zd&d'Zd(d)ZdDd*d+Zd,d-Zd.d/Zd0d1ZdEd2d3ZdFd4d5Zd6d7Zd8d9Z dGd:d;Z!dHdd?Z#dJd@dAZ$eZ%eZ&eZ'eZ(eZ)eZ*eZ+eZ,e Z-d S)K TNavigatorzRNavigation part of the RawTurtle. Implements methods for turtle movement. r)rrrrrrcCsB|j|_|j|_||_d|_|d|_||t |dSr) DEFAULT_ANGLEOFFSET _angleOffsetDEFAULT_ANGLEORIENT _angleOrientr undobufferr:rrr`rrrrrs zTNavigator.__init__cCstdd|_tj|j|_dS)zXreset turtle to its initial values Will be overwritten by parent class rN)r _positionrSTART_ORIENTATIONr_orientrrrrr`s zTNavigator.resetNcCsL|dkr|jS|dkrdS||_|dkr6d|_d|_n|jd|_d|_dS)z:Set turtle-mode to 'standard', 'world' or 'logo'. Nr)rrrr@r)rrr _fullcirclerrrrrs zTNavigator._setmodecCs0||_d||_|jdkr"d|_n |d|_dS)z+Helper function for degrees() and radians()ihrrrN)r _degreesPerAUrrrZ fullcirclerrr_setDegreesPerAUs   zTNavigator._setDegreesPerAUv@cCs||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. Default 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 r rrrr:szTNavigator.degreescCs|dtjdS)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 rrrrrrr^5s zTNavigator.radianscCs|j|j|}||dS)z)move turtle forward by specified distanceN)rr_goto)rr;Zenderrr_goCszTNavigator._gocCs||j9}|j||_dS)z=Turn turtle counterclockwise by specified angle if angle > 0.N)r rrrrrrr_rotateHs zTNavigator._rotatecCs ||_dS)zmove turtle to position end.Nr)rendrrrr MszTNavigator._gotocCs||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) Nrrr;rrrrCQszTNavigator.forwardcCs|| 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) Nrrrrrr/hszTNavigator.backcCs|| 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 Nrrrrrr_|szTNavigator.rightcCs||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 NrrrrrrPszTNavigator.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) rrrrrr[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 rrrrrrr|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 rrrrrrr}s zTNavigator.ycorcCs,|dkr|t|n|t||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)rrrrrrrIszTNavigator.gotocCs|dd|ddS)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)rIrdrrrrrLs zTNavigator.homecCs|t||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) rNr rr)rrrrrriszTNavigator.setxcCs|t|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) rNr)rrrrrrjszTNavigator.setycCsT|dk rt||}t|tr"|}n$t|tr6t|}nt|trF|j}t||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)rrrrrabs)rrrr[rrrr;%s     zTNavigator.distancecCs|dk rt||}t|tr"|}n$t|tr6t|}nt|trF|j}||j\}}tt||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 Nrrr ) rrrrrrratan2rr rrr)rrrr[resultrrrruEs       zTNavigator.towardscCsJ|j\}}tt||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 rrr ) rrrrrr rrr)rrrrrrrrJhs   zTNavigator.headingcCs>|||j}|j}||d||d}||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 @N)rJrrr)rZto_anglerZfullrrrrdwszTNavigator.setheadingc Csp|jr|jdgd|j_|}|dkr2|j}|dkrjt||j}dttdt|dd|}d||}d |}d |t |tj d |j }|d kr| | | }}}| } | } |d kr| d d n |d ||t|D].} |||||d ||q|| |d krR| | | |||jrld |j_dS)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@rrrrrF)rrrrprrrminrrrr _tracerrMrrr) rradiusZextentstepsrpZfracr6Zw2lZtrZdlr|rrrr4s>" "          zTNavigator.circlecCsdSz/dummy method - to be overwritten by child classNr)rrrrrrpszTNavigator.speedcCsdSr"r)rarrrrrszTNavigator._tracercCsdSr"r)rrrrrrMszTNavigator._delay)N)r )N)N)N)NN)r)NN)N).rrrrrrZ DEFAULT_MODErrrr`rr r:r^rrr rCr/r_rPr[r|r}rIrLrirjr;rurJrdr4rprrMr@r3r0rbrQr\rerfrcrrrrrsZ     # # A   rc@seZdZdZedfddZededfddZd.d d Zd/d d ZddZ ddZ ddZ d0ddZ ddZ ddZddZddZddZd d!Zd1d"d#Zd2d%d&Zd3d(d)Zd*d+Zd,d-ZeZe Ze Ze Ze ZeZeZd S)4TPenzFDrawing part of the RawTurtle. Implements drawing properties. racCs||_d|_t|dSr) _resizemoderr$_reset)rrarrrrsz TPen.__init__rWrAcCsFd|_d|_||_||_d|_d|_d|_d|_d|_d|_ d|_ dS)NrTr)rrr)rrrr) _pensize_shown _pencolor _fillcolor_drawing_speed_stretchfactor _shearfactor_tilt _shapetrafo _outlinewidth)rrWrArrrr&sz TPen._resetNcCs.|dkr|jS|}|dkr*|j|ddS)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' N)autouserrra)r%rrV)rZrmoderrrras zTPen.resizemodecCs|dkr|jS|j|ddS)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 N)rY)r'rV)rrzrrrrYsz 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() NFrXr+rVrrrrrZ0s 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() NTr5r6rrrrrX>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 )r+rrrrrNLs z TPen.isdowncCsjdddddd}|dkr|jS||kr0||}n*d|krDd krVnntt|}nd}|j|d dS) 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) rrrrr)ZfastestZfastnormalZslowZslowestNrg%@)rp)r,rrrV)rrpZspeedsrrrrp[s z TPen.speedcGs|rht|}|dkr"|d}}n"|dkr4|\}}n|dkrD|}}||}||}|j||dn||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 more 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') rrrr)rWrAN)rrrVrr)r*)rrr!ZpcolorZfcolorrrrr9s    z TPen.colorcGs:|r*||}||jkrdS|j|dn ||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' N)rW)rr)rVrrrrrrWs   z TPen.pencolorcGs:|r*||}||jkrdS|j|dn ||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) N)rA)rr*rVrrrrrrAs   zTPen.fillcolorcCs|jdddS)zMakes the turtle visible. Aliases: showturtle | st No argument. Example (for a Turtle instance named turtle): >>> turtle.hideturtle() >>> turtle.showturtle() TshownNrVrrrrros 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() Fr8Nr: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 )r(rrrrrO s zTPen.isvisiblec Ks|j|j|j|j|j|j|j|j|j|j |j d }|s>|s>|St |t rN|}ni}| |i}|D]}||||<qd|jr|jd|fd}d|kr|j|dkrd}d|krt |dtr||df|d<|j|dkrd}d|kr|j|dkrd}|r|d|kr&|d|_d|kr:|d|_d|krN|d|_d|krt |dtr|||df|d<|d|_d |kr|d |_d |kr|d |_d |kr|d }t |ttfr||f}||_d |kr|d |_d |kr|d |_ d|kr|d|_d|kr.|d|_ d |ksLd|ksLd |kr|j\} } |j} t|j t|j } } | | | | | | | | | | | | f|_|dS)aLReturn 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} ) r9rXrWrArYrpra stretchfactorrnr9rsrVFrXTrWrYrArprar;rnr9r9rsN)r(r+r)r*r'r,r%r-r.r1r/rdictr,rrrr_newLinerrrrrr0rJ)rrVZpendictZ_pdpZ_p_bufrZnewLineZsfZscxZscyZshfsacarrrrV! s/                          zTPen.penTcCsdSr"rrZusePosrrrr= sz TPen._newLineFcCsdSr"r)rrZforcedrrrrJ sz TPen._updatecCsdSr"rrrrrr sz TPen._colorcCsdSr"rrrrrr szTPen._colorstr)N)N)N)N)T)TF)rrrrrrr&rarYrZrXrNrpr9rWrArorKrOrVr=rJrrrzryr]rUr=rqrMrrrrr$s:    &.%$    r$c@s eZdZdZddZddZdS) _TurtleImagez6Helper class: Datatype to store Turtle attributes cCs||_d|_||dSr)rry _setshape)rr shapeIndexrrrr sz_TurtleImage.__init__cs|j||_|jdkr*j|jkr2nndS|jdkrPj|jkrXnndS|jdkrp|jn |jdkr|jD]}|qj|j|_|jdkr|_nF|jdkrԈjdj|_n&|jdkrfddj|jD|_dS)Nrrt)rtrrr/csg|] }qSrr:r{rHrrrr~ sz*_TurtleImage._setshape..) rrDryrrI_itemr:rur)rrDrHrrGrrC s(""          z_TurtleImage._setshapeN)rrrrrrCrrrrrB srBc@seZdZdZgZdedededfddZdd Zd d Zd d Z ddZ ddZ ddZ ddZ dmddZddZddZddZddZdnd d!Zdod"d#Zdpd$d%Zd&d'Zdqd(d)Zd*d+Zdrd,d-Zd.d/Zd0d1Zdsd3d4Zd5d6Zd7d8Zd9d:Zd;d<Z dtd=d>Z!d?d@Z"dAdBZ#dCdDZ$dudFdGZ%dHdIZ&dJdKZ'dLdMZ(dvdNdOZ)dPdQZ*dwdTdUZ+dVdWZ,dXdYZ-dZd[Z.d\d]Z/d^d_Z0e0Z1dxd`daZ2dydcddZ3dzdedfZ4d{dgdhZ5didjZ6dkdlZ7eZ8dS)|r zvAnimation part of the RawTurtle. Puts RawTurtle upon a TurtleScreen and provides tools for its animation. NrkrrcCs4t|tr||_n|t|tr:|tjkr2tj|||_nTt|ttfrtjD]}|j |krN||_qqNt||_tj|jn t d||j}t || t ||j|||_t|||_d|_d|_d|_|_||_d|_||_|jg|_|jg|_g|_||_t ||_!|"dS)Nzbad canvas argument %sF)#r_Screenrrr screensr>rrr.rrrrr$rrDdrawingLineItemrBr_poly _creatingPoly _fillitem _fillpathr(_hidden_from_screencurrentLineItemr currentLiner stampItems_undobuffersizerrrJ)rZcanvasrkrrrrrrr s@                 zRawTurtle.__init__cCs0t|t||||dS)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&_clearrrJrrrrr` s   zRawTurtle.resetcCs&|dks|dkrd|_n t||_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)rr)rsizerrrrh szRawTurtle.setundobuffercCs|jdkrdS|jS)zReturn count of entries in the undobuffer. No argument. Example (for a Turtle instance named turtle): >>> while undobufferentries(): ... undo() Nr)rrrrrrrx, s zRawTurtle.undobufferentriescCsld|_|_|jD]}|j|q|j|_g|_|jrJ|j |j |jg|_| | |j dS)zDelete all of pen's drawingsN)rNrOrrrIrDrQrRr+r>rr7rhrTrGrrrrU9 s    zRawTurtle._clearcCs||dS)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)rUrJrrrrr5G s zRawTurtle.clearcCsF|j|jjdkrdSt|jdkrB|j|j|j|j|jdSr) rrrrrRrErQr)r'rrrrrV s  zRawTurtle._update_datacCsx|j}|jdkrdS|jdkrD|||||jn0||jdkrt|D] }|q^|dS)z&Perform a Turtle-data update. rNr) rrrrrJrMrrr+)rrrqrrrrJ^ s     zRawTurtle._updatecCs|j||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*)rflagrrrrrp szRawTurtle._tracercCs |j|Sr)rrrrrrr szRawTurtle._colorcCs |j|Sr)rrrrrrr szRawTurtle._colorstrc Cst|tr|Sz|\}}}Wn(ttfk rDtdt|YnX|jjdkrldd|||fD\}}}d|krdkrnn.d|krdkrnnd|krdksntdt|d|||fS) z,Convert colortriples to hexstrings. rrcSsg|]}td|qSrrrrrrr~ sz!RawTurtle._cc..rrrr)rrrrrrr)rrrrrrrr_cc s  Fz RawTurtle._cccs|j||j|j}d|_d|_t|}|_||_|_t|jj|_j|j |jjj }|dkr |j_ nJ|dkr j dj|j_ n*|dkrʇfddj |jjjD|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() Nrrtr/rcsg|] }qSrrErFrGrrr~ sz#RawTurtle.clone..)rr=r+rrrBrDrr>rryr:rHrurrDrQrJ)rrqttyperrGrr8 s.      zRawTurtle.clonecCsB|dkr|jjS||jkr*td||j||dS)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)rrDrrrrCrJ)rrrrrrk s   zRawTurtle.shapecCs||kr|krdkr8nn|j\}}|||jfS|dksH|dkrPtd|dk rt|dkrj||f}q||f}n|dk r|jd|f}n|j}|dkr|j}|jd||ddS)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 zeror3)rar;r9)r-r1rrV)rZ stretch_widZ stretch_lenr9r;rrrrl s$"    zRawTurtle.shapesizecCs |dkr|jS|jd|ddS)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 Nr3)rarn)r.rV)rZshearrrrrn szRawTurtle.shearfactorcCs<| |j|j}|tjddtj}|jd|ddS)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) rrr3)rarsN)r rrrrVrrrsrrrrg szRawTurtle.settiltanglecCs>|dkr0|j dtj|j}||j|jS||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() Nr)r/rrrr rrgr[rrrrt4 szRawTurtle.tiltanglecCs|||dS)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)rgrtrrrrrsN szRawTurtle.tiltcCs6||kr(|kr(|kr(dkr2nn|jS|j\}}}}|dk rL|}|dk rX|}|dk rd|}|dk rp|}||||dkrtd||||f|_t| |dtj} t| t| } } | || || || || || || || |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 singularrr3r4) r0rrrrrrr-r.r/rV)rt11t12t21t22Zm11Zm12Zm21Zm22Zalfar?r@Za11Za12Za21Za22rrrrma s0,   zRawTurtle.shapetransformcs^|j|j\|j\tjj}dt||\fdd|DS)zlComputes transformed polygon shapes from a shape according to current position and heading. rcsFg|]>\}}||j ||jfqSr)r4r5r{rrZe0Ze1Zp0Zp1rrrr~ sz(RawTurtle._polytrafo..)rrrrr5r4r)rrerrar _polytrafo s  zRawTurtle._polytrafocCs2|jj|jj}|jdkr.||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)) rrN)rrrrDry _getshapepolyr)rrkrrrrG s  zRawTurtle.get_shapepolyFcsx|jdks|r|j\n>|jdkrNtd|jd}|dd|f\n|jdkr\|Stfdd|DS) z`Calculate transformed shape polygon according to resizemode and shapetransform. r3r2rg@rrc3s2|]*\}}||||fVqdSrrr`r\r]r^r_rrr sz*RawTurtle._getshapepoly..)r%r0maxr'r)rrrr!rrerrd s  zRawTurtle._getshapepolyc Cs|j}|j|jj}|j}|jj}|jr*|jdkr*|jdkr*d|_ |j }|dkr|j dkrfd}n|j dkrx|j }n|j }|||}|j|j}}|j|||||ddnt|d kr|||j|nZ|d krt||D]D\} \} }}||| d} |j| | |||||j ddqnx|j r6d S|dkrR||d d d nJ|d krv|||j|jdj n&|d kr|D]} || d d d qd|_ d S)zpManages the correct rendering of the turtle with respect to its shape, resizemode, stretch and tilt etc.rFrrrr2Tr"r9rzrArtrNrrrrr/)rrrrDryrHr(rrrPrr%r'r1rcrdr*r)rCrwrziprX) rrrkrZZtitemtshaper6fcocrHrrrrr sR           zRawTurtle._drawturtlec CsT|j}|j|jj}|j}|j}|dkr|}|jdkr@d}n|jdkrR|j}n|j }| | |}|j |j }}|j|||||ddn|dkr|d}|||j|n|d kr4g}|D]} |} || qt|}t||D]D\} \} }}| | | d} |j| | |||||j ddq|j||jd |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) rrrr2Trgrtrrrr)rrrrDryrr:r%r'r1rcrdr*r)rCrurwrr>rrirXrSrr) rrrkrZrjstitemr6rkrlZelementrHrrrrrr sH       zRawTurtle.stampcCs||jkrDt|tr,|D]}|j|qn |j||j|d|f}|j}||jkr`dS|j|}|j|||j kr|j d|j |_ |j |j d|j dgdS)z9does the work for clearstamp() and clearstamps() rrNr) rSrrrrIrrrindexrrinsert)rstampidZsubitemrHZbufrnrrr _clearstamp s        zRawTurtle._clearstampcCs|||dS)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)rqrJ)rrprrrr6 s zRawTurtle.clearstampcCs^|dkr|jdd}n&|dkr0|jd|}n|j|d}|D]}||qB|dS)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)rSrqrJ)rrZtoDeleterHrrrr7- s zRawTurtle.clearstampsc Cs|j|j|jt|jtf}|j}d|j|||j|j dd| |j|j ddff}|j rh|j ||j}|jrZ|jdkrZ||}|d|jd|d|jd}dt|ddd|j|j}|d |} td|D]R} | dkrd } nd } || | |_|jr2||j||jf|j|j| |q|jrZ|j|jd d |jd|jrn|j |t|jtr|j|||_|jr|j|t|j dkr||dS)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. goNrrrrr皙?rTFrrrr"rz*)r+r)r'rrOrrrrQrRrrrrr,rr4r5rrrErKrJr>rMrLrr=) rrgo_modesrZ undo_entrystartdiffdiffsqnhopsdeltarrArrrr I sb      $$      zRawTurtle._gotocs|\}}}}|\}}}} |\} } } |jt|j|dkrDtd| |_| |_| ddgkrbd} n|} j| | | |dfdd|jD}|D]}||j |q|}|j rj dkr||}|d j d |dj d }dt|dd d |j |j }|d |}td|D]P}|dkr@d}nd}||||_|rr|j||jf||||q,|rj|jdd|d||_|jrt|jd kr|j|jgkrd|_d|_| r|jgkrd|_tdn|jdk r|j|dS)z)Reverse a _goto. Used for undo() rz$undogoto: HALLO-DA-STIMMT-WAS-NICHT!rrrucs&g|]}|kr|dkr|qS)r)ryrzrrrrr~ sz'RawTurtle._undogoto..rrrrrsrTFrtNzUnwahrscheinlich in _undogoto!)rrrrrQrRrErrIrr,rr4r5rrrKrJrMrrLrrO)rentryoldnewrwZcoodataZdrawingZpcZpsrBZcLIZcLrZusepcZtodeleter|rxryrzr{r|rrArr}r _undogoto~ sl     $$          zRawTurtle._undogotocCs|jr|jd||jf||j9}|j|}|jj}|dkr|jdkrd|j}dtt ||}d||}t |D]}|j||_| q|||_| dS)z&Turns pen clockwise by angle. rotrrg@rN) rrr rrrrr,rrrrJ)rrZ neworientrZanglevelr r|rrrrr s      zRawTurtle._rotateTcCsnt|jdkrD|j|j|j|j|j|j|_|j |jn|jj|jddg|_|rj|j g|_dS)zCloses current line item and starts a new one. Remark: if current line became too long, animation performance (via _drawline) slowed down considerably. rT)rAN) rrRrrErQr)r'rDrr>rrArrrr= s zRawTurtle._newLinecCs t|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) )rrOrrrrrrB s zRawTurtle.fillingcCsX|s"|j|_|j|j|jg|_||j rL|j d|jf| 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:rNrr>rrOr=rrrJrrrrr1 s   zRawTurtle.begin_fillcCs^|rZt|jdkrF|jj|j|j|jd|jrF|jd|jfd|_|_| dS)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() rr;dofillN) rBrrOrrCrNr*rrrJrrrrr> s  zRawTurtle.end_fillc Gs8|sNt|ttfr0||}|jt|jd}qr|j}|sr|jt|jd}n$|dkrh|jt|jd}||}t|jdr|j |j ||}|j ||j r|j d|fn|}|j r|j dgd|j _z>|dkr|||||||dW5||X|j r4d |j _dS) 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<rTr2rF)rrrrr'rfr)hasattrrrrrr>rrrVrrarMrXrYrWrC)rrVr9rHrVrrrr< s:        z RawTurtle.dotcCsB|j|j||||j\}}|j||jr>|jd|f|S)z)Performs the writing for write() wri)rrXrr)rr>rr)rrVrWrUrHrrrrrXH s zRawTurtle._writerPArialrr7cCs`|jr|jdgd|j_|t|||}|rN|\}}||||jr\d|j_dS)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) rTFN)rrrrXrrr[re)rargZmoverWrUrrrrrrr{R 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)rrLrMrrrrr2o 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)rMrrrrr?} 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)rLrrrrrrD 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") rGrrrrrF 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() [] rrrrrrH szRawTurtle.getturtlecCs |j|S)zDSet delay value which determines speed of turtle animation. )rrrLrrrrM szRawTurtle._delayrcCs"|j|jj||||dS)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. 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 N)rrerrHrJrrrrrR szRawTurtle.onclickcCs"|j|jj||||dS)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. 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. N)rrfrrHrJrrrrrT szRawTurtle.onreleasecCs|j|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. 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). N)rrgrrHrrrrrS szRawTurtle.ondragcCs,|jdkrdS|dkr@|\}}|| ||j|j}n|dkr\|d}||n|dkrp||n|dkr|d}|j||j |n|dkr|d}|jj |dd d d nh|d kr|d}d|_ |_ ||jkr(|j||j |n$|d kr(t ||d|jdS) z2Does the main part of the work for undo() Nrrrrrr)rr<rrhrr8rrV)rrr rr6rrrIrrrCrNrOr$rV)ractionrrZdegPAUZdummyrmrHrrr_undos<           zRawTurtle._undocCsl|jdkrdS|j}|d}|dd}|dkr\|rh|}||d|ddq4n |||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() ... Nrrr)rrr)rrHrrrrrrw's   zRawTurtle.undo)NN)N)NNN)N)N)NNNN)F)N)T)N)FrPr)N)rN)rN)rN)9rrrrrJrrr`rhrxrUr5rrJrrrrXr8rkrlrnrgrtrsrmrcrGrdrrrrqr6r7r rrr=rBr1r>r<rXr{r2r?rDrFrHrErMrRrTrSrrwrvrrrrr sr (  (  (   (  (- 5A  0        cCstjdkrtt_tjS)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 _screenrIrrrrr Js c@sfeZdZdZdZedZddZededededfd d Zd d Z d dZ ddZ ddZ dS)rINr)cCstjdkr4tt_|_|jtj|j|jtjdkrtd}td}td}td}td}td}|j |||||j t_t |tj| ||||dS)Nrzrrrrr)rI_rootrr)_titler)_destroyrrr#r$rrr&)rrzrrrrrrrrrXs   z_Screen.__init__rzrrrcCst|jdsdS|j}|j}t|trNd|krBdkrNnn||}|dkrb||d}t|trd|krdkrnn||}|dkr||d}|j|||||dS)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 r'Nrrr)rrr*r+rrr'r,)rrzrr%r&rQZshrrrr&ns   " " z _Screen.setupcCs tjdk rtj||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)rIrr)r)rZ titlestringrrrr)s  z _Screen.titlecCs:|j}|tjkr(dt_dt_dt_dt_dt_|dS)NF) rrIr rrrrrr()rrootrrrrs z_Screen._destroycCs |dS)z~Shut the turtlegraphics window. Example (for a TurtleScreen instance named screen): >>> screen.bye() N)rrrrrrsz _Screen.byecsNfdd}|tdr"dSz tWntk rHtdYnXdS)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() cs dS)z&Screen.bye() with two dummy-parametersN)r)rrrrrexitGracefullysz+_Screen.exitonclick..exitGracefullyrNr)rRrrAttributeErrorexit)rrrrrrs   z_Screen.exitonclick) rrrrrrrrr&r)rrrrrrrrIRs  ( rIc@s4eZdZdZdZdZedededfddZdS)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. NrkrrcCs,tjdkrtt_tj|tj|||ddS)N)rkrr)r rr r r)rrkrrrrrrs  zTurtle.__init__)rrrrrrrrrrrrr sturtle_docstringdictc Csi}tD]}d|}t|j||<qtD]}d|}t|j||<q(td|d}tdd|D}|d|dd D](}|d t||d ||q||d }|d t||d |||d |W5QRXdS)aCreate 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 .py It is intended to serve as a template for translation of the docstrings into different languages. z_Screen.zTurtle.z%s.pyr6css$|]}|ddtkr|VqdS)rrN)r _alias_listrrrrrsz&write_docstringdict..zdocsdict = { Nrz%s : z """%s """, z """%s """ z} ) _tg_screen_functionsrr_tg_turtle_functionsrrr{reprclose)rdocsdict methodnamerrrrrrr~s$   c Cs`dd|i}t|}|j}|D]8}z||t|_Wq"tk rXtd|Yq"Xq"dS)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)r __import__rrrrr)Zlangmodnamemodulerrrrrread_docstringssrrzCannot find docsdict forz;Unknown Error when trying to import %s-docstring-dictionaryc Csd}}t|j\}}}|dd}|dd}|jp:g}dd|D}dgt|t||}ddt||D} |dk r| d||d||dk r| d||d|d | }d |}d |}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)r{rrrrr~<sz"getmethparlist..cSsg|]\}}||qSrr)r{rZdfltrrrr~>s*z**z, z(%s))inspectZgetargs__code__ __defaults__rrir>r) ZobZdefTextZcallTextrZvarargsZvarkwZitems2ZrealArgsdefaultsZitems1rrrgetmethparlist,s&     rcCsJddl}|dkrdStd}|d|d}|d|}|d|}|S)z>>>>>)objinitrZ paramslistZargslist)getattrrr __func_bodyformatrglobalsr) Z functionsrrrZ docreviserrZpl1Zpl2Zdefstrrrr_make_global_funcsws     rzTurtle._screenzScreen()z Turtle._penzTurtle()__main__cCstrtntdSr)rNr]rUrrrr switchpensrcCslttdttdttdtdD]Z}|dkrDttdD]}tdt dqL|dkrxt dt ttd tq2td t d td tt dtdt dtdt d tt dd t dd t dtdD]$}tdt dtdt dqtdttdD]&}tdt dtdt dq:t dS)zDemo of old turtle.py - moduleTdrrrrZZmaroonr rrFZ startstartrxredrN)r`r*ryr0r=rzrr1rCrPr9r>r_r{)r|rrrrdemo1sX         rcCsBtdttdttddtddd}tdtdD]}tt |dqBt dt rnt q`t tdtd d}td tdtd td d D]p}|dkrttd d|dd|tdD]}t|tdqt|d7}tdttddqtdttdtdttddtdttdD](}t ddtdtdtdq`ttdttdttdt}|dt}|d|d| |d|d||dd|d||d|dd|d|dtt|d}||dkr|d|d ||||d|d!dkr| | t|d7}qZ|j d"d#d$d%|d&|dd'd(}t!"dt r| | q|d|j d)d*d+|#|dd,S)-zDemo of some new features.rrrrrrzwait a moment...rZgreenrrrx Fr rZyellowr2rr2i(rZblueZorangerg @g333333?rzCAUGHT! )rrboldr_)rUrWrcSsttdSr)rr)rrrrrbabaszdemo2..babaz Click me!)ZCourierrr)rUN)$rprqrYrdrur;rbrrr4r{rxrwr`rQrrWr1rAr@r>r]rUr9rkrHrar rPryrIr=rrtimesleeprR)rrZlaenger|Ztrirrrrrrdemo2s                             r)r)r)FrZ_verZtkinterrrrrrrZos.pathrrrcopyrrZ _tg_classesrrZ _tg_utilities__all__rrrrrrrrrrrrrrrr robjectr,rrrrrrr$rBr r r rIr r r~rZ _LANGUAGE ImportErrorrrrrrrrrrrrrrrrrsN      5  c /&/O} "      5c