turtle.py 143 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207
  1. #
  2. # turtle.py: a Tkinter based turtle graphics module for Python
  3. # Version 1.1b - 4. 5. 2009
  4. #
  5. # Copyright (C) 2006 - 2010 Gregor Lingl
  6. # email: glingl@aon.at
  7. #
  8. # This software is provided 'as-is', without any express or implied
  9. # warranty. In no event will the authors be held liable for any damages
  10. # arising from the use of this software.
  11. #
  12. # Permission is granted to anyone to use this software for any purpose,
  13. # including commercial applications, and to alter it and redistribute it
  14. # freely, subject to the following restrictions:
  15. #
  16. # 1. The origin of this software must not be misrepresented; you must not
  17. # claim that you wrote the original software. If you use this software
  18. # in a product, an acknowledgment in the product documentation would be
  19. # appreciated but is not required.
  20. # 2. Altered source versions must be plainly marked as such, and must not be
  21. # misrepresented as being the original software.
  22. # 3. This notice may not be removed or altered from any source distribution.
  23. """
  24. Turtle graphics is a popular way for introducing programming to
  25. kids. It was part of the original Logo programming language developed
  26. by Wally Feurzig and Seymour Papert in 1966.
  27. Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an ``import turtle``, give it
  28. the command turtle.forward(15), and it moves (on-screen!) 15 pixels in
  29. the direction it is facing, drawing a line as it moves. Give it the
  30. command turtle.right(25), and it rotates in-place 25 degrees clockwise.
  31. By combining together these and similar commands, intricate shapes and
  32. pictures can easily be drawn.
  33. ----- turtle.py
  34. This module is an extended reimplementation of turtle.py from the
  35. Python standard distribution up to Python 2.5. (See: https://www.python.org)
  36. It tries to keep the merits of turtle.py and to be (nearly) 100%
  37. compatible with it. This means in the first place to enable the
  38. learning programmer to use all the commands, classes and methods
  39. interactively when using the module from within IDLE run with
  40. the -n switch.
  41. Roughly it has the following features added:
  42. - Better animation of the turtle movements, especially of turning the
  43. turtle. So the turtles can more easily be used as a visual feedback
  44. instrument by the (beginning) programmer.
  45. - Different turtle shapes, gif-images as turtle shapes, user defined
  46. and user controllable turtle shapes, among them compound
  47. (multicolored) shapes. Turtle shapes can be stretched and tilted, which
  48. makes turtles very versatile geometrical objects.
  49. - Fine control over turtle movement and screen updates via delay(),
  50. and enhanced tracer() and speed() methods.
  51. - Aliases for the most commonly used commands, like fd for forward etc.,
  52. following the early Logo traditions. This reduces the boring work of
  53. typing long sequences of commands, which often occur in a natural way
  54. when kids try to program fancy pictures on their first encounter with
  55. turtle graphics.
  56. - Turtles now have an undo()-method with configurable undo-buffer.
  57. - Some simple commands/methods for creating event driven programs
  58. (mouse-, key-, timer-events). Especially useful for programming games.
  59. - A scrollable Canvas class. The default scrollable Canvas can be
  60. extended interactively as needed while playing around with the turtle(s).
  61. - A TurtleScreen class with methods controlling background color or
  62. background image, window and canvas size and other properties of the
  63. TurtleScreen.
  64. - There is a method, setworldcoordinates(), to install a user defined
  65. coordinate-system for the TurtleScreen.
  66. - The implementation uses a 2-vector class named Vec2D, derived from tuple.
  67. This class is public, so it can be imported by the application programmer,
  68. which makes certain types of computations very natural and compact.
  69. - Appearance of the TurtleScreen and the Turtles at startup/import can be
  70. configured by means of a turtle.cfg configuration file.
  71. The default configuration mimics the appearance of the old turtle module.
  72. - If configured appropriately the module reads in docstrings from a docstring
  73. dictionary in some different language, supplied separately and replaces
  74. the English ones by those read in. There is a utility function
  75. write_docstringdict() to write a dictionary with the original (English)
  76. docstrings to disc, so it can serve as a template for translations.
  77. Behind the scenes there are some features included with possible
  78. extensions in mind. These will be commented and documented elsewhere.
  79. """
  80. import tkinter as TK
  81. import types
  82. import math
  83. import time
  84. import inspect
  85. import sys
  86. import warnings
  87. from os.path import isfile, split, join
  88. from copy import deepcopy
  89. from tkinter import simpledialog
  90. _tg_classes = ['ScrolledCanvas', 'TurtleScreen', 'Screen',
  91. 'RawTurtle', 'Turtle', 'RawPen', 'Pen', 'Shape', 'Vec2D']
  92. _tg_screen_functions = ['addshape', 'bgcolor', 'bgpic', 'bye',
  93. 'clearscreen', 'colormode', 'delay', 'exitonclick', 'getcanvas',
  94. 'getshapes', 'listen', 'mainloop', 'mode', 'numinput',
  95. 'onkey', 'onkeypress', 'onkeyrelease', 'onscreenclick', 'ontimer',
  96. 'register_shape', 'resetscreen', 'screensize', 'setup',
  97. 'setworldcoordinates', 'textinput', 'title', 'tracer', 'turtles', 'update',
  98. 'window_height', 'window_width']
  99. _tg_turtle_functions = ['back', 'backward', 'begin_fill', 'begin_poly', 'bk',
  100. 'circle', 'clear', 'clearstamp', 'clearstamps', 'clone', 'color',
  101. 'degrees', 'distance', 'dot', 'down', 'end_fill', 'end_poly', 'fd',
  102. 'fillcolor', 'filling', 'forward', 'get_poly', 'getpen', 'getscreen', 'get_shapepoly',
  103. 'getturtle', 'goto', 'heading', 'hideturtle', 'home', 'ht', 'isdown',
  104. 'isvisible', 'left', 'lt', 'onclick', 'ondrag', 'onrelease', 'pd',
  105. 'pen', 'pencolor', 'pendown', 'pensize', 'penup', 'pos', 'position',
  106. 'pu', 'radians', 'right', 'reset', 'resizemode', 'rt',
  107. 'seth', 'setheading', 'setpos', 'setposition', 'settiltangle',
  108. 'setundobuffer', 'setx', 'sety', 'shape', 'shapesize', 'shapetransform', 'shearfactor', 'showturtle',
  109. 'speed', 'st', 'stamp', 'teleport', 'tilt', 'tiltangle', 'towards',
  110. 'turtlesize', 'undo', 'undobufferentries', 'up', 'width',
  111. 'write', 'xcor', 'ycor']
  112. _tg_utilities = ['write_docstringdict', 'done']
  113. __all__ = (_tg_classes + _tg_screen_functions + _tg_turtle_functions +
  114. _tg_utilities + ['Terminator'])
  115. _alias_list = ['addshape', 'backward', 'bk', 'fd', 'ht', 'lt', 'pd', 'pos',
  116. 'pu', 'rt', 'seth', 'setpos', 'setposition', 'st',
  117. 'turtlesize', 'up', 'width']
  118. _CFG = {"width" : 0.5, # Screen
  119. "height" : 0.75,
  120. "canvwidth" : 400,
  121. "canvheight": 300,
  122. "leftright": None,
  123. "topbottom": None,
  124. "mode": "standard", # TurtleScreen
  125. "colormode": 1.0,
  126. "delay": 10,
  127. "undobuffersize": 1000, # RawTurtle
  128. "shape": "classic",
  129. "pencolor" : "black",
  130. "fillcolor" : "black",
  131. "resizemode" : "noresize",
  132. "visible" : True,
  133. "language": "english", # docstrings
  134. "exampleturtle": "turtle",
  135. "examplescreen": "screen",
  136. "title": "Python Turtle Graphics",
  137. "using_IDLE": False
  138. }
  139. def config_dict(filename):
  140. """Convert content of config-file into dictionary."""
  141. with open(filename, "r") as f:
  142. cfglines = f.readlines()
  143. cfgdict = {}
  144. for line in cfglines:
  145. line = line.strip()
  146. if not line or line.startswith("#"):
  147. continue
  148. try:
  149. key, value = line.split("=")
  150. except ValueError:
  151. print("Bad line in config-file %s:\n%s" % (filename,line))
  152. continue
  153. key = key.strip()
  154. value = value.strip()
  155. if value in ["True", "False", "None", "''", '""']:
  156. value = eval(value)
  157. else:
  158. try:
  159. if "." in value:
  160. value = float(value)
  161. else:
  162. value = int(value)
  163. except ValueError:
  164. pass # value need not be converted
  165. cfgdict[key] = value
  166. return cfgdict
  167. def readconfig(cfgdict):
  168. """Read config-files, change configuration-dict accordingly.
  169. If there is a turtle.cfg file in the current working directory,
  170. read it from there. If this contains an importconfig-value,
  171. say 'myway', construct filename turtle_mayway.cfg else use
  172. turtle.cfg and read it from the import-directory, where
  173. turtle.py is located.
  174. Update configuration dictionary first according to config-file,
  175. in the import directory, then according to config-file in the
  176. current working directory.
  177. If no config-file is found, the default configuration is used.
  178. """
  179. default_cfg = "turtle.cfg"
  180. cfgdict1 = {}
  181. cfgdict2 = {}
  182. if isfile(default_cfg):
  183. cfgdict1 = config_dict(default_cfg)
  184. if "importconfig" in cfgdict1:
  185. default_cfg = "turtle_%s.cfg" % cfgdict1["importconfig"]
  186. try:
  187. head, tail = split(__file__)
  188. cfg_file2 = join(head, default_cfg)
  189. except Exception:
  190. cfg_file2 = ""
  191. if isfile(cfg_file2):
  192. cfgdict2 = config_dict(cfg_file2)
  193. _CFG.update(cfgdict2)
  194. _CFG.update(cfgdict1)
  195. try:
  196. readconfig(_CFG)
  197. except Exception:
  198. print ("No configfile read, reason unknown")
  199. class Vec2D(tuple):
  200. """A 2 dimensional vector class, used as a helper class
  201. for implementing turtle graphics.
  202. May be useful for turtle graphics programs also.
  203. Derived from tuple, so a vector is a tuple!
  204. Provides (for a, b vectors, k number):
  205. a+b vector addition
  206. a-b vector subtraction
  207. a*b inner product
  208. k*a and a*k multiplication with scalar
  209. |a| absolute value of a
  210. a.rotate(angle) rotation
  211. """
  212. def __new__(cls, x, y):
  213. return tuple.__new__(cls, (x, y))
  214. def __add__(self, other):
  215. return Vec2D(self[0]+other[0], self[1]+other[1])
  216. def __mul__(self, other):
  217. if isinstance(other, Vec2D):
  218. return self[0]*other[0]+self[1]*other[1]
  219. return Vec2D(self[0]*other, self[1]*other)
  220. def __rmul__(self, other):
  221. if isinstance(other, int) or isinstance(other, float):
  222. return Vec2D(self[0]*other, self[1]*other)
  223. return NotImplemented
  224. def __sub__(self, other):
  225. return Vec2D(self[0]-other[0], self[1]-other[1])
  226. def __neg__(self):
  227. return Vec2D(-self[0], -self[1])
  228. def __abs__(self):
  229. return math.hypot(*self)
  230. def rotate(self, angle):
  231. """rotate self counterclockwise by angle
  232. """
  233. perp = Vec2D(-self[1], self[0])
  234. angle = math.radians(angle)
  235. c, s = math.cos(angle), math.sin(angle)
  236. return Vec2D(self[0]*c+perp[0]*s, self[1]*c+perp[1]*s)
  237. def __getnewargs__(self):
  238. return (self[0], self[1])
  239. def __repr__(self):
  240. return "(%.2f,%.2f)" % self
  241. ##############################################################################
  242. ### From here up to line : Tkinter - Interface for turtle.py ###
  243. ### May be replaced by an interface to some different graphics toolkit ###
  244. ##############################################################################
  245. ## helper functions for Scrolled Canvas, to forward Canvas-methods
  246. ## to ScrolledCanvas class
  247. def __methodDict(cls, _dict):
  248. """helper function for Scrolled Canvas"""
  249. baseList = list(cls.__bases__)
  250. baseList.reverse()
  251. for _super in baseList:
  252. __methodDict(_super, _dict)
  253. for key, value in cls.__dict__.items():
  254. if type(value) == types.FunctionType:
  255. _dict[key] = value
  256. def __methods(cls):
  257. """helper function for Scrolled Canvas"""
  258. _dict = {}
  259. __methodDict(cls, _dict)
  260. return _dict.keys()
  261. __stringBody = (
  262. 'def %(method)s(self, *args, **kw): return ' +
  263. 'self.%(attribute)s.%(method)s(*args, **kw)')
  264. def __forwardmethods(fromClass, toClass, toPart, exclude = ()):
  265. ### MANY CHANGES ###
  266. _dict_1 = {}
  267. __methodDict(toClass, _dict_1)
  268. _dict = {}
  269. mfc = __methods(fromClass)
  270. for ex in _dict_1.keys():
  271. if ex[:1] == '_' or ex[-1:] == '_' or ex in exclude or ex in mfc:
  272. pass
  273. else:
  274. _dict[ex] = _dict_1[ex]
  275. for method, func in _dict.items():
  276. d = {'method': method, 'func': func}
  277. if isinstance(toPart, str):
  278. execString = \
  279. __stringBody % {'method' : method, 'attribute' : toPart}
  280. exec(execString, d)
  281. setattr(fromClass, method, d[method]) ### NEWU!
  282. class ScrolledCanvas(TK.Frame):
  283. """Modeled after the scrolled canvas class from Grayons's Tkinter book.
  284. Used as the default canvas, which pops up automatically when
  285. using turtle graphics functions or the Turtle class.
  286. """
  287. def __init__(self, master, width=500, height=350,
  288. canvwidth=600, canvheight=500):
  289. TK.Frame.__init__(self, master, width=width, height=height)
  290. self._rootwindow = self.winfo_toplevel()
  291. self.width, self.height = width, height
  292. self.canvwidth, self.canvheight = canvwidth, canvheight
  293. self.bg = "white"
  294. self._canvas = TK.Canvas(master, width=width, height=height,
  295. bg=self.bg, relief=TK.SUNKEN, borderwidth=2)
  296. self.hscroll = TK.Scrollbar(master, command=self._canvas.xview,
  297. orient=TK.HORIZONTAL)
  298. self.vscroll = TK.Scrollbar(master, command=self._canvas.yview)
  299. self._canvas.configure(xscrollcommand=self.hscroll.set,
  300. yscrollcommand=self.vscroll.set)
  301. self.rowconfigure(0, weight=1, minsize=0)
  302. self.columnconfigure(0, weight=1, minsize=0)
  303. self._canvas.grid(padx=1, in_ = self, pady=1, row=0,
  304. column=0, rowspan=1, columnspan=1, sticky='news')
  305. self.vscroll.grid(padx=1, in_ = self, pady=1, row=0,
  306. column=1, rowspan=1, columnspan=1, sticky='news')
  307. self.hscroll.grid(padx=1, in_ = self, pady=1, row=1,
  308. column=0, rowspan=1, columnspan=1, sticky='news')
  309. self.reset()
  310. self._rootwindow.bind('<Configure>', self.onResize)
  311. def reset(self, canvwidth=None, canvheight=None, bg = None):
  312. """Adjust canvas and scrollbars according to given canvas size."""
  313. if canvwidth:
  314. self.canvwidth = canvwidth
  315. if canvheight:
  316. self.canvheight = canvheight
  317. if bg:
  318. self.bg = bg
  319. self._canvas.config(bg=bg,
  320. scrollregion=(-self.canvwidth//2, -self.canvheight//2,
  321. self.canvwidth//2, self.canvheight//2))
  322. self._canvas.xview_moveto(0.5*(self.canvwidth - self.width + 30) /
  323. self.canvwidth)
  324. self._canvas.yview_moveto(0.5*(self.canvheight- self.height + 30) /
  325. self.canvheight)
  326. self.adjustScrolls()
  327. def adjustScrolls(self):
  328. """ Adjust scrollbars according to window- and canvas-size.
  329. """
  330. cwidth = self._canvas.winfo_width()
  331. cheight = self._canvas.winfo_height()
  332. self._canvas.xview_moveto(0.5*(self.canvwidth-cwidth)/self.canvwidth)
  333. self._canvas.yview_moveto(0.5*(self.canvheight-cheight)/self.canvheight)
  334. if cwidth < self.canvwidth or cheight < self.canvheight:
  335. self.hscroll.grid(padx=1, in_ = self, pady=1, row=1,
  336. column=0, rowspan=1, columnspan=1, sticky='news')
  337. self.vscroll.grid(padx=1, in_ = self, pady=1, row=0,
  338. column=1, rowspan=1, columnspan=1, sticky='news')
  339. else:
  340. self.hscroll.grid_forget()
  341. self.vscroll.grid_forget()
  342. def onResize(self, event):
  343. """self-explanatory"""
  344. self.adjustScrolls()
  345. def bbox(self, *args):
  346. """ 'forward' method, which canvas itself has inherited...
  347. """
  348. return self._canvas.bbox(*args)
  349. def cget(self, *args, **kwargs):
  350. """ 'forward' method, which canvas itself has inherited...
  351. """
  352. return self._canvas.cget(*args, **kwargs)
  353. def config(self, *args, **kwargs):
  354. """ 'forward' method, which canvas itself has inherited...
  355. """
  356. self._canvas.config(*args, **kwargs)
  357. def bind(self, *args, **kwargs):
  358. """ 'forward' method, which canvas itself has inherited...
  359. """
  360. self._canvas.bind(*args, **kwargs)
  361. def unbind(self, *args, **kwargs):
  362. """ 'forward' method, which canvas itself has inherited...
  363. """
  364. self._canvas.unbind(*args, **kwargs)
  365. def focus_force(self):
  366. """ 'forward' method, which canvas itself has inherited...
  367. """
  368. self._canvas.focus_force()
  369. __forwardmethods(ScrolledCanvas, TK.Canvas, '_canvas')
  370. class _Root(TK.Tk):
  371. """Root class for Screen based on Tkinter."""
  372. def __init__(self):
  373. TK.Tk.__init__(self)
  374. def setupcanvas(self, width, height, cwidth, cheight):
  375. self._canvas = ScrolledCanvas(self, width, height, cwidth, cheight)
  376. self._canvas.pack(expand=1, fill="both")
  377. def _getcanvas(self):
  378. return self._canvas
  379. def set_geometry(self, width, height, startx, starty):
  380. self.geometry("%dx%d%+d%+d"%(width, height, startx, starty))
  381. def ondestroy(self, destroy):
  382. self.wm_protocol("WM_DELETE_WINDOW", destroy)
  383. def win_width(self):
  384. return self.winfo_screenwidth()
  385. def win_height(self):
  386. return self.winfo_screenheight()
  387. Canvas = TK.Canvas
  388. class TurtleScreenBase(object):
  389. """Provide the basic graphics functionality.
  390. Interface between Tkinter and turtle.py.
  391. To port turtle.py to some different graphics toolkit
  392. a corresponding TurtleScreenBase class has to be implemented.
  393. """
  394. def _blankimage(self):
  395. """return a blank image object
  396. """
  397. img = TK.PhotoImage(width=1, height=1, master=self.cv)
  398. img.blank()
  399. return img
  400. def _image(self, filename):
  401. """return an image object containing the
  402. imagedata from a gif-file named filename.
  403. """
  404. return TK.PhotoImage(file=filename, master=self.cv)
  405. def __init__(self, cv):
  406. self.cv = cv
  407. if isinstance(cv, ScrolledCanvas):
  408. w = self.cv.canvwidth
  409. h = self.cv.canvheight
  410. else: # expected: ordinary TK.Canvas
  411. w = int(self.cv.cget("width"))
  412. h = int(self.cv.cget("height"))
  413. self.cv.config(scrollregion = (-w//2, -h//2, w//2, h//2 ))
  414. self.canvwidth = w
  415. self.canvheight = h
  416. self.xscale = self.yscale = 1.0
  417. def _createpoly(self):
  418. """Create an invisible polygon item on canvas self.cv)
  419. """
  420. return self.cv.create_polygon((0, 0, 0, 0, 0, 0), fill="", outline="")
  421. def _drawpoly(self, polyitem, coordlist, fill=None,
  422. outline=None, width=None, top=False):
  423. """Configure polygonitem polyitem according to provided
  424. arguments:
  425. coordlist is sequence of coordinates
  426. fill is filling color
  427. outline is outline color
  428. top is a boolean value, which specifies if polyitem
  429. will be put on top of the canvas' displaylist so it
  430. will not be covered by other items.
  431. """
  432. cl = []
  433. for x, y in coordlist:
  434. cl.append(x * self.xscale)
  435. cl.append(-y * self.yscale)
  436. self.cv.coords(polyitem, *cl)
  437. if fill is not None:
  438. self.cv.itemconfigure(polyitem, fill=fill)
  439. if outline is not None:
  440. self.cv.itemconfigure(polyitem, outline=outline)
  441. if width is not None:
  442. self.cv.itemconfigure(polyitem, width=width)
  443. if top:
  444. self.cv.tag_raise(polyitem)
  445. def _createline(self):
  446. """Create an invisible line item on canvas self.cv)
  447. """
  448. return self.cv.create_line(0, 0, 0, 0, fill="", width=2,
  449. capstyle = TK.ROUND)
  450. def _drawline(self, lineitem, coordlist=None,
  451. fill=None, width=None, top=False):
  452. """Configure lineitem according to provided arguments:
  453. coordlist is sequence of coordinates
  454. fill is drawing color
  455. width is width of drawn line.
  456. top is a boolean value, which specifies if polyitem
  457. will be put on top of the canvas' displaylist so it
  458. will not be covered by other items.
  459. """
  460. if coordlist is not None:
  461. cl = []
  462. for x, y in coordlist:
  463. cl.append(x * self.xscale)
  464. cl.append(-y * self.yscale)
  465. self.cv.coords(lineitem, *cl)
  466. if fill is not None:
  467. self.cv.itemconfigure(lineitem, fill=fill)
  468. if width is not None:
  469. self.cv.itemconfigure(lineitem, width=width)
  470. if top:
  471. self.cv.tag_raise(lineitem)
  472. def _delete(self, item):
  473. """Delete graphics item from canvas.
  474. If item is"all" delete all graphics items.
  475. """
  476. self.cv.delete(item)
  477. def _update(self):
  478. """Redraw graphics items on canvas
  479. """
  480. self.cv.update()
  481. def _delay(self, delay):
  482. """Delay subsequent canvas actions for delay ms."""
  483. self.cv.after(delay)
  484. def _iscolorstring(self, color):
  485. """Check if the string color is a legal Tkinter color string.
  486. """
  487. try:
  488. rgb = self.cv.winfo_rgb(color)
  489. ok = True
  490. except TK.TclError:
  491. ok = False
  492. return ok
  493. def _bgcolor(self, color=None):
  494. """Set canvas' backgroundcolor if color is not None,
  495. else return backgroundcolor."""
  496. if color is not None:
  497. self.cv.config(bg = color)
  498. self._update()
  499. else:
  500. return self.cv.cget("bg")
  501. def _write(self, pos, txt, align, font, pencolor):
  502. """Write txt at pos in canvas with specified font
  503. and color.
  504. Return text item and x-coord of right bottom corner
  505. of text's bounding box."""
  506. x, y = pos
  507. x = x * self.xscale
  508. y = y * self.yscale
  509. anchor = {"left":"sw", "center":"s", "right":"se" }
  510. item = self.cv.create_text(x-1, -y, text = txt, anchor = anchor[align],
  511. fill = pencolor, font = font)
  512. x0, y0, x1, y1 = self.cv.bbox(item)
  513. return item, x1-1
  514. def _onclick(self, item, fun, num=1, add=None):
  515. """Bind fun to mouse-click event on turtle.
  516. fun must be a function with two arguments, the coordinates
  517. of the clicked point on the canvas.
  518. num, the number of the mouse-button defaults to 1
  519. """
  520. if fun is None:
  521. self.cv.tag_unbind(item, "<Button-%s>" % num)
  522. else:
  523. def eventfun(event):
  524. x, y = (self.cv.canvasx(event.x)/self.xscale,
  525. -self.cv.canvasy(event.y)/self.yscale)
  526. fun(x, y)
  527. self.cv.tag_bind(item, "<Button-%s>" % num, eventfun, add)
  528. def _onrelease(self, item, fun, num=1, add=None):
  529. """Bind fun to mouse-button-release event on turtle.
  530. fun must be a function with two arguments, the coordinates
  531. of the point on the canvas where mouse button is released.
  532. num, the number of the mouse-button defaults to 1
  533. If a turtle is clicked, first _onclick-event will be performed,
  534. then _onscreensclick-event.
  535. """
  536. if fun is None:
  537. self.cv.tag_unbind(item, "<Button%s-ButtonRelease>" % num)
  538. else:
  539. def eventfun(event):
  540. x, y = (self.cv.canvasx(event.x)/self.xscale,
  541. -self.cv.canvasy(event.y)/self.yscale)
  542. fun(x, y)
  543. self.cv.tag_bind(item, "<Button%s-ButtonRelease>" % num,
  544. eventfun, add)
  545. def _ondrag(self, item, fun, num=1, add=None):
  546. """Bind fun to mouse-move-event (with pressed mouse button) on turtle.
  547. fun must be a function with two arguments, the coordinates of the
  548. actual mouse position on the canvas.
  549. num, the number of the mouse-button defaults to 1
  550. Every sequence of mouse-move-events on a turtle is preceded by a
  551. mouse-click event on that turtle.
  552. """
  553. if fun is None:
  554. self.cv.tag_unbind(item, "<Button%s-Motion>" % num)
  555. else:
  556. def eventfun(event):
  557. try:
  558. x, y = (self.cv.canvasx(event.x)/self.xscale,
  559. -self.cv.canvasy(event.y)/self.yscale)
  560. fun(x, y)
  561. except Exception:
  562. pass
  563. self.cv.tag_bind(item, "<Button%s-Motion>" % num, eventfun, add)
  564. def _onscreenclick(self, fun, num=1, add=None):
  565. """Bind fun to mouse-click event on canvas.
  566. fun must be a function with two arguments, the coordinates
  567. of the clicked point on the canvas.
  568. num, the number of the mouse-button defaults to 1
  569. If a turtle is clicked, first _onclick-event will be performed,
  570. then _onscreensclick-event.
  571. """
  572. if fun is None:
  573. self.cv.unbind("<Button-%s>" % num)
  574. else:
  575. def eventfun(event):
  576. x, y = (self.cv.canvasx(event.x)/self.xscale,
  577. -self.cv.canvasy(event.y)/self.yscale)
  578. fun(x, y)
  579. self.cv.bind("<Button-%s>" % num, eventfun, add)
  580. def _onkeyrelease(self, fun, key):
  581. """Bind fun to key-release event of key.
  582. Canvas must have focus. See method listen
  583. """
  584. if fun is None:
  585. self.cv.unbind("<KeyRelease-%s>" % key, None)
  586. else:
  587. def eventfun(event):
  588. fun()
  589. self.cv.bind("<KeyRelease-%s>" % key, eventfun)
  590. def _onkeypress(self, fun, key=None):
  591. """If key is given, bind fun to key-press event of key.
  592. Otherwise bind fun to any key-press.
  593. Canvas must have focus. See method listen.
  594. """
  595. if fun is None:
  596. if key is None:
  597. self.cv.unbind("<KeyPress>", None)
  598. else:
  599. self.cv.unbind("<KeyPress-%s>" % key, None)
  600. else:
  601. def eventfun(event):
  602. fun()
  603. if key is None:
  604. self.cv.bind("<KeyPress>", eventfun)
  605. else:
  606. self.cv.bind("<KeyPress-%s>" % key, eventfun)
  607. def _listen(self):
  608. """Set focus on canvas (in order to collect key-events)
  609. """
  610. self.cv.focus_force()
  611. def _ontimer(self, fun, t):
  612. """Install a timer, which calls fun after t milliseconds.
  613. """
  614. if t == 0:
  615. self.cv.after_idle(fun)
  616. else:
  617. self.cv.after(t, fun)
  618. def _createimage(self, image):
  619. """Create and return image item on canvas.
  620. """
  621. return self.cv.create_image(0, 0, image=image)
  622. def _drawimage(self, item, pos, image):
  623. """Configure image item as to draw image object
  624. at position (x,y) on canvas)
  625. """
  626. x, y = pos
  627. self.cv.coords(item, (x * self.xscale, -y * self.yscale))
  628. self.cv.itemconfig(item, image=image)
  629. def _setbgpic(self, item, image):
  630. """Configure image item as to draw image object
  631. at center of canvas. Set item to the first item
  632. in the displaylist, so it will be drawn below
  633. any other item ."""
  634. self.cv.itemconfig(item, image=image)
  635. self.cv.tag_lower(item)
  636. def _type(self, item):
  637. """Return 'line' or 'polygon' or 'image' depending on
  638. type of item.
  639. """
  640. return self.cv.type(item)
  641. def _pointlist(self, item):
  642. """returns list of coordinate-pairs of points of item
  643. Example (for insiders):
  644. >>> from turtle import *
  645. >>> getscreen()._pointlist(getturtle().turtle._item)
  646. [(0.0, 9.9999999999999982), (0.0, -9.9999999999999982),
  647. (9.9999999999999982, 0.0)]
  648. >>> """
  649. cl = self.cv.coords(item)
  650. pl = [(cl[i], -cl[i+1]) for i in range(0, len(cl), 2)]
  651. return pl
  652. def _setscrollregion(self, srx1, sry1, srx2, sry2):
  653. self.cv.config(scrollregion=(srx1, sry1, srx2, sry2))
  654. def _rescale(self, xscalefactor, yscalefactor):
  655. items = self.cv.find_all()
  656. for item in items:
  657. coordinates = list(self.cv.coords(item))
  658. newcoordlist = []
  659. while coordinates:
  660. x, y = coordinates[:2]
  661. newcoordlist.append(x * xscalefactor)
  662. newcoordlist.append(y * yscalefactor)
  663. coordinates = coordinates[2:]
  664. self.cv.coords(item, *newcoordlist)
  665. def _resize(self, canvwidth=None, canvheight=None, bg=None):
  666. """Resize the canvas the turtles are drawing on. Does
  667. not alter the drawing window.
  668. """
  669. # needs amendment
  670. if not isinstance(self.cv, ScrolledCanvas):
  671. return self.canvwidth, self.canvheight
  672. if canvwidth is canvheight is bg is None:
  673. return self.cv.canvwidth, self.cv.canvheight
  674. if canvwidth is not None:
  675. self.canvwidth = canvwidth
  676. if canvheight is not None:
  677. self.canvheight = canvheight
  678. self.cv.reset(canvwidth, canvheight, bg)
  679. def _window_size(self):
  680. """ Return the width and height of the turtle window.
  681. """
  682. width = self.cv.winfo_width()
  683. if width <= 1: # the window isn't managed by a geometry manager
  684. width = self.cv['width']
  685. height = self.cv.winfo_height()
  686. if height <= 1: # the window isn't managed by a geometry manager
  687. height = self.cv['height']
  688. return width, height
  689. def mainloop(self):
  690. """Starts event loop - calling Tkinter's mainloop function.
  691. No argument.
  692. Must be last statement in a turtle graphics program.
  693. Must NOT be used if a script is run from within IDLE in -n mode
  694. (No subprocess) - for interactive use of turtle graphics.
  695. Example (for a TurtleScreen instance named screen):
  696. >>> screen.mainloop()
  697. """
  698. self.cv.tk.mainloop()
  699. def textinput(self, title, prompt):
  700. """Pop up a dialog window for input of a string.
  701. Arguments: title is the title of the dialog window,
  702. prompt is a text mostly describing what information to input.
  703. Return the string input
  704. If the dialog is canceled, return None.
  705. Example (for a TurtleScreen instance named screen):
  706. >>> screen.textinput("NIM", "Name of first player:")
  707. """
  708. return simpledialog.askstring(title, prompt, parent=self.cv)
  709. def numinput(self, title, prompt, default=None, minval=None, maxval=None):
  710. """Pop up a dialog window for input of a number.
  711. Arguments: title is the title of the dialog window,
  712. prompt is a text mostly describing what numerical information to input.
  713. default: default value
  714. minval: minimum value for input
  715. maxval: maximum value for input
  716. The number input must be in the range minval .. maxval if these are
  717. given. If not, a hint is issued and the dialog remains open for
  718. correction. Return the number input.
  719. If the dialog is canceled, return None.
  720. Example (for a TurtleScreen instance named screen):
  721. >>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)
  722. """
  723. return simpledialog.askfloat(title, prompt, initialvalue=default,
  724. minvalue=minval, maxvalue=maxval,
  725. parent=self.cv)
  726. ##############################################################################
  727. ### End of Tkinter - interface ###
  728. ##############################################################################
  729. class Terminator (Exception):
  730. """Will be raised in TurtleScreen.update, if _RUNNING becomes False.
  731. This stops execution of a turtle graphics script.
  732. Main purpose: use in the Demo-Viewer turtle.Demo.py.
  733. """
  734. pass
  735. class TurtleGraphicsError(Exception):
  736. """Some TurtleGraphics Error
  737. """
  738. class Shape(object):
  739. """Data structure modeling shapes.
  740. attribute _type is one of "polygon", "image", "compound"
  741. attribute _data is - depending on _type a poygon-tuple,
  742. an image or a list constructed using the addcomponent method.
  743. """
  744. def __init__(self, type_, data=None):
  745. self._type = type_
  746. if type_ == "polygon":
  747. if isinstance(data, list):
  748. data = tuple(data)
  749. elif type_ == "image":
  750. if isinstance(data, str):
  751. if data.lower().endswith(".gif") and isfile(data):
  752. data = TurtleScreen._image(data)
  753. # else data assumed to be Photoimage
  754. elif type_ == "compound":
  755. data = []
  756. else:
  757. raise TurtleGraphicsError("There is no shape type %s" % type_)
  758. self._data = data
  759. def addcomponent(self, poly, fill, outline=None):
  760. """Add component to a shape of type compound.
  761. Arguments: poly is a polygon, i. e. a tuple of number pairs.
  762. fill is the fillcolor of the component,
  763. outline is the outline color of the component.
  764. call (for a Shapeobject namend s):
  765. -- s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue")
  766. Example:
  767. >>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
  768. >>> s = Shape("compound")
  769. >>> s.addcomponent(poly, "red", "blue")
  770. >>> # .. add more components and then use register_shape()
  771. """
  772. if self._type != "compound":
  773. raise TurtleGraphicsError("Cannot add component to %s Shape"
  774. % self._type)
  775. if outline is None:
  776. outline = fill
  777. self._data.append([poly, fill, outline])
  778. class Tbuffer(object):
  779. """Ring buffer used as undobuffer for RawTurtle objects."""
  780. def __init__(self, bufsize=10):
  781. self.bufsize = bufsize
  782. self.buffer = [[None]] * bufsize
  783. self.ptr = -1
  784. self.cumulate = False
  785. def reset(self, bufsize=None):
  786. if bufsize is None:
  787. for i in range(self.bufsize):
  788. self.buffer[i] = [None]
  789. else:
  790. self.bufsize = bufsize
  791. self.buffer = [[None]] * bufsize
  792. self.ptr = -1
  793. def push(self, item):
  794. if self.bufsize > 0:
  795. if not self.cumulate:
  796. self.ptr = (self.ptr + 1) % self.bufsize
  797. self.buffer[self.ptr] = item
  798. else:
  799. self.buffer[self.ptr].append(item)
  800. def pop(self):
  801. if self.bufsize > 0:
  802. item = self.buffer[self.ptr]
  803. if item is None:
  804. return None
  805. else:
  806. self.buffer[self.ptr] = [None]
  807. self.ptr = (self.ptr - 1) % self.bufsize
  808. return (item)
  809. def nr_of_items(self):
  810. return self.bufsize - self.buffer.count([None])
  811. def __repr__(self):
  812. return str(self.buffer) + " " + str(self.ptr)
  813. class TurtleScreen(TurtleScreenBase):
  814. """Provides screen oriented methods like bgcolor etc.
  815. Only relies upon the methods of TurtleScreenBase and NOT
  816. upon components of the underlying graphics toolkit -
  817. which is Tkinter in this case.
  818. """
  819. _RUNNING = True
  820. def __init__(self, cv, mode=_CFG["mode"],
  821. colormode=_CFG["colormode"], delay=_CFG["delay"]):
  822. TurtleScreenBase.__init__(self, cv)
  823. self._shapes = {
  824. "arrow" : Shape("polygon", ((-10,0), (10,0), (0,10))),
  825. "turtle" : Shape("polygon", ((0,16), (-2,14), (-1,10), (-4,7),
  826. (-7,9), (-9,8), (-6,5), (-7,1), (-5,-3), (-8,-6),
  827. (-6,-8), (-4,-5), (0,-7), (4,-5), (6,-8), (8,-6),
  828. (5,-3), (7,1), (6,5), (9,8), (7,9), (4,7), (1,10),
  829. (2,14))),
  830. "circle" : Shape("polygon", ((10,0), (9.51,3.09), (8.09,5.88),
  831. (5.88,8.09), (3.09,9.51), (0,10), (-3.09,9.51),
  832. (-5.88,8.09), (-8.09,5.88), (-9.51,3.09), (-10,0),
  833. (-9.51,-3.09), (-8.09,-5.88), (-5.88,-8.09),
  834. (-3.09,-9.51), (-0.00,-10.00), (3.09,-9.51),
  835. (5.88,-8.09), (8.09,-5.88), (9.51,-3.09))),
  836. "square" : Shape("polygon", ((10,-10), (10,10), (-10,10),
  837. (-10,-10))),
  838. "triangle" : Shape("polygon", ((10,-5.77), (0,11.55),
  839. (-10,-5.77))),
  840. "classic": Shape("polygon", ((0,0),(-5,-9),(0,-7),(5,-9))),
  841. "blank" : Shape("image", self._blankimage())
  842. }
  843. self._bgpics = {"nopic" : ""}
  844. self._mode = mode
  845. self._delayvalue = delay
  846. self._colormode = _CFG["colormode"]
  847. self._keys = []
  848. self.clear()
  849. if sys.platform == 'darwin':
  850. # Force Turtle window to the front on OS X. This is needed because
  851. # the Turtle window will show behind the Terminal window when you
  852. # start the demo from the command line.
  853. rootwindow = cv.winfo_toplevel()
  854. rootwindow.call('wm', 'attributes', '.', '-topmost', '1')
  855. rootwindow.call('wm', 'attributes', '.', '-topmost', '0')
  856. def clear(self):
  857. """Delete all drawings and all turtles from the TurtleScreen.
  858. No argument.
  859. Reset empty TurtleScreen to its initial state: white background,
  860. no backgroundimage, no eventbindings and tracing on.
  861. Example (for a TurtleScreen instance named screen):
  862. >>> screen.clear()
  863. Note: this method is not available as function.
  864. """
  865. self._delayvalue = _CFG["delay"]
  866. self._colormode = _CFG["colormode"]
  867. self._delete("all")
  868. self._bgpic = self._createimage("")
  869. self._bgpicname = "nopic"
  870. self._tracing = 1
  871. self._updatecounter = 0
  872. self._turtles = []
  873. self.bgcolor("white")
  874. for btn in 1, 2, 3:
  875. self.onclick(None, btn)
  876. self.onkeypress(None)
  877. for key in self._keys[:]:
  878. self.onkey(None, key)
  879. self.onkeypress(None, key)
  880. Turtle._pen = None
  881. def mode(self, mode=None):
  882. """Set turtle-mode ('standard', 'logo' or 'world') and perform reset.
  883. Optional argument:
  884. mode -- one of the strings 'standard', 'logo' or 'world'
  885. Mode 'standard' is compatible with turtle.py.
  886. Mode 'logo' is compatible with most Logo-Turtle-Graphics.
  887. Mode 'world' uses userdefined 'worldcoordinates'. *Attention*: in
  888. this mode angles appear distorted if x/y unit-ratio doesn't equal 1.
  889. If mode is not given, return the current mode.
  890. Mode Initial turtle heading positive angles
  891. ------------|-------------------------|-------------------
  892. 'standard' to the right (east) counterclockwise
  893. 'logo' upward (north) clockwise
  894. Examples:
  895. >>> mode('logo') # resets turtle heading to north
  896. >>> mode()
  897. 'logo'
  898. """
  899. if mode is None:
  900. return self._mode
  901. mode = mode.lower()
  902. if mode not in ["standard", "logo", "world"]:
  903. raise TurtleGraphicsError("No turtle-graphics-mode %s" % mode)
  904. self._mode = mode
  905. if mode in ["standard", "logo"]:
  906. self._setscrollregion(-self.canvwidth//2, -self.canvheight//2,
  907. self.canvwidth//2, self.canvheight//2)
  908. self.xscale = self.yscale = 1.0
  909. self.reset()
  910. def setworldcoordinates(self, llx, lly, urx, ury):
  911. """Set up a user defined coordinate-system.
  912. Arguments:
  913. llx -- a number, x-coordinate of lower left corner of canvas
  914. lly -- a number, y-coordinate of lower left corner of canvas
  915. urx -- a number, x-coordinate of upper right corner of canvas
  916. ury -- a number, y-coordinate of upper right corner of canvas
  917. Set up user coodinat-system and switch to mode 'world' if necessary.
  918. This performs a screen.reset. If mode 'world' is already active,
  919. all drawings are redrawn according to the new coordinates.
  920. But ATTENTION: in user-defined coordinatesystems angles may appear
  921. distorted. (see Screen.mode())
  922. Example (for a TurtleScreen instance named screen):
  923. >>> screen.setworldcoordinates(-10,-0.5,50,1.5)
  924. >>> for _ in range(36):
  925. ... left(10)
  926. ... forward(0.5)
  927. """
  928. if self.mode() != "world":
  929. self.mode("world")
  930. xspan = float(urx - llx)
  931. yspan = float(ury - lly)
  932. wx, wy = self._window_size()
  933. self.screensize(wx-20, wy-20)
  934. oldxscale, oldyscale = self.xscale, self.yscale
  935. self.xscale = self.canvwidth / xspan
  936. self.yscale = self.canvheight / yspan
  937. srx1 = llx * self.xscale
  938. sry1 = -ury * self.yscale
  939. srx2 = self.canvwidth + srx1
  940. sry2 = self.canvheight + sry1
  941. self._setscrollregion(srx1, sry1, srx2, sry2)
  942. self._rescale(self.xscale/oldxscale, self.yscale/oldyscale)
  943. self.update()
  944. def register_shape(self, name, shape=None):
  945. """Adds a turtle shape to TurtleScreen's shapelist.
  946. Arguments:
  947. (1) name is the name of a gif-file and shape is None.
  948. Installs the corresponding image shape.
  949. !! Image-shapes DO NOT rotate when turning the turtle,
  950. !! so they do not display the heading of the turtle!
  951. (2) name is an arbitrary string and shape is a tuple
  952. of pairs of coordinates. Installs the corresponding
  953. polygon shape
  954. (3) name is an arbitrary string and shape is a
  955. (compound) Shape object. Installs the corresponding
  956. compound shape.
  957. To use a shape, you have to issue the command shape(shapename).
  958. call: register_shape("turtle.gif")
  959. --or: register_shape("tri", ((0,0), (10,10), (-10,10)))
  960. Example (for a TurtleScreen instance named screen):
  961. >>> screen.register_shape("triangle", ((5,-3),(0,5),(-5,-3)))
  962. """
  963. if shape is None:
  964. # image
  965. if name.lower().endswith(".gif"):
  966. shape = Shape("image", self._image(name))
  967. else:
  968. raise TurtleGraphicsError("Bad arguments for register_shape.\n"
  969. + "Use help(register_shape)" )
  970. elif isinstance(shape, tuple):
  971. shape = Shape("polygon", shape)
  972. ## else shape assumed to be Shape-instance
  973. self._shapes[name] = shape
  974. def _colorstr(self, color):
  975. """Return color string corresponding to args.
  976. Argument may be a string or a tuple of three
  977. numbers corresponding to actual colormode,
  978. i.e. in the range 0<=n<=colormode.
  979. If the argument doesn't represent a color,
  980. an error is raised.
  981. """
  982. if len(color) == 1:
  983. color = color[0]
  984. if isinstance(color, str):
  985. if self._iscolorstring(color) or color == "":
  986. return color
  987. else:
  988. raise TurtleGraphicsError("bad color string: %s" % str(color))
  989. try:
  990. r, g, b = color
  991. except (TypeError, ValueError):
  992. raise TurtleGraphicsError("bad color arguments: %s" % str(color))
  993. if self._colormode == 1.0:
  994. r, g, b = [round(255.0*x) for x in (r, g, b)]
  995. if not ((0 <= r <= 255) and (0 <= g <= 255) and (0 <= b <= 255)):
  996. raise TurtleGraphicsError("bad color sequence: %s" % str(color))
  997. return "#%02x%02x%02x" % (r, g, b)
  998. def _color(self, cstr):
  999. if not cstr.startswith("#"):
  1000. return cstr
  1001. if len(cstr) == 7:
  1002. cl = [int(cstr[i:i+2], 16) for i in (1, 3, 5)]
  1003. elif len(cstr) == 4:
  1004. cl = [16*int(cstr[h], 16) for h in cstr[1:]]
  1005. else:
  1006. raise TurtleGraphicsError("bad colorstring: %s" % cstr)
  1007. return tuple(c * self._colormode/255 for c in cl)
  1008. def colormode(self, cmode=None):
  1009. """Return the colormode or set it to 1.0 or 255.
  1010. Optional argument:
  1011. cmode -- one of the values 1.0 or 255
  1012. r, g, b values of colortriples have to be in range 0..cmode.
  1013. Example (for a TurtleScreen instance named screen):
  1014. >>> screen.colormode()
  1015. 1.0
  1016. >>> screen.colormode(255)
  1017. >>> pencolor(240,160,80)
  1018. """
  1019. if cmode is None:
  1020. return self._colormode
  1021. if cmode == 1.0:
  1022. self._colormode = float(cmode)
  1023. elif cmode == 255:
  1024. self._colormode = int(cmode)
  1025. def reset(self):
  1026. """Reset all Turtles on the Screen to their initial state.
  1027. No argument.
  1028. Example (for a TurtleScreen instance named screen):
  1029. >>> screen.reset()
  1030. """
  1031. for turtle in self._turtles:
  1032. turtle._setmode(self._mode)
  1033. turtle.reset()
  1034. def turtles(self):
  1035. """Return the list of turtles on the screen.
  1036. Example (for a TurtleScreen instance named screen):
  1037. >>> screen.turtles()
  1038. [<turtle.Turtle object at 0x00E11FB0>]
  1039. """
  1040. return self._turtles
  1041. def bgcolor(self, *args):
  1042. """Set or return backgroundcolor of the TurtleScreen.
  1043. Arguments (if given): a color string or three numbers
  1044. in the range 0..colormode or a 3-tuple of such numbers.
  1045. Example (for a TurtleScreen instance named screen):
  1046. >>> screen.bgcolor("orange")
  1047. >>> screen.bgcolor()
  1048. 'orange'
  1049. >>> screen.bgcolor(0.5,0,0.5)
  1050. >>> screen.bgcolor()
  1051. '#800080'
  1052. """
  1053. if args:
  1054. color = self._colorstr(args)
  1055. else:
  1056. color = None
  1057. color = self._bgcolor(color)
  1058. if color is not None:
  1059. color = self._color(color)
  1060. return color
  1061. def tracer(self, n=None, delay=None):
  1062. """Turns turtle animation on/off and set delay for update drawings.
  1063. Optional arguments:
  1064. n -- nonnegative integer
  1065. delay -- nonnegative integer
  1066. If n is given, only each n-th regular screen update is really performed.
  1067. (Can be used to accelerate the drawing of complex graphics.)
  1068. Second arguments sets delay value (see RawTurtle.delay())
  1069. Example (for a TurtleScreen instance named screen):
  1070. >>> screen.tracer(8, 25)
  1071. >>> dist = 2
  1072. >>> for i in range(200):
  1073. ... fd(dist)
  1074. ... rt(90)
  1075. ... dist += 2
  1076. """
  1077. if n is None:
  1078. return self._tracing
  1079. self._tracing = int(n)
  1080. self._updatecounter = 0
  1081. if delay is not None:
  1082. self._delayvalue = int(delay)
  1083. if self._tracing:
  1084. self.update()
  1085. def delay(self, delay=None):
  1086. """ Return or set the drawing delay in milliseconds.
  1087. Optional argument:
  1088. delay -- positive integer
  1089. Example (for a TurtleScreen instance named screen):
  1090. >>> screen.delay(15)
  1091. >>> screen.delay()
  1092. 15
  1093. """
  1094. if delay is None:
  1095. return self._delayvalue
  1096. self._delayvalue = int(delay)
  1097. def _incrementudc(self):
  1098. """Increment update counter."""
  1099. if not TurtleScreen._RUNNING:
  1100. TurtleScreen._RUNNING = True
  1101. raise Terminator
  1102. if self._tracing > 0:
  1103. self._updatecounter += 1
  1104. self._updatecounter %= self._tracing
  1105. def update(self):
  1106. """Perform a TurtleScreen update.
  1107. """
  1108. tracing = self._tracing
  1109. self._tracing = True
  1110. for t in self.turtles():
  1111. t._update_data()
  1112. t._drawturtle()
  1113. self._tracing = tracing
  1114. self._update()
  1115. def window_width(self):
  1116. """ Return the width of the turtle window.
  1117. Example (for a TurtleScreen instance named screen):
  1118. >>> screen.window_width()
  1119. 640
  1120. """
  1121. return self._window_size()[0]
  1122. def window_height(self):
  1123. """ Return the height of the turtle window.
  1124. Example (for a TurtleScreen instance named screen):
  1125. >>> screen.window_height()
  1126. 480
  1127. """
  1128. return self._window_size()[1]
  1129. def getcanvas(self):
  1130. """Return the Canvas of this TurtleScreen.
  1131. No argument.
  1132. Example (for a Screen instance named screen):
  1133. >>> cv = screen.getcanvas()
  1134. >>> cv
  1135. <turtle.ScrolledCanvas instance at 0x010742D8>
  1136. """
  1137. return self.cv
  1138. def getshapes(self):
  1139. """Return a list of names of all currently available turtle shapes.
  1140. No argument.
  1141. Example (for a TurtleScreen instance named screen):
  1142. >>> screen.getshapes()
  1143. ['arrow', 'blank', 'circle', ... , 'turtle']
  1144. """
  1145. return sorted(self._shapes.keys())
  1146. def onclick(self, fun, btn=1, add=None):
  1147. """Bind fun to mouse-click event on canvas.
  1148. Arguments:
  1149. fun -- a function with two arguments, the coordinates of the
  1150. clicked point on the canvas.
  1151. btn -- the number of the mouse-button, defaults to 1
  1152. Example (for a TurtleScreen instance named screen)
  1153. >>> screen.onclick(goto)
  1154. >>> # Subsequently clicking into the TurtleScreen will
  1155. >>> # make the turtle move to the clicked point.
  1156. >>> screen.onclick(None)
  1157. """
  1158. self._onscreenclick(fun, btn, add)
  1159. def onkey(self, fun, key):
  1160. """Bind fun to key-release event of key.
  1161. Arguments:
  1162. fun -- a function with no arguments
  1163. key -- a string: key (e.g. "a") or key-symbol (e.g. "space")
  1164. In order to be able to register key-events, TurtleScreen
  1165. must have focus. (See method listen.)
  1166. Example (for a TurtleScreen instance named screen):
  1167. >>> def f():
  1168. ... fd(50)
  1169. ... lt(60)
  1170. ...
  1171. >>> screen.onkey(f, "Up")
  1172. >>> screen.listen()
  1173. Subsequently the turtle can be moved by repeatedly pressing
  1174. the up-arrow key, consequently drawing a hexagon
  1175. """
  1176. if fun is None:
  1177. if key in self._keys:
  1178. self._keys.remove(key)
  1179. elif key not in self._keys:
  1180. self._keys.append(key)
  1181. self._onkeyrelease(fun, key)
  1182. def onkeypress(self, fun, key=None):
  1183. """Bind fun to key-press event of key if key is given,
  1184. or to any key-press-event if no key is given.
  1185. Arguments:
  1186. fun -- a function with no arguments
  1187. key -- a string: key (e.g. "a") or key-symbol (e.g. "space")
  1188. In order to be able to register key-events, TurtleScreen
  1189. must have focus. (See method listen.)
  1190. Example (for a TurtleScreen instance named screen
  1191. and a Turtle instance named turtle):
  1192. >>> def f():
  1193. ... fd(50)
  1194. ... lt(60)
  1195. ...
  1196. >>> screen.onkeypress(f, "Up")
  1197. >>> screen.listen()
  1198. Subsequently the turtle can be moved by repeatedly pressing
  1199. the up-arrow key, or by keeping pressed the up-arrow key.
  1200. consequently drawing a hexagon.
  1201. """
  1202. if fun is None:
  1203. if key in self._keys:
  1204. self._keys.remove(key)
  1205. elif key is not None and key not in self._keys:
  1206. self._keys.append(key)
  1207. self._onkeypress(fun, key)
  1208. def listen(self, xdummy=None, ydummy=None):
  1209. """Set focus on TurtleScreen (in order to collect key-events)
  1210. No arguments.
  1211. Dummy arguments are provided in order
  1212. to be able to pass listen to the onclick method.
  1213. Example (for a TurtleScreen instance named screen):
  1214. >>> screen.listen()
  1215. """
  1216. self._listen()
  1217. def ontimer(self, fun, t=0):
  1218. """Install a timer, which calls fun after t milliseconds.
  1219. Arguments:
  1220. fun -- a function with no arguments.
  1221. t -- a number >= 0
  1222. Example (for a TurtleScreen instance named screen):
  1223. >>> running = True
  1224. >>> def f():
  1225. ... if running:
  1226. ... fd(50)
  1227. ... lt(60)
  1228. ... screen.ontimer(f, 250)
  1229. ...
  1230. >>> f() # makes the turtle marching around
  1231. >>> running = False
  1232. """
  1233. self._ontimer(fun, t)
  1234. def bgpic(self, picname=None):
  1235. """Set background image or return name of current backgroundimage.
  1236. Optional argument:
  1237. picname -- a string, name of a gif-file or "nopic".
  1238. If picname is a filename, set the corresponding image as background.
  1239. If picname is "nopic", delete backgroundimage, if present.
  1240. If picname is None, return the filename of the current backgroundimage.
  1241. Example (for a TurtleScreen instance named screen):
  1242. >>> screen.bgpic()
  1243. 'nopic'
  1244. >>> screen.bgpic("landscape.gif")
  1245. >>> screen.bgpic()
  1246. 'landscape.gif'
  1247. """
  1248. if picname is None:
  1249. return self._bgpicname
  1250. if picname not in self._bgpics:
  1251. self._bgpics[picname] = self._image(picname)
  1252. self._setbgpic(self._bgpic, self._bgpics[picname])
  1253. self._bgpicname = picname
  1254. def screensize(self, canvwidth=None, canvheight=None, bg=None):
  1255. """Resize the canvas the turtles are drawing on.
  1256. Optional arguments:
  1257. canvwidth -- positive integer, new width of canvas in pixels
  1258. canvheight -- positive integer, new height of canvas in pixels
  1259. bg -- colorstring or color-tuple, new backgroundcolor
  1260. If no arguments are given, return current (canvaswidth, canvasheight)
  1261. Do not alter the drawing window. To observe hidden parts of
  1262. the canvas use the scrollbars. (Can make visible those parts
  1263. of a drawing, which were outside the canvas before!)
  1264. Example (for a Turtle instance named turtle):
  1265. >>> turtle.screensize(2000,1500)
  1266. >>> # e.g. to search for an erroneously escaped turtle ;-)
  1267. """
  1268. return self._resize(canvwidth, canvheight, bg)
  1269. onscreenclick = onclick
  1270. resetscreen = reset
  1271. clearscreen = clear
  1272. addshape = register_shape
  1273. onkeyrelease = onkey
  1274. class TNavigator(object):
  1275. """Navigation part of the RawTurtle.
  1276. Implements methods for turtle movement.
  1277. """
  1278. START_ORIENTATION = {
  1279. "standard": Vec2D(1.0, 0.0),
  1280. "world" : Vec2D(1.0, 0.0),
  1281. "logo" : Vec2D(0.0, 1.0) }
  1282. DEFAULT_MODE = "standard"
  1283. DEFAULT_ANGLEOFFSET = 0
  1284. DEFAULT_ANGLEORIENT = 1
  1285. def __init__(self, mode=DEFAULT_MODE):
  1286. self._angleOffset = self.DEFAULT_ANGLEOFFSET
  1287. self._angleOrient = self.DEFAULT_ANGLEORIENT
  1288. self._mode = mode
  1289. self.undobuffer = None
  1290. self.degrees()
  1291. self._mode = None
  1292. self._setmode(mode)
  1293. TNavigator.reset(self)
  1294. def reset(self):
  1295. """reset turtle to its initial values
  1296. Will be overwritten by parent class
  1297. """
  1298. self._position = Vec2D(0.0, 0.0)
  1299. self._orient = TNavigator.START_ORIENTATION[self._mode]
  1300. def _setmode(self, mode=None):
  1301. """Set turtle-mode to 'standard', 'world' or 'logo'.
  1302. """
  1303. if mode is None:
  1304. return self._mode
  1305. if mode not in ["standard", "logo", "world"]:
  1306. return
  1307. self._mode = mode
  1308. if mode in ["standard", "world"]:
  1309. self._angleOffset = 0
  1310. self._angleOrient = 1
  1311. else: # mode == "logo":
  1312. self._angleOffset = self._fullcircle/4.
  1313. self._angleOrient = -1
  1314. def _setDegreesPerAU(self, fullcircle):
  1315. """Helper function for degrees() and radians()"""
  1316. self._fullcircle = fullcircle
  1317. self._degreesPerAU = 360/fullcircle
  1318. if self._mode == "standard":
  1319. self._angleOffset = 0
  1320. else:
  1321. self._angleOffset = fullcircle/4.
  1322. def degrees(self, fullcircle=360.0):
  1323. """ Set angle measurement units to degrees.
  1324. Optional argument:
  1325. fullcircle - a number
  1326. Set angle measurement units, i. e. set number
  1327. of 'degrees' for a full circle. Default value is
  1328. 360 degrees.
  1329. Example (for a Turtle instance named turtle):
  1330. >>> turtle.left(90)
  1331. >>> turtle.heading()
  1332. 90
  1333. Change angle measurement unit to grad (also known as gon,
  1334. grade, or gradian and equals 1/100-th of the right angle.)
  1335. >>> turtle.degrees(400.0)
  1336. >>> turtle.heading()
  1337. 100
  1338. """
  1339. self._setDegreesPerAU(fullcircle)
  1340. def radians(self):
  1341. """ Set the angle measurement units to radians.
  1342. No arguments.
  1343. Example (for a Turtle instance named turtle):
  1344. >>> turtle.heading()
  1345. 90
  1346. >>> turtle.radians()
  1347. >>> turtle.heading()
  1348. 1.5707963267948966
  1349. """
  1350. self._setDegreesPerAU(math.tau)
  1351. def _go(self, distance):
  1352. """move turtle forward by specified distance"""
  1353. ende = self._position + self._orient * distance
  1354. self._goto(ende)
  1355. def _rotate(self, angle):
  1356. """Turn turtle counterclockwise by specified angle if angle > 0."""
  1357. angle *= self._degreesPerAU
  1358. self._orient = self._orient.rotate(angle)
  1359. def _goto(self, end):
  1360. """move turtle to position end."""
  1361. self._position = end
  1362. def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None:
  1363. """To be overwritten by child class RawTurtle.
  1364. Includes no TPen references."""
  1365. new_x = x if x is not None else self._position[0]
  1366. new_y = y if y is not None else self._position[1]
  1367. self._position = Vec2D(new_x, new_y)
  1368. def forward(self, distance):
  1369. """Move the turtle forward by the specified distance.
  1370. Aliases: forward | fd
  1371. Argument:
  1372. distance -- a number (integer or float)
  1373. Move the turtle forward by the specified distance, in the direction
  1374. the turtle is headed.
  1375. Example (for a Turtle instance named turtle):
  1376. >>> turtle.position()
  1377. (0.00, 0.00)
  1378. >>> turtle.forward(25)
  1379. >>> turtle.position()
  1380. (25.00,0.00)
  1381. >>> turtle.forward(-75)
  1382. >>> turtle.position()
  1383. (-50.00,0.00)
  1384. """
  1385. self._go(distance)
  1386. def back(self, distance):
  1387. """Move the turtle backward by distance.
  1388. Aliases: back | backward | bk
  1389. Argument:
  1390. distance -- a number
  1391. Move the turtle backward by distance, opposite to the direction the
  1392. turtle is headed. Do not change the turtle's heading.
  1393. Example (for a Turtle instance named turtle):
  1394. >>> turtle.position()
  1395. (0.00, 0.00)
  1396. >>> turtle.backward(30)
  1397. >>> turtle.position()
  1398. (-30.00, 0.00)
  1399. """
  1400. self._go(-distance)
  1401. def right(self, angle):
  1402. """Turn turtle right by angle units.
  1403. Aliases: right | rt
  1404. Argument:
  1405. angle -- a number (integer or float)
  1406. Turn turtle right by angle units. (Units are by default degrees,
  1407. but can be set via the degrees() and radians() functions.)
  1408. Angle orientation depends on mode. (See this.)
  1409. Example (for a Turtle instance named turtle):
  1410. >>> turtle.heading()
  1411. 22.0
  1412. >>> turtle.right(45)
  1413. >>> turtle.heading()
  1414. 337.0
  1415. """
  1416. self._rotate(-angle)
  1417. def left(self, angle):
  1418. """Turn turtle left by angle units.
  1419. Aliases: left | lt
  1420. Argument:
  1421. angle -- a number (integer or float)
  1422. Turn turtle left by angle units. (Units are by default degrees,
  1423. but can be set via the degrees() and radians() functions.)
  1424. Angle orientation depends on mode. (See this.)
  1425. Example (for a Turtle instance named turtle):
  1426. >>> turtle.heading()
  1427. 22.0
  1428. >>> turtle.left(45)
  1429. >>> turtle.heading()
  1430. 67.0
  1431. """
  1432. self._rotate(angle)
  1433. def pos(self):
  1434. """Return the turtle's current location (x,y), as a Vec2D-vector.
  1435. Aliases: pos | position
  1436. No arguments.
  1437. Example (for a Turtle instance named turtle):
  1438. >>> turtle.pos()
  1439. (0.00, 240.00)
  1440. """
  1441. return self._position
  1442. def xcor(self):
  1443. """ Return the turtle's x coordinate.
  1444. No arguments.
  1445. Example (for a Turtle instance named turtle):
  1446. >>> reset()
  1447. >>> turtle.left(60)
  1448. >>> turtle.forward(100)
  1449. >>> print turtle.xcor()
  1450. 50.0
  1451. """
  1452. return self._position[0]
  1453. def ycor(self):
  1454. """ Return the turtle's y coordinate
  1455. ---
  1456. No arguments.
  1457. Example (for a Turtle instance named turtle):
  1458. >>> reset()
  1459. >>> turtle.left(60)
  1460. >>> turtle.forward(100)
  1461. >>> print turtle.ycor()
  1462. 86.6025403784
  1463. """
  1464. return self._position[1]
  1465. def goto(self, x, y=None):
  1466. """Move turtle to an absolute position.
  1467. Aliases: setpos | setposition | goto:
  1468. Arguments:
  1469. x -- a number or a pair/vector of numbers
  1470. y -- a number None
  1471. call: goto(x, y) # two coordinates
  1472. --or: goto((x, y)) # a pair (tuple) of coordinates
  1473. --or: goto(vec) # e.g. as returned by pos()
  1474. Move turtle to an absolute position. If the pen is down,
  1475. a line will be drawn. The turtle's orientation does not change.
  1476. Example (for a Turtle instance named turtle):
  1477. >>> tp = turtle.pos()
  1478. >>> tp
  1479. (0.00, 0.00)
  1480. >>> turtle.setpos(60,30)
  1481. >>> turtle.pos()
  1482. (60.00,30.00)
  1483. >>> turtle.setpos((20,80))
  1484. >>> turtle.pos()
  1485. (20.00,80.00)
  1486. >>> turtle.setpos(tp)
  1487. >>> turtle.pos()
  1488. (0.00,0.00)
  1489. """
  1490. if y is None:
  1491. self._goto(Vec2D(*x))
  1492. else:
  1493. self._goto(Vec2D(x, y))
  1494. def home(self):
  1495. """Move turtle to the origin - coordinates (0,0).
  1496. No arguments.
  1497. Move turtle to the origin - coordinates (0,0) and set its
  1498. heading to its start-orientation (which depends on mode).
  1499. Example (for a Turtle instance named turtle):
  1500. >>> turtle.home()
  1501. """
  1502. self.goto(0, 0)
  1503. self.setheading(0)
  1504. def setx(self, x):
  1505. """Set the turtle's first coordinate to x
  1506. Argument:
  1507. x -- a number (integer or float)
  1508. Set the turtle's first coordinate to x, leave second coordinate
  1509. unchanged.
  1510. Example (for a Turtle instance named turtle):
  1511. >>> turtle.position()
  1512. (0.00, 240.00)
  1513. >>> turtle.setx(10)
  1514. >>> turtle.position()
  1515. (10.00, 240.00)
  1516. """
  1517. self._goto(Vec2D(x, self._position[1]))
  1518. def sety(self, y):
  1519. """Set the turtle's second coordinate to y
  1520. Argument:
  1521. y -- a number (integer or float)
  1522. Set the turtle's first coordinate to x, second coordinate remains
  1523. unchanged.
  1524. Example (for a Turtle instance named turtle):
  1525. >>> turtle.position()
  1526. (0.00, 40.00)
  1527. >>> turtle.sety(-10)
  1528. >>> turtle.position()
  1529. (0.00, -10.00)
  1530. """
  1531. self._goto(Vec2D(self._position[0], y))
  1532. def distance(self, x, y=None):
  1533. """Return the distance from the turtle to (x,y) in turtle step units.
  1534. Arguments:
  1535. x -- a number or a pair/vector of numbers or a turtle instance
  1536. y -- a number None None
  1537. call: distance(x, y) # two coordinates
  1538. --or: distance((x, y)) # a pair (tuple) of coordinates
  1539. --or: distance(vec) # e.g. as returned by pos()
  1540. --or: distance(mypen) # where mypen is another turtle
  1541. Example (for a Turtle instance named turtle):
  1542. >>> turtle.pos()
  1543. (0.00, 0.00)
  1544. >>> turtle.distance(30,40)
  1545. 50.0
  1546. >>> pen = Turtle()
  1547. >>> pen.forward(77)
  1548. >>> turtle.distance(pen)
  1549. 77.0
  1550. """
  1551. if y is not None:
  1552. pos = Vec2D(x, y)
  1553. if isinstance(x, Vec2D):
  1554. pos = x
  1555. elif isinstance(x, tuple):
  1556. pos = Vec2D(*x)
  1557. elif isinstance(x, TNavigator):
  1558. pos = x._position
  1559. return abs(pos - self._position)
  1560. def towards(self, x, y=None):
  1561. """Return the angle of the line from the turtle's position to (x, y).
  1562. Arguments:
  1563. x -- a number or a pair/vector of numbers or a turtle instance
  1564. y -- a number None None
  1565. call: distance(x, y) # two coordinates
  1566. --or: distance((x, y)) # a pair (tuple) of coordinates
  1567. --or: distance(vec) # e.g. as returned by pos()
  1568. --or: distance(mypen) # where mypen is another turtle
  1569. Return the angle, between the line from turtle-position to position
  1570. specified by x, y and the turtle's start orientation. (Depends on
  1571. modes - "standard" or "logo")
  1572. Example (for a Turtle instance named turtle):
  1573. >>> turtle.pos()
  1574. (10.00, 10.00)
  1575. >>> turtle.towards(0,0)
  1576. 225.0
  1577. """
  1578. if y is not None:
  1579. pos = Vec2D(x, y)
  1580. if isinstance(x, Vec2D):
  1581. pos = x
  1582. elif isinstance(x, tuple):
  1583. pos = Vec2D(*x)
  1584. elif isinstance(x, TNavigator):
  1585. pos = x._position
  1586. x, y = pos - self._position
  1587. result = round(math.degrees(math.atan2(y, x)), 10) % 360.0
  1588. result /= self._degreesPerAU
  1589. return (self._angleOffset + self._angleOrient*result) % self._fullcircle
  1590. def heading(self):
  1591. """ Return the turtle's current heading.
  1592. No arguments.
  1593. Example (for a Turtle instance named turtle):
  1594. >>> turtle.left(67)
  1595. >>> turtle.heading()
  1596. 67.0
  1597. """
  1598. x, y = self._orient
  1599. result = round(math.degrees(math.atan2(y, x)), 10) % 360.0
  1600. result /= self._degreesPerAU
  1601. return (self._angleOffset + self._angleOrient*result) % self._fullcircle
  1602. def setheading(self, to_angle):
  1603. """Set the orientation of the turtle to to_angle.
  1604. Aliases: setheading | seth
  1605. Argument:
  1606. to_angle -- a number (integer or float)
  1607. Set the orientation of the turtle to to_angle.
  1608. Here are some common directions in degrees:
  1609. standard - mode: logo-mode:
  1610. -------------------|--------------------
  1611. 0 - east 0 - north
  1612. 90 - north 90 - east
  1613. 180 - west 180 - south
  1614. 270 - south 270 - west
  1615. Example (for a Turtle instance named turtle):
  1616. >>> turtle.setheading(90)
  1617. >>> turtle.heading()
  1618. 90
  1619. """
  1620. angle = (to_angle - self.heading())*self._angleOrient
  1621. full = self._fullcircle
  1622. angle = (angle+full/2.)%full - full/2.
  1623. self._rotate(angle)
  1624. def circle(self, radius, extent = None, steps = None):
  1625. """ Draw a circle with given radius.
  1626. Arguments:
  1627. radius -- a number
  1628. extent (optional) -- a number
  1629. steps (optional) -- an integer
  1630. Draw a circle with given radius. The center is radius units left
  1631. of the turtle; extent - an angle - determines which part of the
  1632. circle is drawn. If extent is not given, draw the entire circle.
  1633. If extent is not a full circle, one endpoint of the arc is the
  1634. current pen position. Draw the arc in counterclockwise direction
  1635. if radius is positive, otherwise in clockwise direction. Finally
  1636. the direction of the turtle is changed by the amount of extent.
  1637. As the circle is approximated by an inscribed regular polygon,
  1638. steps determines the number of steps to use. If not given,
  1639. it will be calculated automatically. Maybe used to draw regular
  1640. polygons.
  1641. call: circle(radius) # full circle
  1642. --or: circle(radius, extent) # arc
  1643. --or: circle(radius, extent, steps)
  1644. --or: circle(radius, steps=6) # 6-sided polygon
  1645. Example (for a Turtle instance named turtle):
  1646. >>> turtle.circle(50)
  1647. >>> turtle.circle(120, 180) # semicircle
  1648. """
  1649. if self.undobuffer:
  1650. self.undobuffer.push(["seq"])
  1651. self.undobuffer.cumulate = True
  1652. speed = self.speed()
  1653. if extent is None:
  1654. extent = self._fullcircle
  1655. if steps is None:
  1656. frac = abs(extent)/self._fullcircle
  1657. steps = 1+int(min(11+abs(radius)/6.0, 59.0)*frac)
  1658. w = 1.0 * extent / steps
  1659. w2 = 0.5 * w
  1660. l = 2.0 * radius * math.sin(math.radians(w2)*self._degreesPerAU)
  1661. if radius < 0:
  1662. l, w, w2 = -l, -w, -w2
  1663. tr = self._tracer()
  1664. dl = self._delay()
  1665. if speed == 0:
  1666. self._tracer(0, 0)
  1667. else:
  1668. self.speed(0)
  1669. self._rotate(w2)
  1670. for i in range(steps):
  1671. self.speed(speed)
  1672. self._go(l)
  1673. self.speed(0)
  1674. self._rotate(w)
  1675. self._rotate(-w2)
  1676. if speed == 0:
  1677. self._tracer(tr, dl)
  1678. self.speed(speed)
  1679. if self.undobuffer:
  1680. self.undobuffer.cumulate = False
  1681. ## three dummy methods to be implemented by child class:
  1682. def speed(self, s=0):
  1683. """dummy method - to be overwritten by child class"""
  1684. def _tracer(self, a=None, b=None):
  1685. """dummy method - to be overwritten by child class"""
  1686. def _delay(self, n=None):
  1687. """dummy method - to be overwritten by child class"""
  1688. fd = forward
  1689. bk = back
  1690. backward = back
  1691. rt = right
  1692. lt = left
  1693. position = pos
  1694. setpos = goto
  1695. setposition = goto
  1696. seth = setheading
  1697. class TPen(object):
  1698. """Drawing part of the RawTurtle.
  1699. Implements drawing properties.
  1700. """
  1701. def __init__(self, resizemode=_CFG["resizemode"]):
  1702. self._resizemode = resizemode # or "user" or "noresize"
  1703. self.undobuffer = None
  1704. TPen._reset(self)
  1705. def _reset(self, pencolor=_CFG["pencolor"],
  1706. fillcolor=_CFG["fillcolor"]):
  1707. self._pensize = 1
  1708. self._shown = True
  1709. self._pencolor = pencolor
  1710. self._fillcolor = fillcolor
  1711. self._drawing = True
  1712. self._speed = 3
  1713. self._stretchfactor = (1., 1.)
  1714. self._shearfactor = 0.
  1715. self._tilt = 0.
  1716. self._shapetrafo = (1., 0., 0., 1.)
  1717. self._outlinewidth = 1
  1718. def resizemode(self, rmode=None):
  1719. """Set resizemode to one of the values: "auto", "user", "noresize".
  1720. (Optional) Argument:
  1721. rmode -- one of the strings "auto", "user", "noresize"
  1722. Different resizemodes have the following effects:
  1723. - "auto" adapts the appearance of the turtle
  1724. corresponding to the value of pensize.
  1725. - "user" adapts the appearance of the turtle according to the
  1726. values of stretchfactor and outlinewidth (outline),
  1727. which are set by shapesize()
  1728. - "noresize" no adaption of the turtle's appearance takes place.
  1729. If no argument is given, return current resizemode.
  1730. resizemode("user") is called by a call of shapesize with arguments.
  1731. Examples (for a Turtle instance named turtle):
  1732. >>> turtle.resizemode("noresize")
  1733. >>> turtle.resizemode()
  1734. 'noresize'
  1735. """
  1736. if rmode is None:
  1737. return self._resizemode
  1738. rmode = rmode.lower()
  1739. if rmode in ["auto", "user", "noresize"]:
  1740. self.pen(resizemode=rmode)
  1741. def pensize(self, width=None):
  1742. """Set or return the line thickness.
  1743. Aliases: pensize | width
  1744. Argument:
  1745. width -- positive number
  1746. Set the line thickness to width or return it. If resizemode is set
  1747. to "auto" and turtleshape is a polygon, that polygon is drawn with
  1748. the same line thickness. If no argument is given, current pensize
  1749. is returned.
  1750. Example (for a Turtle instance named turtle):
  1751. >>> turtle.pensize()
  1752. 1
  1753. >>> turtle.pensize(10) # from here on lines of width 10 are drawn
  1754. """
  1755. if width is None:
  1756. return self._pensize
  1757. self.pen(pensize=width)
  1758. def penup(self):
  1759. """Pull the pen up -- no drawing when moving.
  1760. Aliases: penup | pu | up
  1761. No argument
  1762. Example (for a Turtle instance named turtle):
  1763. >>> turtle.penup()
  1764. """
  1765. if not self._drawing:
  1766. return
  1767. self.pen(pendown=False)
  1768. def pendown(self):
  1769. """Pull the pen down -- drawing when moving.
  1770. Aliases: pendown | pd | down
  1771. No argument.
  1772. Example (for a Turtle instance named turtle):
  1773. >>> turtle.pendown()
  1774. """
  1775. if self._drawing:
  1776. return
  1777. self.pen(pendown=True)
  1778. def isdown(self):
  1779. """Return True if pen is down, False if it's up.
  1780. No argument.
  1781. Example (for a Turtle instance named turtle):
  1782. >>> turtle.penup()
  1783. >>> turtle.isdown()
  1784. False
  1785. >>> turtle.pendown()
  1786. >>> turtle.isdown()
  1787. True
  1788. """
  1789. return self._drawing
  1790. def speed(self, speed=None):
  1791. """ Return or set the turtle's speed.
  1792. Optional argument:
  1793. speed -- an integer in the range 0..10 or a speedstring (see below)
  1794. Set the turtle's speed to an integer value in the range 0 .. 10.
  1795. If no argument is given: return current speed.
  1796. If input is a number greater than 10 or smaller than 0.5,
  1797. speed is set to 0.
  1798. Speedstrings are mapped to speedvalues in the following way:
  1799. 'fastest' : 0
  1800. 'fast' : 10
  1801. 'normal' : 6
  1802. 'slow' : 3
  1803. 'slowest' : 1
  1804. speeds from 1 to 10 enforce increasingly faster animation of
  1805. line drawing and turtle turning.
  1806. Attention:
  1807. speed = 0 : *no* animation takes place. forward/back makes turtle jump
  1808. and likewise left/right make the turtle turn instantly.
  1809. Example (for a Turtle instance named turtle):
  1810. >>> turtle.speed(3)
  1811. """
  1812. speeds = {'fastest':0, 'fast':10, 'normal':6, 'slow':3, 'slowest':1 }
  1813. if speed is None:
  1814. return self._speed
  1815. if speed in speeds:
  1816. speed = speeds[speed]
  1817. elif 0.5 < speed < 10.5:
  1818. speed = int(round(speed))
  1819. else:
  1820. speed = 0
  1821. self.pen(speed=speed)
  1822. def color(self, *args):
  1823. """Return or set the pencolor and fillcolor.
  1824. Arguments:
  1825. Several input formats are allowed.
  1826. They use 0, 1, 2, or 3 arguments as follows:
  1827. color()
  1828. Return the current pencolor and the current fillcolor
  1829. as a pair of color specification strings as are returned
  1830. by pencolor and fillcolor.
  1831. color(colorstring), color((r,g,b)), color(r,g,b)
  1832. inputs as in pencolor, set both, fillcolor and pencolor,
  1833. to the given value.
  1834. color(colorstring1, colorstring2),
  1835. color((r1,g1,b1), (r2,g2,b2))
  1836. equivalent to pencolor(colorstring1) and fillcolor(colorstring2)
  1837. and analogously, if the other input format is used.
  1838. If turtleshape is a polygon, outline and interior of that polygon
  1839. is drawn with the newly set colors.
  1840. For more info see: pencolor, fillcolor
  1841. Example (for a Turtle instance named turtle):
  1842. >>> turtle.color('red', 'green')
  1843. >>> turtle.color()
  1844. ('red', 'green')
  1845. >>> colormode(255)
  1846. >>> color((40, 80, 120), (160, 200, 240))
  1847. >>> color()
  1848. ('#285078', '#a0c8f0')
  1849. """
  1850. if args:
  1851. l = len(args)
  1852. if l == 1:
  1853. pcolor = fcolor = args[0]
  1854. elif l == 2:
  1855. pcolor, fcolor = args
  1856. elif l == 3:
  1857. pcolor = fcolor = args
  1858. pcolor = self._colorstr(pcolor)
  1859. fcolor = self._colorstr(fcolor)
  1860. self.pen(pencolor=pcolor, fillcolor=fcolor)
  1861. else:
  1862. return self._color(self._pencolor), self._color(self._fillcolor)
  1863. def pencolor(self, *args):
  1864. """ Return or set the pencolor.
  1865. Arguments:
  1866. Four input formats are allowed:
  1867. - pencolor()
  1868. Return the current pencolor as color specification string,
  1869. possibly in hex-number format (see example).
  1870. May be used as input to another color/pencolor/fillcolor call.
  1871. - pencolor(colorstring)
  1872. s is a Tk color specification string, such as "red" or "yellow"
  1873. - pencolor((r, g, b))
  1874. *a tuple* of r, g, and b, which represent, an RGB color,
  1875. and each of r, g, and b are in the range 0..colormode,
  1876. where colormode is either 1.0 or 255
  1877. - pencolor(r, g, b)
  1878. r, g, and b represent an RGB color, and each of r, g, and b
  1879. are in the range 0..colormode
  1880. If turtleshape is a polygon, the outline of that polygon is drawn
  1881. with the newly set pencolor.
  1882. Example (for a Turtle instance named turtle):
  1883. >>> turtle.pencolor('brown')
  1884. >>> tup = (0.2, 0.8, 0.55)
  1885. >>> turtle.pencolor(tup)
  1886. >>> turtle.pencolor()
  1887. '#33cc8c'
  1888. """
  1889. if args:
  1890. color = self._colorstr(args)
  1891. if color == self._pencolor:
  1892. return
  1893. self.pen(pencolor=color)
  1894. else:
  1895. return self._color(self._pencolor)
  1896. def fillcolor(self, *args):
  1897. """ Return or set the fillcolor.
  1898. Arguments:
  1899. Four input formats are allowed:
  1900. - fillcolor()
  1901. Return the current fillcolor as color specification string,
  1902. possibly in hex-number format (see example).
  1903. May be used as input to another color/pencolor/fillcolor call.
  1904. - fillcolor(colorstring)
  1905. s is a Tk color specification string, such as "red" or "yellow"
  1906. - fillcolor((r, g, b))
  1907. *a tuple* of r, g, and b, which represent, an RGB color,
  1908. and each of r, g, and b are in the range 0..colormode,
  1909. where colormode is either 1.0 or 255
  1910. - fillcolor(r, g, b)
  1911. r, g, and b represent an RGB color, and each of r, g, and b
  1912. are in the range 0..colormode
  1913. If turtleshape is a polygon, the interior of that polygon is drawn
  1914. with the newly set fillcolor.
  1915. Example (for a Turtle instance named turtle):
  1916. >>> turtle.fillcolor('violet')
  1917. >>> col = turtle.pencolor()
  1918. >>> turtle.fillcolor(col)
  1919. >>> turtle.fillcolor(0, .5, 0)
  1920. """
  1921. if args:
  1922. color = self._colorstr(args)
  1923. if color == self._fillcolor:
  1924. return
  1925. self.pen(fillcolor=color)
  1926. else:
  1927. return self._color(self._fillcolor)
  1928. def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None:
  1929. """To be overwritten by child class RawTurtle.
  1930. Includes no TNavigator references.
  1931. """
  1932. pendown = self.isdown()
  1933. if pendown:
  1934. self.pen(pendown=False)
  1935. self.pen(pendown=pendown)
  1936. def showturtle(self):
  1937. """Makes the turtle visible.
  1938. Aliases: showturtle | st
  1939. No argument.
  1940. Example (for a Turtle instance named turtle):
  1941. >>> turtle.hideturtle()
  1942. >>> turtle.showturtle()
  1943. """
  1944. self.pen(shown=True)
  1945. def hideturtle(self):
  1946. """Makes the turtle invisible.
  1947. Aliases: hideturtle | ht
  1948. No argument.
  1949. It's a good idea to do this while you're in the
  1950. middle of a complicated drawing, because hiding
  1951. the turtle speeds up the drawing observably.
  1952. Example (for a Turtle instance named turtle):
  1953. >>> turtle.hideturtle()
  1954. """
  1955. self.pen(shown=False)
  1956. def isvisible(self):
  1957. """Return True if the Turtle is shown, False if it's hidden.
  1958. No argument.
  1959. Example (for a Turtle instance named turtle):
  1960. >>> turtle.hideturtle()
  1961. >>> print turtle.isvisible():
  1962. False
  1963. """
  1964. return self._shown
  1965. def pen(self, pen=None, **pendict):
  1966. """Return or set the pen's attributes.
  1967. Arguments:
  1968. pen -- a dictionary with some or all of the below listed keys.
  1969. **pendict -- one or more keyword-arguments with the below
  1970. listed keys as keywords.
  1971. Return or set the pen's attributes in a 'pen-dictionary'
  1972. with the following key/value pairs:
  1973. "shown" : True/False
  1974. "pendown" : True/False
  1975. "pencolor" : color-string or color-tuple
  1976. "fillcolor" : color-string or color-tuple
  1977. "pensize" : positive number
  1978. "speed" : number in range 0..10
  1979. "resizemode" : "auto" or "user" or "noresize"
  1980. "stretchfactor": (positive number, positive number)
  1981. "shearfactor": number
  1982. "outline" : positive number
  1983. "tilt" : number
  1984. This dictionary can be used as argument for a subsequent
  1985. pen()-call to restore the former pen-state. Moreover one
  1986. or more of these attributes can be provided as keyword-arguments.
  1987. This can be used to set several pen attributes in one statement.
  1988. Examples (for a Turtle instance named turtle):
  1989. >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
  1990. >>> turtle.pen()
  1991. {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
  1992. 'pencolor': 'red', 'pendown': True, 'fillcolor': 'black',
  1993. 'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
  1994. >>> penstate=turtle.pen()
  1995. >>> turtle.color("yellow","")
  1996. >>> turtle.penup()
  1997. >>> turtle.pen()
  1998. {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
  1999. 'pencolor': 'yellow', 'pendown': False, 'fillcolor': '',
  2000. 'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
  2001. >>> p.pen(penstate, fillcolor="green")
  2002. >>> p.pen()
  2003. {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
  2004. 'pencolor': 'red', 'pendown': True, 'fillcolor': 'green',
  2005. 'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
  2006. """
  2007. _pd = {"shown" : self._shown,
  2008. "pendown" : self._drawing,
  2009. "pencolor" : self._pencolor,
  2010. "fillcolor" : self._fillcolor,
  2011. "pensize" : self._pensize,
  2012. "speed" : self._speed,
  2013. "resizemode" : self._resizemode,
  2014. "stretchfactor" : self._stretchfactor,
  2015. "shearfactor" : self._shearfactor,
  2016. "outline" : self._outlinewidth,
  2017. "tilt" : self._tilt
  2018. }
  2019. if not (pen or pendict):
  2020. return _pd
  2021. if isinstance(pen, dict):
  2022. p = pen
  2023. else:
  2024. p = {}
  2025. p.update(pendict)
  2026. _p_buf = {}
  2027. for key in p:
  2028. _p_buf[key] = _pd[key]
  2029. if self.undobuffer:
  2030. self.undobuffer.push(("pen", _p_buf))
  2031. newLine = False
  2032. if "pendown" in p:
  2033. if self._drawing != p["pendown"]:
  2034. newLine = True
  2035. if "pencolor" in p:
  2036. if isinstance(p["pencolor"], tuple):
  2037. p["pencolor"] = self._colorstr((p["pencolor"],))
  2038. if self._pencolor != p["pencolor"]:
  2039. newLine = True
  2040. if "pensize" in p:
  2041. if self._pensize != p["pensize"]:
  2042. newLine = True
  2043. if newLine:
  2044. self._newLine()
  2045. if "pendown" in p:
  2046. self._drawing = p["pendown"]
  2047. if "pencolor" in p:
  2048. self._pencolor = p["pencolor"]
  2049. if "pensize" in p:
  2050. self._pensize = p["pensize"]
  2051. if "fillcolor" in p:
  2052. if isinstance(p["fillcolor"], tuple):
  2053. p["fillcolor"] = self._colorstr((p["fillcolor"],))
  2054. self._fillcolor = p["fillcolor"]
  2055. if "speed" in p:
  2056. self._speed = p["speed"]
  2057. if "resizemode" in p:
  2058. self._resizemode = p["resizemode"]
  2059. if "stretchfactor" in p:
  2060. sf = p["stretchfactor"]
  2061. if isinstance(sf, (int, float)):
  2062. sf = (sf, sf)
  2063. self._stretchfactor = sf
  2064. if "shearfactor" in p:
  2065. self._shearfactor = p["shearfactor"]
  2066. if "outline" in p:
  2067. self._outlinewidth = p["outline"]
  2068. if "shown" in p:
  2069. self._shown = p["shown"]
  2070. if "tilt" in p:
  2071. self._tilt = p["tilt"]
  2072. if "stretchfactor" in p or "tilt" in p or "shearfactor" in p:
  2073. scx, scy = self._stretchfactor
  2074. shf = self._shearfactor
  2075. sa, ca = math.sin(self._tilt), math.cos(self._tilt)
  2076. self._shapetrafo = ( scx*ca, scy*(shf*ca + sa),
  2077. -scx*sa, scy*(ca - shf*sa))
  2078. self._update()
  2079. ## three dummy methods to be implemented by child class:
  2080. def _newLine(self, usePos = True):
  2081. """dummy method - to be overwritten by child class"""
  2082. def _update(self, count=True, forced=False):
  2083. """dummy method - to be overwritten by child class"""
  2084. def _color(self, args):
  2085. """dummy method - to be overwritten by child class"""
  2086. def _colorstr(self, args):
  2087. """dummy method - to be overwritten by child class"""
  2088. width = pensize
  2089. up = penup
  2090. pu = penup
  2091. pd = pendown
  2092. down = pendown
  2093. st = showturtle
  2094. ht = hideturtle
  2095. class _TurtleImage(object):
  2096. """Helper class: Datatype to store Turtle attributes
  2097. """
  2098. def __init__(self, screen, shapeIndex):
  2099. self.screen = screen
  2100. self._type = None
  2101. self._setshape(shapeIndex)
  2102. def _setshape(self, shapeIndex):
  2103. screen = self.screen
  2104. self.shapeIndex = shapeIndex
  2105. if self._type == "polygon" == screen._shapes[shapeIndex]._type:
  2106. return
  2107. if self._type == "image" == screen._shapes[shapeIndex]._type:
  2108. return
  2109. if self._type in ["image", "polygon"]:
  2110. screen._delete(self._item)
  2111. elif self._type == "compound":
  2112. for item in self._item:
  2113. screen._delete(item)
  2114. self._type = screen._shapes[shapeIndex]._type
  2115. if self._type == "polygon":
  2116. self._item = screen._createpoly()
  2117. elif self._type == "image":
  2118. self._item = screen._createimage(screen._shapes["blank"]._data)
  2119. elif self._type == "compound":
  2120. self._item = [screen._createpoly() for item in
  2121. screen._shapes[shapeIndex]._data]
  2122. class RawTurtle(TPen, TNavigator):
  2123. """Animation part of the RawTurtle.
  2124. Puts RawTurtle upon a TurtleScreen and provides tools for
  2125. its animation.
  2126. """
  2127. screens = []
  2128. def __init__(self, canvas=None,
  2129. shape=_CFG["shape"],
  2130. undobuffersize=_CFG["undobuffersize"],
  2131. visible=_CFG["visible"]):
  2132. if isinstance(canvas, _Screen):
  2133. self.screen = canvas
  2134. elif isinstance(canvas, TurtleScreen):
  2135. if canvas not in RawTurtle.screens:
  2136. RawTurtle.screens.append(canvas)
  2137. self.screen = canvas
  2138. elif isinstance(canvas, (ScrolledCanvas, Canvas)):
  2139. for screen in RawTurtle.screens:
  2140. if screen.cv == canvas:
  2141. self.screen = screen
  2142. break
  2143. else:
  2144. self.screen = TurtleScreen(canvas)
  2145. RawTurtle.screens.append(self.screen)
  2146. else:
  2147. raise TurtleGraphicsError("bad canvas argument %s" % canvas)
  2148. screen = self.screen
  2149. TNavigator.__init__(self, screen.mode())
  2150. TPen.__init__(self)
  2151. screen._turtles.append(self)
  2152. self.drawingLineItem = screen._createline()
  2153. self.turtle = _TurtleImage(screen, shape)
  2154. self._poly = None
  2155. self._creatingPoly = False
  2156. self._fillitem = self._fillpath = None
  2157. self._shown = visible
  2158. self._hidden_from_screen = False
  2159. self.currentLineItem = screen._createline()
  2160. self.currentLine = [self._position]
  2161. self.items = [self.currentLineItem]
  2162. self.stampItems = []
  2163. self._undobuffersize = undobuffersize
  2164. self.undobuffer = Tbuffer(undobuffersize)
  2165. self._update()
  2166. def reset(self):
  2167. """Delete the turtle's drawings and restore its default values.
  2168. No argument.
  2169. Delete the turtle's drawings from the screen, re-center the turtle
  2170. and set variables to the default values.
  2171. Example (for a Turtle instance named turtle):
  2172. >>> turtle.position()
  2173. (0.00,-22.00)
  2174. >>> turtle.heading()
  2175. 100.0
  2176. >>> turtle.reset()
  2177. >>> turtle.position()
  2178. (0.00,0.00)
  2179. >>> turtle.heading()
  2180. 0.0
  2181. """
  2182. TNavigator.reset(self)
  2183. TPen._reset(self)
  2184. self._clear()
  2185. self._drawturtle()
  2186. self._update()
  2187. def setundobuffer(self, size):
  2188. """Set or disable undobuffer.
  2189. Argument:
  2190. size -- an integer or None
  2191. If size is an integer an empty undobuffer of given size is installed.
  2192. Size gives the maximum number of turtle-actions that can be undone
  2193. by the undo() function.
  2194. If size is None, no undobuffer is present.
  2195. Example (for a Turtle instance named turtle):
  2196. >>> turtle.setundobuffer(42)
  2197. """
  2198. if size is None or size <= 0:
  2199. self.undobuffer = None
  2200. else:
  2201. self.undobuffer = Tbuffer(size)
  2202. def undobufferentries(self):
  2203. """Return count of entries in the undobuffer.
  2204. No argument.
  2205. Example (for a Turtle instance named turtle):
  2206. >>> while undobufferentries():
  2207. ... undo()
  2208. """
  2209. if self.undobuffer is None:
  2210. return 0
  2211. return self.undobuffer.nr_of_items()
  2212. def _clear(self):
  2213. """Delete all of pen's drawings"""
  2214. self._fillitem = self._fillpath = None
  2215. for item in self.items:
  2216. self.screen._delete(item)
  2217. self.currentLineItem = self.screen._createline()
  2218. self.currentLine = []
  2219. if self._drawing:
  2220. self.currentLine.append(self._position)
  2221. self.items = [self.currentLineItem]
  2222. self.clearstamps()
  2223. self.setundobuffer(self._undobuffersize)
  2224. def clear(self):
  2225. """Delete the turtle's drawings from the screen. Do not move turtle.
  2226. No arguments.
  2227. Delete the turtle's drawings from the screen. Do not move turtle.
  2228. State and position of the turtle as well as drawings of other
  2229. turtles are not affected.
  2230. Examples (for a Turtle instance named turtle):
  2231. >>> turtle.clear()
  2232. """
  2233. self._clear()
  2234. self._update()
  2235. def _update_data(self):
  2236. self.screen._incrementudc()
  2237. if self.screen._updatecounter != 0:
  2238. return
  2239. if len(self.currentLine)>1:
  2240. self.screen._drawline(self.currentLineItem, self.currentLine,
  2241. self._pencolor, self._pensize)
  2242. def _update(self):
  2243. """Perform a Turtle-data update.
  2244. """
  2245. screen = self.screen
  2246. if screen._tracing == 0:
  2247. return
  2248. elif screen._tracing == 1:
  2249. self._update_data()
  2250. self._drawturtle()
  2251. screen._update() # TurtleScreenBase
  2252. screen._delay(screen._delayvalue) # TurtleScreenBase
  2253. else:
  2254. self._update_data()
  2255. if screen._updatecounter == 0:
  2256. for t in screen.turtles():
  2257. t._drawturtle()
  2258. screen._update()
  2259. def _tracer(self, flag=None, delay=None):
  2260. """Turns turtle animation on/off and set delay for update drawings.
  2261. Optional arguments:
  2262. n -- nonnegative integer
  2263. delay -- nonnegative integer
  2264. If n is given, only each n-th regular screen update is really performed.
  2265. (Can be used to accelerate the drawing of complex graphics.)
  2266. Second arguments sets delay value (see RawTurtle.delay())
  2267. Example (for a Turtle instance named turtle):
  2268. >>> turtle.tracer(8, 25)
  2269. >>> dist = 2
  2270. >>> for i in range(200):
  2271. ... turtle.fd(dist)
  2272. ... turtle.rt(90)
  2273. ... dist += 2
  2274. """
  2275. return self.screen.tracer(flag, delay)
  2276. def _color(self, args):
  2277. return self.screen._color(args)
  2278. def _colorstr(self, args):
  2279. return self.screen._colorstr(args)
  2280. def _cc(self, args):
  2281. """Convert colortriples to hexstrings.
  2282. """
  2283. if isinstance(args, str):
  2284. return args
  2285. try:
  2286. r, g, b = args
  2287. except (TypeError, ValueError):
  2288. raise TurtleGraphicsError("bad color arguments: %s" % str(args))
  2289. if self.screen._colormode == 1.0:
  2290. r, g, b = [round(255.0*x) for x in (r, g, b)]
  2291. if not ((0 <= r <= 255) and (0 <= g <= 255) and (0 <= b <= 255)):
  2292. raise TurtleGraphicsError("bad color sequence: %s" % str(args))
  2293. return "#%02x%02x%02x" % (r, g, b)
  2294. def teleport(self, x=None, y=None, *, fill_gap: bool = False) -> None:
  2295. """Instantly move turtle to an absolute position.
  2296. Arguments:
  2297. x -- a number or None
  2298. y -- a number None
  2299. fill_gap -- a boolean This argument must be specified by name.
  2300. call: teleport(x, y) # two coordinates
  2301. --or: teleport(x) # teleport to x position, keeping y as is
  2302. --or: teleport(y=y) # teleport to y position, keeping x as is
  2303. --or: teleport(x, y, fill_gap=True)
  2304. # teleport but fill the gap in between
  2305. Move turtle to an absolute position. Unlike goto(x, y), a line will not
  2306. be drawn. The turtle's orientation does not change. If currently
  2307. filling, the polygon(s) teleported from will be filled after leaving,
  2308. and filling will begin again after teleporting. This can be disabled
  2309. with fill_gap=True, which makes the imaginary line traveled during
  2310. teleporting act as a fill barrier like in goto(x, y).
  2311. Example (for a Turtle instance named turtle):
  2312. >>> tp = turtle.pos()
  2313. >>> tp
  2314. (0.00,0.00)
  2315. >>> turtle.teleport(60)
  2316. >>> turtle.pos()
  2317. (60.00,0.00)
  2318. >>> turtle.teleport(y=10)
  2319. >>> turtle.pos()
  2320. (60.00,10.00)
  2321. >>> turtle.teleport(20, 30)
  2322. >>> turtle.pos()
  2323. (20.00,30.00)
  2324. """
  2325. pendown = self.isdown()
  2326. was_filling = self.filling()
  2327. if pendown:
  2328. self.pen(pendown=False)
  2329. if was_filling and not fill_gap:
  2330. self.end_fill()
  2331. new_x = x if x is not None else self._position[0]
  2332. new_y = y if y is not None else self._position[1]
  2333. self._position = Vec2D(new_x, new_y)
  2334. self.pen(pendown=pendown)
  2335. if was_filling and not fill_gap:
  2336. self.begin_fill()
  2337. def clone(self):
  2338. """Create and return a clone of the turtle.
  2339. No argument.
  2340. Create and return a clone of the turtle with same position, heading
  2341. and turtle properties.
  2342. Example (for a Turtle instance named mick):
  2343. mick = Turtle()
  2344. joe = mick.clone()
  2345. """
  2346. screen = self.screen
  2347. self._newLine(self._drawing)
  2348. turtle = self.turtle
  2349. self.screen = None
  2350. self.turtle = None # too make self deepcopy-able
  2351. q = deepcopy(self)
  2352. self.screen = screen
  2353. self.turtle = turtle
  2354. q.screen = screen
  2355. q.turtle = _TurtleImage(screen, self.turtle.shapeIndex)
  2356. screen._turtles.append(q)
  2357. ttype = screen._shapes[self.turtle.shapeIndex]._type
  2358. if ttype == "polygon":
  2359. q.turtle._item = screen._createpoly()
  2360. elif ttype == "image":
  2361. q.turtle._item = screen._createimage(screen._shapes["blank"]._data)
  2362. elif ttype == "compound":
  2363. q.turtle._item = [screen._createpoly() for item in
  2364. screen._shapes[self.turtle.shapeIndex]._data]
  2365. q.currentLineItem = screen._createline()
  2366. q._update()
  2367. return q
  2368. def shape(self, name=None):
  2369. """Set turtle shape to shape with given name / return current shapename.
  2370. Optional argument:
  2371. name -- a string, which is a valid shapename
  2372. Set turtle shape to shape with given name or, if name is not given,
  2373. return name of current shape.
  2374. Shape with name must exist in the TurtleScreen's shape dictionary.
  2375. Initially there are the following polygon shapes:
  2376. 'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'.
  2377. To learn about how to deal with shapes see Screen-method register_shape.
  2378. Example (for a Turtle instance named turtle):
  2379. >>> turtle.shape()
  2380. 'arrow'
  2381. >>> turtle.shape("turtle")
  2382. >>> turtle.shape()
  2383. 'turtle'
  2384. """
  2385. if name is None:
  2386. return self.turtle.shapeIndex
  2387. if not name in self.screen.getshapes():
  2388. raise TurtleGraphicsError("There is no shape named %s" % name)
  2389. self.turtle._setshape(name)
  2390. self._update()
  2391. def shapesize(self, stretch_wid=None, stretch_len=None, outline=None):
  2392. """Set/return turtle's stretchfactors/outline. Set resizemode to "user".
  2393. Optional arguments:
  2394. stretch_wid : positive number
  2395. stretch_len : positive number
  2396. outline : positive number
  2397. Return or set the pen's attributes x/y-stretchfactors and/or outline.
  2398. Set resizemode to "user".
  2399. If and only if resizemode is set to "user", the turtle will be displayed
  2400. stretched according to its stretchfactors:
  2401. stretch_wid is stretchfactor perpendicular to orientation
  2402. stretch_len is stretchfactor in direction of turtles orientation.
  2403. outline determines the width of the shapes's outline.
  2404. Examples (for a Turtle instance named turtle):
  2405. >>> turtle.resizemode("user")
  2406. >>> turtle.shapesize(5, 5, 12)
  2407. >>> turtle.shapesize(outline=8)
  2408. """
  2409. if stretch_wid is stretch_len is outline is None:
  2410. stretch_wid, stretch_len = self._stretchfactor
  2411. return stretch_wid, stretch_len, self._outlinewidth
  2412. if stretch_wid == 0 or stretch_len == 0:
  2413. raise TurtleGraphicsError("stretch_wid/stretch_len must not be zero")
  2414. if stretch_wid is not None:
  2415. if stretch_len is None:
  2416. stretchfactor = stretch_wid, stretch_wid
  2417. else:
  2418. stretchfactor = stretch_wid, stretch_len
  2419. elif stretch_len is not None:
  2420. stretchfactor = self._stretchfactor[0], stretch_len
  2421. else:
  2422. stretchfactor = self._stretchfactor
  2423. if outline is None:
  2424. outline = self._outlinewidth
  2425. self.pen(resizemode="user",
  2426. stretchfactor=stretchfactor, outline=outline)
  2427. def shearfactor(self, shear=None):
  2428. """Set or return the current shearfactor.
  2429. Optional argument: shear -- number, tangent of the shear angle
  2430. Shear the turtleshape according to the given shearfactor shear,
  2431. which is the tangent of the shear angle. DO NOT change the
  2432. turtle's heading (direction of movement).
  2433. If shear is not given: return the current shearfactor, i. e. the
  2434. tangent of the shear angle, by which lines parallel to the
  2435. heading of the turtle are sheared.
  2436. Examples (for a Turtle instance named turtle):
  2437. >>> turtle.shape("circle")
  2438. >>> turtle.shapesize(5,2)
  2439. >>> turtle.shearfactor(0.5)
  2440. >>> turtle.shearfactor()
  2441. >>> 0.5
  2442. """
  2443. if shear is None:
  2444. return self._shearfactor
  2445. self.pen(resizemode="user", shearfactor=shear)
  2446. def settiltangle(self, angle):
  2447. """Rotate the turtleshape to point in the specified direction
  2448. Argument: angle -- number
  2449. Rotate the turtleshape to point in the direction specified by angle,
  2450. regardless of its current tilt-angle. DO NOT change the turtle's
  2451. heading (direction of movement).
  2452. Deprecated since Python 3.1
  2453. Examples (for a Turtle instance named turtle):
  2454. >>> turtle.shape("circle")
  2455. >>> turtle.shapesize(5,2)
  2456. >>> turtle.settiltangle(45)
  2457. >>> turtle.stamp()
  2458. >>> turtle.fd(50)
  2459. >>> turtle.settiltangle(-45)
  2460. >>> turtle.stamp()
  2461. >>> turtle.fd(50)
  2462. """
  2463. warnings._deprecated("turtle.RawTurtle.settiltangle()",
  2464. "{name!r} is deprecated since Python 3.1 and scheduled "
  2465. "for removal in Python {remove}. Use tiltangle() instead.",
  2466. remove=(3, 13))
  2467. self.tiltangle(angle)
  2468. def tiltangle(self, angle=None):
  2469. """Set or return the current tilt-angle.
  2470. Optional argument: angle -- number
  2471. Rotate the turtleshape to point in the direction specified by angle,
  2472. regardless of its current tilt-angle. DO NOT change the turtle's
  2473. heading (direction of movement).
  2474. If angle is not given: return the current tilt-angle, i. e. the angle
  2475. between the orientation of the turtleshape and the heading of the
  2476. turtle (its direction of movement).
  2477. (Incorrectly marked as deprecated since Python 3.1, it is really
  2478. settiltangle that is deprecated.)
  2479. Examples (for a Turtle instance named turtle):
  2480. >>> turtle.shape("circle")
  2481. >>> turtle.shapesize(5, 2)
  2482. >>> turtle.tiltangle()
  2483. 0.0
  2484. >>> turtle.tiltangle(45)
  2485. >>> turtle.tiltangle()
  2486. 45.0
  2487. >>> turtle.stamp()
  2488. >>> turtle.fd(50)
  2489. >>> turtle.tiltangle(-45)
  2490. >>> turtle.tiltangle()
  2491. 315.0
  2492. >>> turtle.stamp()
  2493. >>> turtle.fd(50)
  2494. """
  2495. if angle is None:
  2496. tilt = -math.degrees(self._tilt) * self._angleOrient
  2497. return (tilt / self._degreesPerAU) % self._fullcircle
  2498. else:
  2499. tilt = -angle * self._degreesPerAU * self._angleOrient
  2500. tilt = math.radians(tilt) % math.tau
  2501. self.pen(resizemode="user", tilt=tilt)
  2502. def tilt(self, angle):
  2503. """Rotate the turtleshape by angle.
  2504. Argument:
  2505. angle - a number
  2506. Rotate the turtleshape by angle from its current tilt-angle,
  2507. but do NOT change the turtle's heading (direction of movement).
  2508. Examples (for a Turtle instance named turtle):
  2509. >>> turtle.shape("circle")
  2510. >>> turtle.shapesize(5,2)
  2511. >>> turtle.tilt(30)
  2512. >>> turtle.fd(50)
  2513. >>> turtle.tilt(30)
  2514. >>> turtle.fd(50)
  2515. """
  2516. self.tiltangle(angle + self.tiltangle())
  2517. def shapetransform(self, t11=None, t12=None, t21=None, t22=None):
  2518. """Set or return the current transformation matrix of the turtle shape.
  2519. Optional arguments: t11, t12, t21, t22 -- numbers.
  2520. If none of the matrix elements are given, return the transformation
  2521. matrix.
  2522. Otherwise set the given elements and transform the turtleshape
  2523. according to the matrix consisting of first row t11, t12 and
  2524. second row t21, 22.
  2525. Modify stretchfactor, shearfactor and tiltangle according to the
  2526. given matrix.
  2527. Examples (for a Turtle instance named turtle):
  2528. >>> turtle.shape("square")
  2529. >>> turtle.shapesize(4,2)
  2530. >>> turtle.shearfactor(-0.5)
  2531. >>> turtle.shapetransform()
  2532. (4.0, -1.0, -0.0, 2.0)
  2533. """
  2534. if t11 is t12 is t21 is t22 is None:
  2535. return self._shapetrafo
  2536. m11, m12, m21, m22 = self._shapetrafo
  2537. if t11 is not None: m11 = t11
  2538. if t12 is not None: m12 = t12
  2539. if t21 is not None: m21 = t21
  2540. if t22 is not None: m22 = t22
  2541. if t11 * t22 - t12 * t21 == 0:
  2542. raise TurtleGraphicsError("Bad shape transform matrix: must not be singular")
  2543. self._shapetrafo = (m11, m12, m21, m22)
  2544. alfa = math.atan2(-m21, m11) % math.tau
  2545. sa, ca = math.sin(alfa), math.cos(alfa)
  2546. a11, a12, a21, a22 = (ca*m11 - sa*m21, ca*m12 - sa*m22,
  2547. sa*m11 + ca*m21, sa*m12 + ca*m22)
  2548. self._stretchfactor = a11, a22
  2549. self._shearfactor = a12/a22
  2550. self._tilt = alfa
  2551. self.pen(resizemode="user")
  2552. def _polytrafo(self, poly):
  2553. """Computes transformed polygon shapes from a shape
  2554. according to current position and heading.
  2555. """
  2556. screen = self.screen
  2557. p0, p1 = self._position
  2558. e0, e1 = self._orient
  2559. e = Vec2D(e0, e1 * screen.yscale / screen.xscale)
  2560. e0, e1 = (1.0 / abs(e)) * e
  2561. return [(p0+(e1*x+e0*y)/screen.xscale, p1+(-e0*x+e1*y)/screen.yscale)
  2562. for (x, y) in poly]
  2563. def get_shapepoly(self):
  2564. """Return the current shape polygon as tuple of coordinate pairs.
  2565. No argument.
  2566. Examples (for a Turtle instance named turtle):
  2567. >>> turtle.shape("square")
  2568. >>> turtle.shapetransform(4, -1, 0, 2)
  2569. >>> turtle.get_shapepoly()
  2570. ((50, -20), (30, 20), (-50, 20), (-30, -20))
  2571. """
  2572. shape = self.screen._shapes[self.turtle.shapeIndex]
  2573. if shape._type == "polygon":
  2574. return self._getshapepoly(shape._data, shape._type == "compound")
  2575. # else return None
  2576. def _getshapepoly(self, polygon, compound=False):
  2577. """Calculate transformed shape polygon according to resizemode
  2578. and shapetransform.
  2579. """
  2580. if self._resizemode == "user" or compound:
  2581. t11, t12, t21, t22 = self._shapetrafo
  2582. elif self._resizemode == "auto":
  2583. l = max(1, self._pensize/5.0)
  2584. t11, t12, t21, t22 = l, 0, 0, l
  2585. elif self._resizemode == "noresize":
  2586. return polygon
  2587. return tuple((t11*x + t12*y, t21*x + t22*y) for (x, y) in polygon)
  2588. def _drawturtle(self):
  2589. """Manages the correct rendering of the turtle with respect to
  2590. its shape, resizemode, stretch and tilt etc."""
  2591. screen = self.screen
  2592. shape = screen._shapes[self.turtle.shapeIndex]
  2593. ttype = shape._type
  2594. titem = self.turtle._item
  2595. if self._shown and screen._updatecounter == 0 and screen._tracing > 0:
  2596. self._hidden_from_screen = False
  2597. tshape = shape._data
  2598. if ttype == "polygon":
  2599. if self._resizemode == "noresize": w = 1
  2600. elif self._resizemode == "auto": w = self._pensize
  2601. else: w =self._outlinewidth
  2602. shape = self._polytrafo(self._getshapepoly(tshape))
  2603. fc, oc = self._fillcolor, self._pencolor
  2604. screen._drawpoly(titem, shape, fill=fc, outline=oc,
  2605. width=w, top=True)
  2606. elif ttype == "image":
  2607. screen._drawimage(titem, self._position, tshape)
  2608. elif ttype == "compound":
  2609. for item, (poly, fc, oc) in zip(titem, tshape):
  2610. poly = self._polytrafo(self._getshapepoly(poly, True))
  2611. screen._drawpoly(item, poly, fill=self._cc(fc),
  2612. outline=self._cc(oc), width=self._outlinewidth, top=True)
  2613. else:
  2614. if self._hidden_from_screen:
  2615. return
  2616. if ttype == "polygon":
  2617. screen._drawpoly(titem, ((0, 0), (0, 0), (0, 0)), "", "")
  2618. elif ttype == "image":
  2619. screen._drawimage(titem, self._position,
  2620. screen._shapes["blank"]._data)
  2621. elif ttype == "compound":
  2622. for item in titem:
  2623. screen._drawpoly(item, ((0, 0), (0, 0), (0, 0)), "", "")
  2624. self._hidden_from_screen = True
  2625. ############################## stamp stuff ###############################
  2626. def stamp(self):
  2627. """Stamp a copy of the turtleshape onto the canvas and return its id.
  2628. No argument.
  2629. Stamp a copy of the turtle shape onto the canvas at the current
  2630. turtle position. Return a stamp_id for that stamp, which can be
  2631. used to delete it by calling clearstamp(stamp_id).
  2632. Example (for a Turtle instance named turtle):
  2633. >>> turtle.color("blue")
  2634. >>> turtle.stamp()
  2635. 13
  2636. >>> turtle.fd(50)
  2637. """
  2638. screen = self.screen
  2639. shape = screen._shapes[self.turtle.shapeIndex]
  2640. ttype = shape._type
  2641. tshape = shape._data
  2642. if ttype == "polygon":
  2643. stitem = screen._createpoly()
  2644. if self._resizemode == "noresize": w = 1
  2645. elif self._resizemode == "auto": w = self._pensize
  2646. else: w =self._outlinewidth
  2647. shape = self._polytrafo(self._getshapepoly(tshape))
  2648. fc, oc = self._fillcolor, self._pencolor
  2649. screen._drawpoly(stitem, shape, fill=fc, outline=oc,
  2650. width=w, top=True)
  2651. elif ttype == "image":
  2652. stitem = screen._createimage("")
  2653. screen._drawimage(stitem, self._position, tshape)
  2654. elif ttype == "compound":
  2655. stitem = []
  2656. for element in tshape:
  2657. item = screen._createpoly()
  2658. stitem.append(item)
  2659. stitem = tuple(stitem)
  2660. for item, (poly, fc, oc) in zip(stitem, tshape):
  2661. poly = self._polytrafo(self._getshapepoly(poly, True))
  2662. screen._drawpoly(item, poly, fill=self._cc(fc),
  2663. outline=self._cc(oc), width=self._outlinewidth, top=True)
  2664. self.stampItems.append(stitem)
  2665. self.undobuffer.push(("stamp", stitem))
  2666. return stitem
  2667. def _clearstamp(self, stampid):
  2668. """does the work for clearstamp() and clearstamps()
  2669. """
  2670. if stampid in self.stampItems:
  2671. if isinstance(stampid, tuple):
  2672. for subitem in stampid:
  2673. self.screen._delete(subitem)
  2674. else:
  2675. self.screen._delete(stampid)
  2676. self.stampItems.remove(stampid)
  2677. # Delete stampitem from undobuffer if necessary
  2678. # if clearstamp is called directly.
  2679. item = ("stamp", stampid)
  2680. buf = self.undobuffer
  2681. if item not in buf.buffer:
  2682. return
  2683. index = buf.buffer.index(item)
  2684. buf.buffer.remove(item)
  2685. if index <= buf.ptr:
  2686. buf.ptr = (buf.ptr - 1) % buf.bufsize
  2687. buf.buffer.insert((buf.ptr+1)%buf.bufsize, [None])
  2688. def clearstamp(self, stampid):
  2689. """Delete stamp with given stampid
  2690. Argument:
  2691. stampid - an integer, must be return value of previous stamp() call.
  2692. Example (for a Turtle instance named turtle):
  2693. >>> turtle.color("blue")
  2694. >>> astamp = turtle.stamp()
  2695. >>> turtle.fd(50)
  2696. >>> turtle.clearstamp(astamp)
  2697. """
  2698. self._clearstamp(stampid)
  2699. self._update()
  2700. def clearstamps(self, n=None):
  2701. """Delete all or first/last n of turtle's stamps.
  2702. Optional argument:
  2703. n -- an integer
  2704. If n is None, delete all of pen's stamps,
  2705. else if n > 0 delete first n stamps
  2706. else if n < 0 delete last n stamps.
  2707. Example (for a Turtle instance named turtle):
  2708. >>> for i in range(8):
  2709. ... turtle.stamp(); turtle.fd(30)
  2710. ...
  2711. >>> turtle.clearstamps(2)
  2712. >>> turtle.clearstamps(-2)
  2713. >>> turtle.clearstamps()
  2714. """
  2715. if n is None:
  2716. toDelete = self.stampItems[:]
  2717. elif n >= 0:
  2718. toDelete = self.stampItems[:n]
  2719. else:
  2720. toDelete = self.stampItems[n:]
  2721. for item in toDelete:
  2722. self._clearstamp(item)
  2723. self._update()
  2724. def _goto(self, end):
  2725. """Move the pen to the point end, thereby drawing a line
  2726. if pen is down. All other methods for turtle movement depend
  2727. on this one.
  2728. """
  2729. ## Version with undo-stuff
  2730. go_modes = ( self._drawing,
  2731. self._pencolor,
  2732. self._pensize,
  2733. isinstance(self._fillpath, list))
  2734. screen = self.screen
  2735. undo_entry = ("go", self._position, end, go_modes,
  2736. (self.currentLineItem,
  2737. self.currentLine[:],
  2738. screen._pointlist(self.currentLineItem),
  2739. self.items[:])
  2740. )
  2741. if self.undobuffer:
  2742. self.undobuffer.push(undo_entry)
  2743. start = self._position
  2744. if self._speed and screen._tracing == 1:
  2745. diff = (end-start)
  2746. diffsq = (diff[0]*screen.xscale)**2 + (diff[1]*screen.yscale)**2
  2747. nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed))
  2748. delta = diff * (1.0/nhops)
  2749. for n in range(1, nhops):
  2750. if n == 1:
  2751. top = True
  2752. else:
  2753. top = False
  2754. self._position = start + delta * n
  2755. if self._drawing:
  2756. screen._drawline(self.drawingLineItem,
  2757. (start, self._position),
  2758. self._pencolor, self._pensize, top)
  2759. self._update()
  2760. if self._drawing:
  2761. screen._drawline(self.drawingLineItem, ((0, 0), (0, 0)),
  2762. fill="", width=self._pensize)
  2763. # Turtle now at end,
  2764. if self._drawing: # now update currentLine
  2765. self.currentLine.append(end)
  2766. if isinstance(self._fillpath, list):
  2767. self._fillpath.append(end)
  2768. ###### vererbung!!!!!!!!!!!!!!!!!!!!!!
  2769. self._position = end
  2770. if self._creatingPoly:
  2771. self._poly.append(end)
  2772. if len(self.currentLine) > 42: # 42! answer to the ultimate question
  2773. # of life, the universe and everything
  2774. self._newLine()
  2775. self._update() #count=True)
  2776. def _undogoto(self, entry):
  2777. """Reverse a _goto. Used for undo()
  2778. """
  2779. old, new, go_modes, coodata = entry
  2780. drawing, pc, ps, filling = go_modes
  2781. cLI, cL, pl, items = coodata
  2782. screen = self.screen
  2783. if abs(self._position - new) > 0.5:
  2784. print ("undogoto: HALLO-DA-STIMMT-WAS-NICHT!")
  2785. # restore former situation
  2786. self.currentLineItem = cLI
  2787. self.currentLine = cL
  2788. if pl == [(0, 0), (0, 0)]:
  2789. usepc = ""
  2790. else:
  2791. usepc = pc
  2792. screen._drawline(cLI, pl, fill=usepc, width=ps)
  2793. todelete = [i for i in self.items if (i not in items) and
  2794. (screen._type(i) == "line")]
  2795. for i in todelete:
  2796. screen._delete(i)
  2797. self.items.remove(i)
  2798. start = old
  2799. if self._speed and screen._tracing == 1:
  2800. diff = old - new
  2801. diffsq = (diff[0]*screen.xscale)**2 + (diff[1]*screen.yscale)**2
  2802. nhops = 1+int((diffsq**0.5)/(3*(1.1**self._speed)*self._speed))
  2803. delta = diff * (1.0/nhops)
  2804. for n in range(1, nhops):
  2805. if n == 1:
  2806. top = True
  2807. else:
  2808. top = False
  2809. self._position = new + delta * n
  2810. if drawing:
  2811. screen._drawline(self.drawingLineItem,
  2812. (start, self._position),
  2813. pc, ps, top)
  2814. self._update()
  2815. if drawing:
  2816. screen._drawline(self.drawingLineItem, ((0, 0), (0, 0)),
  2817. fill="", width=ps)
  2818. # Turtle now at position old,
  2819. self._position = old
  2820. ## if undo is done during creating a polygon, the last vertex
  2821. ## will be deleted. if the polygon is entirely deleted,
  2822. ## creatingPoly will be set to False.
  2823. ## Polygons created before the last one will not be affected by undo()
  2824. if self._creatingPoly:
  2825. if len(self._poly) > 0:
  2826. self._poly.pop()
  2827. if self._poly == []:
  2828. self._creatingPoly = False
  2829. self._poly = None
  2830. if filling:
  2831. if self._fillpath == []:
  2832. self._fillpath = None
  2833. print("Unwahrscheinlich in _undogoto!")
  2834. elif self._fillpath is not None:
  2835. self._fillpath.pop()
  2836. self._update() #count=True)
  2837. def _rotate(self, angle):
  2838. """Turns pen clockwise by angle.
  2839. """
  2840. if self.undobuffer:
  2841. self.undobuffer.push(("rot", angle, self._degreesPerAU))
  2842. angle *= self._degreesPerAU
  2843. neworient = self._orient.rotate(angle)
  2844. tracing = self.screen._tracing
  2845. if tracing == 1 and self._speed > 0:
  2846. anglevel = 3.0 * self._speed
  2847. steps = 1 + int(abs(angle)/anglevel)
  2848. delta = 1.0*angle/steps
  2849. for _ in range(steps):
  2850. self._orient = self._orient.rotate(delta)
  2851. self._update()
  2852. self._orient = neworient
  2853. self._update()
  2854. def _newLine(self, usePos=True):
  2855. """Closes current line item and starts a new one.
  2856. Remark: if current line became too long, animation
  2857. performance (via _drawline) slowed down considerably.
  2858. """
  2859. if len(self.currentLine) > 1:
  2860. self.screen._drawline(self.currentLineItem, self.currentLine,
  2861. self._pencolor, self._pensize)
  2862. self.currentLineItem = self.screen._createline()
  2863. self.items.append(self.currentLineItem)
  2864. else:
  2865. self.screen._drawline(self.currentLineItem, top=True)
  2866. self.currentLine = []
  2867. if usePos:
  2868. self.currentLine = [self._position]
  2869. def filling(self):
  2870. """Return fillstate (True if filling, False else).
  2871. No argument.
  2872. Example (for a Turtle instance named turtle):
  2873. >>> turtle.begin_fill()
  2874. >>> if turtle.filling():
  2875. ... turtle.pensize(5)
  2876. ... else:
  2877. ... turtle.pensize(3)
  2878. """
  2879. return isinstance(self._fillpath, list)
  2880. def begin_fill(self):
  2881. """Called just before drawing a shape to be filled.
  2882. No argument.
  2883. Example (for a Turtle instance named turtle):
  2884. >>> turtle.color("black", "red")
  2885. >>> turtle.begin_fill()
  2886. >>> turtle.circle(60)
  2887. >>> turtle.end_fill()
  2888. """
  2889. if not self.filling():
  2890. self._fillitem = self.screen._createpoly()
  2891. self.items.append(self._fillitem)
  2892. self._fillpath = [self._position]
  2893. self._newLine()
  2894. if self.undobuffer:
  2895. self.undobuffer.push(("beginfill", self._fillitem))
  2896. self._update()
  2897. def end_fill(self):
  2898. """Fill the shape drawn after the call begin_fill().
  2899. No argument.
  2900. Example (for a Turtle instance named turtle):
  2901. >>> turtle.color("black", "red")
  2902. >>> turtle.begin_fill()
  2903. >>> turtle.circle(60)
  2904. >>> turtle.end_fill()
  2905. """
  2906. if self.filling():
  2907. if len(self._fillpath) > 2:
  2908. self.screen._drawpoly(self._fillitem, self._fillpath,
  2909. fill=self._fillcolor)
  2910. if self.undobuffer:
  2911. self.undobuffer.push(("dofill", self._fillitem))
  2912. self._fillitem = self._fillpath = None
  2913. self._update()
  2914. def dot(self, size=None, *color):
  2915. """Draw a dot with diameter size, using color.
  2916. Optional arguments:
  2917. size -- an integer >= 1 (if given)
  2918. color -- a colorstring or a numeric color tuple
  2919. Draw a circular dot with diameter size, using color.
  2920. If size is not given, the maximum of pensize+4 and 2*pensize is used.
  2921. Example (for a Turtle instance named turtle):
  2922. >>> turtle.dot()
  2923. >>> turtle.fd(50); turtle.dot(20, "blue"); turtle.fd(50)
  2924. """
  2925. if not color:
  2926. if isinstance(size, (str, tuple)):
  2927. color = self._colorstr(size)
  2928. size = self._pensize + max(self._pensize, 4)
  2929. else:
  2930. color = self._pencolor
  2931. if not size:
  2932. size = self._pensize + max(self._pensize, 4)
  2933. else:
  2934. if size is None:
  2935. size = self._pensize + max(self._pensize, 4)
  2936. color = self._colorstr(color)
  2937. # If screen were to gain a dot function, see GH #104218.
  2938. pen = self.pen()
  2939. if self.undobuffer:
  2940. self.undobuffer.push(["seq"])
  2941. self.undobuffer.cumulate = True
  2942. try:
  2943. if self.resizemode() == 'auto':
  2944. self.ht()
  2945. self.pendown()
  2946. self.pensize(size)
  2947. self.pencolor(color)
  2948. self.forward(0)
  2949. finally:
  2950. self.pen(pen)
  2951. if self.undobuffer:
  2952. self.undobuffer.cumulate = False
  2953. def _write(self, txt, align, font):
  2954. """Performs the writing for write()
  2955. """
  2956. item, end = self.screen._write(self._position, txt, align, font,
  2957. self._pencolor)
  2958. self._update()
  2959. self.items.append(item)
  2960. if self.undobuffer:
  2961. self.undobuffer.push(("wri", item))
  2962. return end
  2963. def write(self, arg, move=False, align="left", font=("Arial", 8, "normal")):
  2964. """Write text at the current turtle position.
  2965. Arguments:
  2966. arg -- info, which is to be written to the TurtleScreen
  2967. move (optional) -- True/False
  2968. align (optional) -- one of the strings "left", "center" or right"
  2969. font (optional) -- a triple (fontname, fontsize, fonttype)
  2970. Write text - the string representation of arg - at the current
  2971. turtle position according to align ("left", "center" or right")
  2972. and with the given font.
  2973. If move is True, the pen is moved to the bottom-right corner
  2974. of the text. By default, move is False.
  2975. Example (for a Turtle instance named turtle):
  2976. >>> turtle.write('Home = ', True, align="center")
  2977. >>> turtle.write((0,0), True)
  2978. """
  2979. if self.undobuffer:
  2980. self.undobuffer.push(["seq"])
  2981. self.undobuffer.cumulate = True
  2982. end = self._write(str(arg), align.lower(), font)
  2983. if move:
  2984. x, y = self.pos()
  2985. self.setpos(end, y)
  2986. if self.undobuffer:
  2987. self.undobuffer.cumulate = False
  2988. def begin_poly(self):
  2989. """Start recording the vertices of a polygon.
  2990. No argument.
  2991. Start recording the vertices of a polygon. Current turtle position
  2992. is first point of polygon.
  2993. Example (for a Turtle instance named turtle):
  2994. >>> turtle.begin_poly()
  2995. """
  2996. self._poly = [self._position]
  2997. self._creatingPoly = True
  2998. def end_poly(self):
  2999. """Stop recording the vertices of a polygon.
  3000. No argument.
  3001. Stop recording the vertices of a polygon. Current turtle position is
  3002. last point of polygon. This will be connected with the first point.
  3003. Example (for a Turtle instance named turtle):
  3004. >>> turtle.end_poly()
  3005. """
  3006. self._creatingPoly = False
  3007. def get_poly(self):
  3008. """Return the lastly recorded polygon.
  3009. No argument.
  3010. Example (for a Turtle instance named turtle):
  3011. >>> p = turtle.get_poly()
  3012. >>> turtle.register_shape("myFavouriteShape", p)
  3013. """
  3014. ## check if there is any poly?
  3015. if self._poly is not None:
  3016. return tuple(self._poly)
  3017. def getscreen(self):
  3018. """Return the TurtleScreen object, the turtle is drawing on.
  3019. No argument.
  3020. Return the TurtleScreen object, the turtle is drawing on.
  3021. So TurtleScreen-methods can be called for that object.
  3022. Example (for a Turtle instance named turtle):
  3023. >>> ts = turtle.getscreen()
  3024. >>> ts
  3025. <turtle.TurtleScreen object at 0x0106B770>
  3026. >>> ts.bgcolor("pink")
  3027. """
  3028. return self.screen
  3029. def getturtle(self):
  3030. """Return the Turtleobject itself.
  3031. No argument.
  3032. Only reasonable use: as a function to return the 'anonymous turtle':
  3033. Example:
  3034. >>> pet = getturtle()
  3035. >>> pet.fd(50)
  3036. >>> pet
  3037. <turtle.Turtle object at 0x0187D810>
  3038. >>> turtles()
  3039. [<turtle.Turtle object at 0x0187D810>]
  3040. """
  3041. return self
  3042. getpen = getturtle
  3043. ################################################################
  3044. ### screen oriented methods recurring to methods of TurtleScreen
  3045. ################################################################
  3046. def _delay(self, delay=None):
  3047. """Set delay value which determines speed of turtle animation.
  3048. """
  3049. return self.screen.delay(delay)
  3050. def onclick(self, fun, btn=1, add=None):
  3051. """Bind fun to mouse-click event on this turtle on canvas.
  3052. Arguments:
  3053. fun -- a function with two arguments, to which will be assigned
  3054. the coordinates of the clicked point on the canvas.
  3055. btn -- number of the mouse-button defaults to 1 (left mouse button).
  3056. add -- True or False. If True, new binding will be added, otherwise
  3057. it will replace a former binding.
  3058. Example for the anonymous turtle, i. e. the procedural way:
  3059. >>> def turn(x, y):
  3060. ... left(360)
  3061. ...
  3062. >>> onclick(turn) # Now clicking into the turtle will turn it.
  3063. >>> onclick(None) # event-binding will be removed
  3064. """
  3065. self.screen._onclick(self.turtle._item, fun, btn, add)
  3066. self._update()
  3067. def onrelease(self, fun, btn=1, add=None):
  3068. """Bind fun to mouse-button-release event on this turtle on canvas.
  3069. Arguments:
  3070. fun -- a function with two arguments, to which will be assigned
  3071. the coordinates of the clicked point on the canvas.
  3072. btn -- number of the mouse-button defaults to 1 (left mouse button).
  3073. Example (for a MyTurtle instance named joe):
  3074. >>> class MyTurtle(Turtle):
  3075. ... def glow(self,x,y):
  3076. ... self.fillcolor("red")
  3077. ... def unglow(self,x,y):
  3078. ... self.fillcolor("")
  3079. ...
  3080. >>> joe = MyTurtle()
  3081. >>> joe.onclick(joe.glow)
  3082. >>> joe.onrelease(joe.unglow)
  3083. Clicking on joe turns fillcolor red, unclicking turns it to
  3084. transparent.
  3085. """
  3086. self.screen._onrelease(self.turtle._item, fun, btn, add)
  3087. self._update()
  3088. def ondrag(self, fun, btn=1, add=None):
  3089. """Bind fun to mouse-move event on this turtle on canvas.
  3090. Arguments:
  3091. fun -- a function with two arguments, to which will be assigned
  3092. the coordinates of the clicked point on the canvas.
  3093. btn -- number of the mouse-button defaults to 1 (left mouse button).
  3094. Every sequence of mouse-move-events on a turtle is preceded by a
  3095. mouse-click event on that turtle.
  3096. Example (for a Turtle instance named turtle):
  3097. >>> turtle.ondrag(turtle.goto)
  3098. Subsequently clicking and dragging a Turtle will move it
  3099. across the screen thereby producing handdrawings (if pen is
  3100. down).
  3101. """
  3102. self.screen._ondrag(self.turtle._item, fun, btn, add)
  3103. def _undo(self, action, data):
  3104. """Does the main part of the work for undo()
  3105. """
  3106. if self.undobuffer is None:
  3107. return
  3108. if action == "rot":
  3109. angle, degPAU = data
  3110. self._rotate(-angle*degPAU/self._degreesPerAU)
  3111. dummy = self.undobuffer.pop()
  3112. elif action == "stamp":
  3113. stitem = data[0]
  3114. self.clearstamp(stitem)
  3115. elif action == "go":
  3116. self._undogoto(data)
  3117. elif action in ["wri", "dot"]:
  3118. item = data[0]
  3119. self.screen._delete(item)
  3120. self.items.remove(item)
  3121. elif action == "dofill":
  3122. item = data[0]
  3123. self.screen._drawpoly(item, ((0, 0),(0, 0),(0, 0)),
  3124. fill="", outline="")
  3125. elif action == "beginfill":
  3126. item = data[0]
  3127. self._fillitem = self._fillpath = None
  3128. if item in self.items:
  3129. self.screen._delete(item)
  3130. self.items.remove(item)
  3131. elif action == "pen":
  3132. TPen.pen(self, data[0])
  3133. self.undobuffer.pop()
  3134. def undo(self):
  3135. """undo (repeatedly) the last turtle action.
  3136. No argument.
  3137. undo (repeatedly) the last turtle action.
  3138. Number of available undo actions is determined by the size of
  3139. the undobuffer.
  3140. Example (for a Turtle instance named turtle):
  3141. >>> for i in range(4):
  3142. ... turtle.fd(50); turtle.lt(80)
  3143. ...
  3144. >>> for i in range(8):
  3145. ... turtle.undo()
  3146. ...
  3147. """
  3148. if self.undobuffer is None:
  3149. return
  3150. item = self.undobuffer.pop()
  3151. action = item[0]
  3152. data = item[1:]
  3153. if action == "seq":
  3154. while data:
  3155. item = data.pop()
  3156. self._undo(item[0], item[1:])
  3157. else:
  3158. self._undo(action, data)
  3159. turtlesize = shapesize
  3160. RawPen = RawTurtle
  3161. ### Screen - Singleton ########################
  3162. def Screen():
  3163. """Return the singleton screen object.
  3164. If none exists at the moment, create a new one and return it,
  3165. else return the existing one."""
  3166. if Turtle._screen is None:
  3167. Turtle._screen = _Screen()
  3168. return Turtle._screen
  3169. class _Screen(TurtleScreen):
  3170. _root = None
  3171. _canvas = None
  3172. _title = _CFG["title"]
  3173. def __init__(self):
  3174. if _Screen._root is None:
  3175. _Screen._root = self._root = _Root()
  3176. self._root.title(_Screen._title)
  3177. self._root.ondestroy(self._destroy)
  3178. if _Screen._canvas is None:
  3179. width = _CFG["width"]
  3180. height = _CFG["height"]
  3181. canvwidth = _CFG["canvwidth"]
  3182. canvheight = _CFG["canvheight"]
  3183. leftright = _CFG["leftright"]
  3184. topbottom = _CFG["topbottom"]
  3185. self._root.setupcanvas(width, height, canvwidth, canvheight)
  3186. _Screen._canvas = self._root._getcanvas()
  3187. TurtleScreen.__init__(self, _Screen._canvas)
  3188. self.setup(width, height, leftright, topbottom)
  3189. def setup(self, width=_CFG["width"], height=_CFG["height"],
  3190. startx=_CFG["leftright"], starty=_CFG["topbottom"]):
  3191. """ Set the size and position of the main window.
  3192. Arguments:
  3193. width: as integer a size in pixels, as float a fraction of the screen.
  3194. Default is 50% of screen.
  3195. height: as integer the height in pixels, as float a fraction of the
  3196. screen. Default is 75% of screen.
  3197. startx: if positive, starting position in pixels from the left
  3198. edge of the screen, if negative from the right edge
  3199. Default, startx=None is to center window horizontally.
  3200. starty: if positive, starting position in pixels from the top
  3201. edge of the screen, if negative from the bottom edge
  3202. Default, starty=None is to center window vertically.
  3203. Examples (for a Screen instance named screen):
  3204. >>> screen.setup (width=200, height=200, startx=0, starty=0)
  3205. sets window to 200x200 pixels, in upper left of screen
  3206. >>> screen.setup(width=.75, height=0.5, startx=None, starty=None)
  3207. sets window to 75% of screen by 50% of screen and centers
  3208. """
  3209. if not hasattr(self._root, "set_geometry"):
  3210. return
  3211. sw = self._root.win_width()
  3212. sh = self._root.win_height()
  3213. if isinstance(width, float) and 0 <= width <= 1:
  3214. width = sw*width
  3215. if startx is None:
  3216. startx = (sw - width) / 2
  3217. if isinstance(height, float) and 0 <= height <= 1:
  3218. height = sh*height
  3219. if starty is None:
  3220. starty = (sh - height) / 2
  3221. self._root.set_geometry(width, height, startx, starty)
  3222. self.update()
  3223. def title(self, titlestring):
  3224. """Set title of turtle-window
  3225. Argument:
  3226. titlestring -- a string, to appear in the titlebar of the
  3227. turtle graphics window.
  3228. This is a method of Screen-class. Not available for TurtleScreen-
  3229. objects.
  3230. Example (for a Screen instance named screen):
  3231. >>> screen.title("Welcome to the turtle-zoo!")
  3232. """
  3233. if _Screen._root is not None:
  3234. _Screen._root.title(titlestring)
  3235. _Screen._title = titlestring
  3236. def _destroy(self):
  3237. root = self._root
  3238. if root is _Screen._root:
  3239. Turtle._pen = None
  3240. Turtle._screen = None
  3241. _Screen._root = None
  3242. _Screen._canvas = None
  3243. TurtleScreen._RUNNING = False
  3244. root.destroy()
  3245. def bye(self):
  3246. """Shut the turtlegraphics window.
  3247. Example (for a TurtleScreen instance named screen):
  3248. >>> screen.bye()
  3249. """
  3250. self._destroy()
  3251. def exitonclick(self):
  3252. """Go into mainloop until the mouse is clicked.
  3253. No arguments.
  3254. Bind bye() method to mouseclick on TurtleScreen.
  3255. If "using_IDLE" - value in configuration dictionary is False
  3256. (default value), enter mainloop.
  3257. If IDLE with -n switch (no subprocess) is used, this value should be
  3258. set to True in turtle.cfg. In this case IDLE's mainloop
  3259. is active also for the client script.
  3260. This is a method of the Screen-class and not available for
  3261. TurtleScreen instances.
  3262. Example (for a Screen instance named screen):
  3263. >>> screen.exitonclick()
  3264. """
  3265. def exitGracefully(x, y):
  3266. """Screen.bye() with two dummy-parameters"""
  3267. self.bye()
  3268. self.onclick(exitGracefully)
  3269. if _CFG["using_IDLE"]:
  3270. return
  3271. try:
  3272. mainloop()
  3273. except AttributeError:
  3274. exit(0)
  3275. class Turtle(RawTurtle):
  3276. """RawTurtle auto-creating (scrolled) canvas.
  3277. When a Turtle object is created or a function derived from some
  3278. Turtle method is called a TurtleScreen object is automatically created.
  3279. """
  3280. _pen = None
  3281. _screen = None
  3282. def __init__(self,
  3283. shape=_CFG["shape"],
  3284. undobuffersize=_CFG["undobuffersize"],
  3285. visible=_CFG["visible"]):
  3286. if Turtle._screen is None:
  3287. Turtle._screen = Screen()
  3288. RawTurtle.__init__(self, Turtle._screen,
  3289. shape=shape,
  3290. undobuffersize=undobuffersize,
  3291. visible=visible)
  3292. Pen = Turtle
  3293. def write_docstringdict(filename="turtle_docstringdict"):
  3294. """Create and write docstring-dictionary to file.
  3295. Optional argument:
  3296. filename -- a string, used as filename
  3297. default value is turtle_docstringdict
  3298. Has to be called explicitly, (not used by the turtle-graphics classes)
  3299. The docstring dictionary will be written to the Python script <filename>.py
  3300. It is intended to serve as a template for translation of the docstrings
  3301. into different languages.
  3302. """
  3303. docsdict = {}
  3304. for methodname in _tg_screen_functions:
  3305. key = "_Screen."+methodname
  3306. docsdict[key] = eval(key).__doc__
  3307. for methodname in _tg_turtle_functions:
  3308. key = "Turtle."+methodname
  3309. docsdict[key] = eval(key).__doc__
  3310. with open("%s.py" % filename,"w") as f:
  3311. keys = sorted(x for x in docsdict
  3312. if x.split('.')[1] not in _alias_list)
  3313. f.write('docsdict = {\n\n')
  3314. for key in keys[:-1]:
  3315. f.write('%s :\n' % repr(key))
  3316. f.write(' """%s\n""",\n\n' % docsdict[key])
  3317. key = keys[-1]
  3318. f.write('%s :\n' % repr(key))
  3319. f.write(' """%s\n"""\n\n' % docsdict[key])
  3320. f.write("}\n")
  3321. f.close()
  3322. def read_docstrings(lang):
  3323. """Read in docstrings from lang-specific docstring dictionary.
  3324. Transfer docstrings, translated to lang, from a dictionary-file
  3325. to the methods of classes Screen and Turtle and - in revised form -
  3326. to the corresponding functions.
  3327. """
  3328. modname = "turtle_docstringdict_%(language)s" % {'language':lang.lower()}
  3329. module = __import__(modname)
  3330. docsdict = module.docsdict
  3331. for key in docsdict:
  3332. try:
  3333. # eval(key).im_func.__doc__ = docsdict[key]
  3334. eval(key).__doc__ = docsdict[key]
  3335. except Exception:
  3336. print("Bad docstring-entry: %s" % key)
  3337. _LANGUAGE = _CFG["language"]
  3338. try:
  3339. if _LANGUAGE != "english":
  3340. read_docstrings(_LANGUAGE)
  3341. except ImportError:
  3342. print("Cannot find docsdict for", _LANGUAGE)
  3343. except Exception:
  3344. print ("Unknown Error when trying to import %s-docstring-dictionary" %
  3345. _LANGUAGE)
  3346. def getmethparlist(ob):
  3347. """Get strings describing the arguments for the given object
  3348. Returns a pair of strings representing function parameter lists
  3349. including parenthesis. The first string is suitable for use in
  3350. function definition and the second is suitable for use in function
  3351. call. The "self" parameter is not included.
  3352. """
  3353. orig_sig = inspect.signature(ob)
  3354. # bit of a hack for methods - turn it into a function
  3355. # but we drop the "self" param.
  3356. # Try and build one for Python defined functions
  3357. func_sig = orig_sig.replace(
  3358. parameters=list(orig_sig.parameters.values())[1:],
  3359. )
  3360. call_args = []
  3361. for param in func_sig.parameters.values():
  3362. match param.kind:
  3363. case (
  3364. inspect.Parameter.POSITIONAL_ONLY
  3365. | inspect.Parameter.POSITIONAL_OR_KEYWORD
  3366. ):
  3367. call_args.append(param.name)
  3368. case inspect.Parameter.VAR_POSITIONAL:
  3369. call_args.append(f'*{param.name}')
  3370. case inspect.Parameter.KEYWORD_ONLY:
  3371. call_args.append(f'{param.name}={param.name}')
  3372. case inspect.Parameter.VAR_KEYWORD:
  3373. call_args.append(f'**{param.name}')
  3374. case _:
  3375. raise RuntimeError('Unsupported parameter kind', param.kind)
  3376. call_text = f'({', '.join(call_args)})'
  3377. return str(func_sig), call_text
  3378. def _turtle_docrevise(docstr):
  3379. """To reduce docstrings from RawTurtle class for functions
  3380. """
  3381. import re
  3382. if docstr is None:
  3383. return None
  3384. turtlename = _CFG["exampleturtle"]
  3385. newdocstr = docstr.replace("%s." % turtlename,"")
  3386. parexp = re.compile(r' \(.+ %s\):' % turtlename)
  3387. newdocstr = parexp.sub(":", newdocstr)
  3388. return newdocstr
  3389. def _screen_docrevise(docstr):
  3390. """To reduce docstrings from TurtleScreen class for functions
  3391. """
  3392. import re
  3393. if docstr is None:
  3394. return None
  3395. screenname = _CFG["examplescreen"]
  3396. newdocstr = docstr.replace("%s." % screenname,"")
  3397. parexp = re.compile(r' \(.+ %s\):' % screenname)
  3398. newdocstr = parexp.sub(":", newdocstr)
  3399. return newdocstr
  3400. ## The following mechanism makes all methods of RawTurtle and Turtle available
  3401. ## as functions. So we can enhance, change, add, delete methods to these
  3402. ## classes and do not need to change anything here.
  3403. __func_body = """\
  3404. def {name}{paramslist}:
  3405. if {obj} is None:
  3406. if not TurtleScreen._RUNNING:
  3407. TurtleScreen._RUNNING = True
  3408. raise Terminator
  3409. {obj} = {init}
  3410. try:
  3411. return {obj}.{name}{argslist}
  3412. except TK.TclError:
  3413. if not TurtleScreen._RUNNING:
  3414. TurtleScreen._RUNNING = True
  3415. raise Terminator
  3416. raise
  3417. """
  3418. def _make_global_funcs(functions, cls, obj, init, docrevise):
  3419. for methodname in functions:
  3420. method = getattr(cls, methodname)
  3421. pl1, pl2 = getmethparlist(method)
  3422. if pl1 == "":
  3423. print(">>>>>>", pl1, pl2)
  3424. continue
  3425. defstr = __func_body.format(obj=obj, init=init, name=methodname,
  3426. paramslist=pl1, argslist=pl2)
  3427. exec(defstr, globals())
  3428. globals()[methodname].__doc__ = docrevise(method.__doc__)
  3429. _make_global_funcs(_tg_screen_functions, _Screen,
  3430. 'Turtle._screen', 'Screen()', _screen_docrevise)
  3431. _make_global_funcs(_tg_turtle_functions, Turtle,
  3432. 'Turtle._pen', 'Turtle()', _turtle_docrevise)
  3433. done = mainloop
  3434. if __name__ == "__main__":
  3435. def switchpen():
  3436. if isdown():
  3437. pu()
  3438. else:
  3439. pd()
  3440. def demo1():
  3441. """Demo of old turtle.py - module"""
  3442. reset()
  3443. tracer(True)
  3444. up()
  3445. backward(100)
  3446. down()
  3447. # draw 3 squares; the last filled
  3448. width(3)
  3449. for i in range(3):
  3450. if i == 2:
  3451. begin_fill()
  3452. for _ in range(4):
  3453. forward(20)
  3454. left(90)
  3455. if i == 2:
  3456. color("maroon")
  3457. end_fill()
  3458. up()
  3459. forward(30)
  3460. down()
  3461. width(1)
  3462. color("black")
  3463. # move out of the way
  3464. tracer(False)
  3465. up()
  3466. right(90)
  3467. forward(100)
  3468. right(90)
  3469. forward(100)
  3470. right(180)
  3471. down()
  3472. # some text
  3473. write("startstart", 1)
  3474. write("start", 1)
  3475. color("red")
  3476. # staircase
  3477. for i in range(5):
  3478. forward(20)
  3479. left(90)
  3480. forward(20)
  3481. right(90)
  3482. # filled staircase
  3483. tracer(True)
  3484. begin_fill()
  3485. for i in range(5):
  3486. forward(20)
  3487. left(90)
  3488. forward(20)
  3489. right(90)
  3490. end_fill()
  3491. # more text
  3492. def demo2():
  3493. """Demo of some new features."""
  3494. speed(1)
  3495. st()
  3496. pensize(3)
  3497. setheading(towards(0, 0))
  3498. radius = distance(0, 0)/2.0
  3499. rt(90)
  3500. for _ in range(18):
  3501. switchpen()
  3502. circle(radius, 10)
  3503. write("wait a moment...")
  3504. while undobufferentries():
  3505. undo()
  3506. reset()
  3507. lt(90)
  3508. colormode(255)
  3509. laenge = 10
  3510. pencolor("green")
  3511. pensize(3)
  3512. lt(180)
  3513. for i in range(-2, 16):
  3514. if i > 0:
  3515. begin_fill()
  3516. fillcolor(255-15*i, 0, 15*i)
  3517. for _ in range(3):
  3518. fd(laenge)
  3519. lt(120)
  3520. end_fill()
  3521. laenge += 10
  3522. lt(15)
  3523. speed((speed()+1)%12)
  3524. #end_fill()
  3525. lt(120)
  3526. pu()
  3527. fd(70)
  3528. rt(30)
  3529. pd()
  3530. color("red","yellow")
  3531. speed(0)
  3532. begin_fill()
  3533. for _ in range(4):
  3534. circle(50, 90)
  3535. rt(90)
  3536. fd(30)
  3537. rt(90)
  3538. end_fill()
  3539. lt(90)
  3540. pu()
  3541. fd(30)
  3542. pd()
  3543. shape("turtle")
  3544. tri = getturtle()
  3545. tri.resizemode("auto")
  3546. turtle = Turtle()
  3547. turtle.resizemode("auto")
  3548. turtle.shape("turtle")
  3549. turtle.reset()
  3550. turtle.left(90)
  3551. turtle.speed(0)
  3552. turtle.up()
  3553. turtle.goto(280, 40)
  3554. turtle.lt(30)
  3555. turtle.down()
  3556. turtle.speed(6)
  3557. turtle.color("blue","orange")
  3558. turtle.pensize(2)
  3559. tri.speed(6)
  3560. setheading(towards(turtle))
  3561. count = 1
  3562. while tri.distance(turtle) > 4:
  3563. turtle.fd(3.5)
  3564. turtle.lt(0.6)
  3565. tri.setheading(tri.towards(turtle))
  3566. tri.fd(4)
  3567. if count % 20 == 0:
  3568. turtle.stamp()
  3569. tri.stamp()
  3570. switchpen()
  3571. count += 1
  3572. tri.write("CAUGHT! ", font=("Arial", 16, "bold"), align="right")
  3573. tri.pencolor("black")
  3574. tri.pencolor("red")
  3575. def baba(xdummy, ydummy):
  3576. clearscreen()
  3577. bye()
  3578. time.sleep(2)
  3579. while undobufferentries():
  3580. tri.undo()
  3581. turtle.undo()
  3582. tri.fd(50)
  3583. tri.write(" Click me!", font = ("Courier", 12, "bold") )
  3584. tri.onclick(baba, 1)
  3585. demo1()
  3586. demo2()
  3587. exitonclick()