turtle.py 140 KB

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