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: http://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. @staticmethod
  396. def _blankimage():
  397. """return a blank image object
  398. """
  399. img = TK.PhotoImage(width=1, height=1)
  400. img.blank()
  401. return img
  402. @staticmethod
  403. def _image(filename):
  404. """return an image object containing the
  405. imagedata from a gif-file named filename.
  406. """
  407. return TK.PhotoImage(file=filename)
  408. def __init__(self, cv):
  409. self.cv = cv
  410. if isinstance(cv, ScrolledCanvas):
  411. w = self.cv.canvwidth
  412. h = self.cv.canvheight
  413. else: # expected: ordinary TK.Canvas
  414. w = int(self.cv.cget("width"))
  415. h = int(self.cv.cget("height"))
  416. self.cv.config(scrollregion = (-w//2, -h//2, w//2, h//2 ))
  417. self.canvwidth = w
  418. self.canvheight = h
  419. self.xscale = self.yscale = 1.0
  420. def _createpoly(self):
  421. """Create an invisible polygon item on canvas self.cv)
  422. """
  423. return self.cv.create_polygon((0, 0, 0, 0, 0, 0), fill="", outline="")
  424. def _drawpoly(self, polyitem, coordlist, fill=None,
  425. outline=None, width=None, top=False):
  426. """Configure polygonitem polyitem according to provided
  427. arguments:
  428. coordlist is sequence of coordinates
  429. fill is filling color
  430. outline is outline color
  431. top is a boolean value, which specifies if polyitem
  432. will be put on top of the canvas' displaylist so it
  433. will not be covered by other items.
  434. """
  435. cl = []
  436. for x, y in coordlist:
  437. cl.append(x * self.xscale)
  438. cl.append(-y * self.yscale)
  439. self.cv.coords(polyitem, *cl)
  440. if fill is not None:
  441. self.cv.itemconfigure(polyitem, fill=fill)
  442. if outline is not None:
  443. self.cv.itemconfigure(polyitem, outline=outline)
  444. if width is not None:
  445. self.cv.itemconfigure(polyitem, width=width)
  446. if top:
  447. self.cv.tag_raise(polyitem)
  448. def _createline(self):
  449. """Create an invisible line item on canvas self.cv)
  450. """
  451. return self.cv.create_line(0, 0, 0, 0, fill="", width=2,
  452. capstyle = TK.ROUND)
  453. def _drawline(self, lineitem, coordlist=None,
  454. fill=None, width=None, top=False):
  455. """Configure lineitem according to provided arguments:
  456. coordlist is sequence of coordinates
  457. fill is drawing color
  458. width is width of drawn line.
  459. top is a boolean value, which specifies if polyitem
  460. will be put on top of the canvas' displaylist so it
  461. will not be covered by other items.
  462. """
  463. if coordlist is not None:
  464. cl = []
  465. for x, y in coordlist:
  466. cl.append(x * self.xscale)
  467. cl.append(-y * self.yscale)
  468. self.cv.coords(lineitem, *cl)
  469. if fill is not None:
  470. self.cv.itemconfigure(lineitem, fill=fill)
  471. if width is not None:
  472. self.cv.itemconfigure(lineitem, width=width)
  473. if top:
  474. self.cv.tag_raise(lineitem)
  475. def _delete(self, item):
  476. """Delete graphics item from canvas.
  477. If item is"all" delete all graphics items.
  478. """
  479. self.cv.delete(item)
  480. def _update(self):
  481. """Redraw graphics items on canvas
  482. """
  483. self.cv.update()
  484. def _delay(self, delay):
  485. """Delay subsequent canvas actions for delay ms."""
  486. self.cv.after(delay)
  487. def _iscolorstring(self, color):
  488. """Check if the string color is a legal Tkinter color string.
  489. """
  490. try:
  491. rgb = self.cv.winfo_rgb(color)
  492. ok = True
  493. except TK.TclError:
  494. ok = False
  495. return ok
  496. def _bgcolor(self, color=None):
  497. """Set canvas' backgroundcolor if color is not None,
  498. else return backgroundcolor."""
  499. if color is not None:
  500. self.cv.config(bg = color)
  501. self._update()
  502. else:
  503. return self.cv.cget("bg")
  504. def _write(self, pos, txt, align, font, pencolor):
  505. """Write txt at pos in canvas with specified font
  506. and color.
  507. Return text item and x-coord of right bottom corner
  508. of text's bounding box."""
  509. x, y = pos
  510. x = x * self.xscale
  511. y = y * self.yscale
  512. anchor = {"left":"sw", "center":"s", "right":"se" }
  513. item = self.cv.create_text(x-1, -y, text = txt, anchor = anchor[align],
  514. fill = pencolor, font = font)
  515. x0, y0, x1, y1 = self.cv.bbox(item)
  516. self.cv.update()
  517. return item, x1-1
  518. ## def _dot(self, pos, size, color):
  519. ## """may be implemented for some other graphics toolkit"""
  520. def _onclick(self, item, fun, num=1, add=None):
  521. """Bind fun to mouse-click event on turtle.
  522. fun must be a function with two arguments, the coordinates
  523. of the clicked point on the canvas.
  524. num, the number of the mouse-button defaults to 1
  525. """
  526. if fun is None:
  527. self.cv.tag_unbind(item, "<Button-%s>" % num)
  528. else:
  529. def eventfun(event):
  530. x, y = (self.cv.canvasx(event.x)/self.xscale,
  531. -self.cv.canvasy(event.y)/self.yscale)
  532. fun(x, y)
  533. self.cv.tag_bind(item, "<Button-%s>" % num, eventfun, add)
  534. def _onrelease(self, item, fun, num=1, add=None):
  535. """Bind fun to mouse-button-release event on turtle.
  536. fun must be a function with two arguments, the coordinates
  537. of the point on the canvas where mouse button is released.
  538. num, the number of the mouse-button defaults to 1
  539. If a turtle is clicked, first _onclick-event will be performed,
  540. then _onscreensclick-event.
  541. """
  542. if fun is None:
  543. self.cv.tag_unbind(item, "<Button%s-ButtonRelease>" % num)
  544. else:
  545. def eventfun(event):
  546. x, y = (self.cv.canvasx(event.x)/self.xscale,
  547. -self.cv.canvasy(event.y)/self.yscale)
  548. fun(x, y)
  549. self.cv.tag_bind(item, "<Button%s-ButtonRelease>" % num,
  550. eventfun, add)
  551. def _ondrag(self, item, fun, num=1, add=None):
  552. """Bind fun to mouse-move-event (with pressed mouse button) on turtle.
  553. fun must be a function with two arguments, the coordinates of the
  554. actual mouse position on the canvas.
  555. num, the number of the mouse-button defaults to 1
  556. Every sequence of mouse-move-events on a turtle is preceded by a
  557. mouse-click event on that turtle.
  558. """
  559. if fun is None:
  560. self.cv.tag_unbind(item, "<Button%s-Motion>" % num)
  561. else:
  562. def eventfun(event):
  563. try:
  564. x, y = (self.cv.canvasx(event.x)/self.xscale,
  565. -self.cv.canvasy(event.y)/self.yscale)
  566. fun(x, y)
  567. except Exception:
  568. pass
  569. self.cv.tag_bind(item, "<Button%s-Motion>" % num, eventfun, add)
  570. def _onscreenclick(self, fun, num=1, add=None):
  571. """Bind fun to mouse-click event on canvas.
  572. fun must be a function with two arguments, the coordinates
  573. of the clicked point on the canvas.
  574. num, the number of the mouse-button defaults to 1
  575. If a turtle is clicked, first _onclick-event will be performed,
  576. then _onscreensclick-event.
  577. """
  578. if fun is None:
  579. self.cv.unbind("<Button-%s>" % num)
  580. else:
  581. def eventfun(event):
  582. x, y = (self.cv.canvasx(event.x)/self.xscale,
  583. -self.cv.canvasy(event.y)/self.yscale)
  584. fun(x, y)
  585. self.cv.bind("<Button-%s>" % num, eventfun, add)
  586. def _onkeyrelease(self, fun, key):
  587. """Bind fun to key-release event of key.
  588. Canvas must have focus. See method listen
  589. """
  590. if fun is None:
  591. self.cv.unbind("<KeyRelease-%s>" % key, None)
  592. else:
  593. def eventfun(event):
  594. fun()
  595. self.cv.bind("<KeyRelease-%s>" % key, eventfun)
  596. def _onkeypress(self, fun, key=None):
  597. """If key is given, bind fun to key-press event of key.
  598. Otherwise bind fun to any key-press.
  599. Canvas must have focus. See method listen.
  600. """
  601. if fun is None:
  602. if key is None:
  603. self.cv.unbind("<KeyPress>", None)
  604. else:
  605. self.cv.unbind("<KeyPress-%s>" % key, None)
  606. else:
  607. def eventfun(event):
  608. fun()
  609. if key is None:
  610. self.cv.bind("<KeyPress>", eventfun)
  611. else:
  612. self.cv.bind("<KeyPress-%s>" % key, eventfun)
  613. def _listen(self):
  614. """Set focus on canvas (in order to collect key-events)
  615. """
  616. self.cv.focus_force()
  617. def _ontimer(self, fun, t):
  618. """Install a timer, which calls fun after t milliseconds.
  619. """
  620. if t == 0:
  621. self.cv.after_idle(fun)
  622. else:
  623. self.cv.after(t, fun)
  624. def _createimage(self, image):
  625. """Create and return image item on canvas.
  626. """
  627. return self.cv.create_image(0, 0, image=image)
  628. def _drawimage(self, item, pos, image):
  629. """Configure image item as to draw image object
  630. at position (x,y) on canvas)
  631. """
  632. x, y = pos
  633. self.cv.coords(item, (x * self.xscale, -y * self.yscale))
  634. self.cv.itemconfig(item, image=image)
  635. def _setbgpic(self, item, image):
  636. """Configure image item as to draw image object
  637. at center of canvas. Set item to the first item
  638. in the displaylist, so it will be drawn below
  639. any other item ."""
  640. self.cv.itemconfig(item, image=image)
  641. self.cv.tag_lower(item)
  642. def _type(self, item):
  643. """Return 'line' or 'polygon' or 'image' depending on
  644. type of item.
  645. """
  646. return self.cv.type(item)
  647. def _pointlist(self, item):
  648. """returns list of coordinate-pairs of points of item
  649. Example (for insiders):
  650. >>> from turtle import *
  651. >>> getscreen()._pointlist(getturtle().turtle._item)
  652. [(0.0, 9.9999999999999982), (0.0, -9.9999999999999982),
  653. (9.9999999999999982, 0.0)]
  654. >>> """
  655. cl = self.cv.coords(item)
  656. pl = [(cl[i], -cl[i+1]) for i in range(0, len(cl), 2)]
  657. return pl
  658. def _setscrollregion(self, srx1, sry1, srx2, sry2):
  659. self.cv.config(scrollregion=(srx1, sry1, srx2, sry2))
  660. def _rescale(self, xscalefactor, yscalefactor):
  661. items = self.cv.find_all()
  662. for item in items:
  663. coordinates = list(self.cv.coords(item))
  664. newcoordlist = []
  665. while coordinates:
  666. x, y = coordinates[:2]
  667. newcoordlist.append(x * xscalefactor)
  668. newcoordlist.append(y * yscalefactor)
  669. coordinates = coordinates[2:]
  670. self.cv.coords(item, *newcoordlist)
  671. def _resize(self, canvwidth=None, canvheight=None, bg=None):
  672. """Resize the canvas the turtles are drawing on. Does
  673. not alter the drawing window.
  674. """
  675. # needs amendment
  676. if not isinstance(self.cv, ScrolledCanvas):
  677. return self.canvwidth, self.canvheight
  678. if canvwidth is canvheight is bg is None:
  679. return self.cv.canvwidth, self.cv.canvheight
  680. if canvwidth is not None:
  681. self.canvwidth = canvwidth
  682. if canvheight is not None:
  683. self.canvheight = canvheight
  684. self.cv.reset(canvwidth, canvheight, bg)
  685. def _window_size(self):
  686. """ Return the width and height of the turtle window.
  687. """
  688. width = self.cv.winfo_width()
  689. if width <= 1: # the window isn't managed by a geometry manager
  690. width = self.cv['width']
  691. height = self.cv.winfo_height()
  692. if height <= 1: # the window isn't managed by a geometry manager
  693. height = self.cv['height']
  694. return width, height
  695. def mainloop(self):
  696. """Starts event loop - calling Tkinter's mainloop function.
  697. No argument.
  698. Must be last statement in a turtle graphics program.
  699. Must NOT be used if a script is run from within IDLE in -n mode
  700. (No subprocess) - for interactive use of turtle graphics.
  701. Example (for a TurtleScreen instance named screen):
  702. >>> screen.mainloop()
  703. """
  704. TK.mainloop()
  705. def textinput(self, title, prompt):
  706. """Pop up a dialog window for input of a string.
  707. Arguments: title is the title of the dialog window,
  708. prompt is a text mostly describing what information to input.
  709. Return the string input
  710. If the dialog is canceled, return None.
  711. Example (for a TurtleScreen instance named screen):
  712. >>> screen.textinput("NIM", "Name of first player:")
  713. """
  714. return simpledialog.askstring(title, prompt)
  715. def numinput(self, title, prompt, default=None, minval=None, maxval=None):
  716. """Pop up a dialog window for input of a number.
  717. Arguments: title is the title of the dialog window,
  718. prompt is a text mostly describing what numerical information to input.
  719. default: default value
  720. minval: minimum value for input
  721. maxval: maximum value for input
  722. The number input must be in the range minval .. maxval if these are
  723. given. If not, a hint is issued and the dialog remains open for
  724. correction. Return the number input.
  725. If the dialog is canceled, return None.
  726. Example (for a TurtleScreen instance named screen):
  727. >>> screen.numinput("Poker", "Your stakes:", 1000, minval=10, maxval=10000)
  728. """
  729. return simpledialog.askfloat(title, prompt, initialvalue=default,
  730. minvalue=minval, maxvalue=maxval)
  731. ##############################################################################
  732. ### End of Tkinter - interface ###
  733. ##############################################################################
  734. class Terminator (Exception):
  735. """Will be raised in TurtleScreen.update, if _RUNNING becomes False.
  736. This stops execution of a turtle graphics script.
  737. Main purpose: use in the Demo-Viewer turtle.Demo.py.
  738. """
  739. pass
  740. class TurtleGraphicsError(Exception):
  741. """Some TurtleGraphics Error
  742. """
  743. class Shape(object):
  744. """Data structure modeling shapes.
  745. attribute _type is one of "polygon", "image", "compound"
  746. attribute _data is - depending on _type a poygon-tuple,
  747. an image or a list constructed using the addcomponent method.
  748. """
  749. def __init__(self, type_, data=None):
  750. self._type = type_
  751. if type_ == "polygon":
  752. if isinstance(data, list):
  753. data = tuple(data)
  754. elif type_ == "image":
  755. if isinstance(data, str):
  756. if data.lower().endswith(".gif") and isfile(data):
  757. data = TurtleScreen._image(data)
  758. # else data assumed to be Photoimage
  759. elif type_ == "compound":
  760. data = []
  761. else:
  762. raise TurtleGraphicsError("There is no shape type %s" % type_)
  763. self._data = data
  764. def addcomponent(self, poly, fill, outline=None):
  765. """Add component to a shape of type compound.
  766. Arguments: poly is a polygon, i. e. a tuple of number pairs.
  767. fill is the fillcolor of the component,
  768. outline is the outline color of the component.
  769. call (for a Shapeobject namend s):
  770. -- s.addcomponent(((0,0), (10,10), (-10,10)), "red", "blue")
  771. Example:
  772. >>> poly = ((0,0),(10,-5),(0,10),(-10,-5))
  773. >>> s = Shape("compound")
  774. >>> s.addcomponent(poly, "red", "blue")
  775. >>> # .. add more components and then use register_shape()
  776. """
  777. if self._type != "compound":
  778. raise TurtleGraphicsError("Cannot add component to %s Shape"
  779. % self._type)
  780. if outline is None:
  781. outline = fill
  782. self._data.append([poly, fill, outline])
  783. class Tbuffer(object):
  784. """Ring buffer used as undobuffer for RawTurtle objects."""
  785. def __init__(self, bufsize=10):
  786. self.bufsize = bufsize
  787. self.buffer = [[None]] * bufsize
  788. self.ptr = -1
  789. self.cumulate = False
  790. def reset(self, bufsize=None):
  791. if bufsize is None:
  792. for i in range(self.bufsize):
  793. self.buffer[i] = [None]
  794. else:
  795. self.bufsize = bufsize
  796. self.buffer = [[None]] * bufsize
  797. self.ptr = -1
  798. def push(self, item):
  799. if self.bufsize > 0:
  800. if not self.cumulate:
  801. self.ptr = (self.ptr + 1) % self.bufsize
  802. self.buffer[self.ptr] = item
  803. else:
  804. self.buffer[self.ptr].append(item)
  805. def pop(self):
  806. if self.bufsize > 0:
  807. item = self.buffer[self.ptr]
  808. if item is None:
  809. return None
  810. else:
  811. self.buffer[self.ptr] = [None]
  812. self.ptr = (self.ptr - 1) % self.bufsize
  813. return (item)
  814. def nr_of_items(self):
  815. return self.bufsize - self.buffer.count([None])
  816. def __repr__(self):
  817. return str(self.buffer) + " " + str(self.ptr)
  818. class TurtleScreen(TurtleScreenBase):
  819. """Provides screen oriented methods like setbg etc.
  820. Only relies upon the methods of TurtleScreenBase and NOT
  821. upon components of the underlying graphics toolkit -
  822. which is Tkinter in this case.
  823. """
  824. _RUNNING = True
  825. def __init__(self, cv, mode=_CFG["mode"],
  826. colormode=_CFG["colormode"], delay=_CFG["delay"]):
  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. TurtleScreenBase.__init__(self, cv)
  849. self._mode = mode
  850. self._delayvalue = delay
  851. self._colormode = _CFG["colormode"]
  852. self._keys = []
  853. self.clear()
  854. if sys.platform == 'darwin':
  855. # Force Turtle window to the front on OS X. This is needed because
  856. # the Turtle window will show behind the Terminal window when you
  857. # start the demo from the command line.
  858. rootwindow = cv.winfo_toplevel()
  859. rootwindow.call('wm', 'attributes', '.', '-topmost', '1')
  860. rootwindow.call('wm', 'attributes', '.', '-topmost', '0')
  861. def clear(self):
  862. """Delete all drawings and all turtles from the TurtleScreen.
  863. No argument.
  864. Reset empty TurtleScreen to its initial state: white background,
  865. no backgroundimage, no eventbindings and tracing on.
  866. Example (for a TurtleScreen instance named screen):
  867. >>> screen.clear()
  868. Note: this method is not available as function.
  869. """
  870. self._delayvalue = _CFG["delay"]
  871. self._colormode = _CFG["colormode"]
  872. self._delete("all")
  873. self._bgpic = self._createimage("")
  874. self._bgpicname = "nopic"
  875. self._tracing = 1
  876. self._updatecounter = 0
  877. self._turtles = []
  878. self.bgcolor("white")
  879. for btn in 1, 2, 3:
  880. self.onclick(None, btn)
  881. self.onkeypress(None)
  882. for key in self._keys[:]:
  883. self.onkey(None, key)
  884. self.onkeypress(None, key)
  885. Turtle._pen = None
  886. def mode(self, mode=None):
  887. """Set turtle-mode ('standard', 'logo' or 'world') and perform reset.
  888. Optional argument:
  889. mode -- one of the strings 'standard', 'logo' or 'world'
  890. Mode 'standard' is compatible with turtle.py.
  891. Mode 'logo' is compatible with most Logo-Turtle-Graphics.
  892. Mode 'world' uses userdefined 'worldcoordinates'. *Attention*: in
  893. this mode angles appear distorted if x/y unit-ratio doesn't equal 1.
  894. If mode is not given, return the current mode.
  895. Mode Initial turtle heading positive angles
  896. ------------|-------------------------|-------------------
  897. 'standard' to the right (east) counterclockwise
  898. 'logo' upward (north) clockwise
  899. Examples:
  900. >>> mode('logo') # resets turtle heading to north
  901. >>> mode()
  902. 'logo'
  903. """
  904. if mode is None:
  905. return self._mode
  906. mode = mode.lower()
  907. if mode not in ["standard", "logo", "world"]:
  908. raise TurtleGraphicsError("No turtle-graphics-mode %s" % mode)
  909. self._mode = mode
  910. if mode in ["standard", "logo"]:
  911. self._setscrollregion(-self.canvwidth//2, -self.canvheight//2,
  912. self.canvwidth//2, self.canvheight//2)
  913. self.xscale = self.yscale = 1.0
  914. self.reset()
  915. def setworldcoordinates(self, llx, lly, urx, ury):
  916. """Set up a user defined coordinate-system.
  917. Arguments:
  918. llx -- a number, x-coordinate of lower left corner of canvas
  919. lly -- a number, y-coordinate of lower left corner of canvas
  920. urx -- a number, x-coordinate of upper right corner of canvas
  921. ury -- a number, y-coordinate of upper right corner of canvas
  922. Set up user coodinat-system and switch to mode 'world' if necessary.
  923. This performs a screen.reset. If mode 'world' is already active,
  924. all drawings are redrawn according to the new coordinates.
  925. But ATTENTION: in user-defined coordinatesystems angles may appear
  926. distorted. (see Screen.mode())
  927. Example (for a TurtleScreen instance named screen):
  928. >>> screen.setworldcoordinates(-10,-0.5,50,1.5)
  929. >>> for _ in range(36):
  930. ... left(10)
  931. ... forward(0.5)
  932. """
  933. if self.mode() != "world":
  934. self.mode("world")
  935. xspan = float(urx - llx)
  936. yspan = float(ury - lly)
  937. wx, wy = self._window_size()
  938. self.screensize(wx-20, wy-20)
  939. oldxscale, oldyscale = self.xscale, self.yscale
  940. self.xscale = self.canvwidth / xspan
  941. self.yscale = self.canvheight / yspan
  942. srx1 = llx * self.xscale
  943. sry1 = -ury * self.yscale
  944. srx2 = self.canvwidth + srx1
  945. sry2 = self.canvheight + sry1
  946. self._setscrollregion(srx1, sry1, srx2, sry2)
  947. self._rescale(self.xscale/oldxscale, self.yscale/oldyscale)
  948. self.update()
  949. def register_shape(self, name, shape=None):
  950. """Adds a turtle shape to TurtleScreen's shapelist.
  951. Arguments:
  952. (1) name is the name of a gif-file and shape is None.
  953. Installs the corresponding image shape.
  954. !! Image-shapes DO NOT rotate when turning the turtle,
  955. !! so they do not display the heading of the turtle!
  956. (2) name is an arbitrary string and shape is a tuple
  957. of pairs of coordinates. Installs the corresponding
  958. polygon shape
  959. (3) name is an arbitrary string and shape is a
  960. (compound) Shape object. Installs the corresponding
  961. compound shape.
  962. To use a shape, you have to issue the command shape(shapename).
  963. call: register_shape("turtle.gif")
  964. --or: register_shape("tri", ((0,0), (10,10), (-10,10)))
  965. Example (for a TurtleScreen instance named screen):
  966. >>> screen.register_shape("triangle", ((5,-3),(0,5),(-5,-3)))
  967. """
  968. if shape is None:
  969. # image
  970. if name.lower().endswith(".gif"):
  971. shape = Shape("image", self._image(name))
  972. else:
  973. raise TurtleGraphicsError("Bad arguments for register_shape.\n"
  974. + "Use help(register_shape)" )
  975. elif isinstance(shape, tuple):
  976. shape = Shape("polygon", shape)
  977. ## else shape assumed to be Shape-instance
  978. self._shapes[name] = shape
  979. def _colorstr(self, color):
  980. """Return color string corresponding to args.
  981. Argument may be a string or a tuple of three
  982. numbers corresponding to actual colormode,
  983. i.e. in the range 0<=n<=colormode.
  984. If the argument doesn't represent a color,
  985. an error is raised.
  986. """
  987. if len(color) == 1:
  988. color = color[0]
  989. if isinstance(color, str):
  990. if self._iscolorstring(color) or color == "":
  991. return color
  992. else:
  993. raise TurtleGraphicsError("bad color string: %s" % str(color))
  994. try:
  995. r, g, b = color
  996. except (TypeError, ValueError):
  997. raise TurtleGraphicsError("bad color arguments: %s" % str(color))
  998. if self._colormode == 1.0:
  999. r, g, b = [round(255.0*x) for x in (r, g, b)]
  1000. if not ((0 <= r <= 255) and (0 <= g <= 255) and (0 <= b <= 255)):
  1001. raise TurtleGraphicsError("bad color sequence: %s" % str(color))
  1002. return "#%02x%02x%02x" % (r, g, b)
  1003. def _color(self, cstr):
  1004. if not cstr.startswith("#"):
  1005. return cstr
  1006. if len(cstr) == 7:
  1007. cl = [int(cstr[i:i+2], 16) for i in (1, 3, 5)]
  1008. elif len(cstr) == 4:
  1009. cl = [16*int(cstr[h], 16) for h in cstr[1:]]
  1010. else:
  1011. raise TurtleGraphicsError("bad colorstring: %s" % cstr)
  1012. return tuple(c * self._colormode/255 for c in cl)
  1013. def colormode(self, cmode=None):
  1014. """Return the colormode or set it to 1.0 or 255.
  1015. Optional argument:
  1016. cmode -- one of the values 1.0 or 255
  1017. r, g, b values of colortriples have to be in range 0..cmode.
  1018. Example (for a TurtleScreen instance named screen):
  1019. >>> screen.colormode()
  1020. 1.0
  1021. >>> screen.colormode(255)
  1022. >>> pencolor(240,160,80)
  1023. """
  1024. if cmode is None:
  1025. return self._colormode
  1026. if cmode == 1.0:
  1027. self._colormode = float(cmode)
  1028. elif cmode == 255:
  1029. self._colormode = int(cmode)
  1030. def reset(self):
  1031. """Reset all Turtles on the Screen to their initial state.
  1032. No argument.
  1033. Example (for a TurtleScreen instance named screen):
  1034. >>> screen.reset()
  1035. """
  1036. for turtle in self._turtles:
  1037. turtle._setmode(self._mode)
  1038. turtle.reset()
  1039. def turtles(self):
  1040. """Return the list of turtles on the screen.
  1041. Example (for a TurtleScreen instance named screen):
  1042. >>> screen.turtles()
  1043. [<turtle.Turtle object at 0x00E11FB0>]
  1044. """
  1045. return self._turtles
  1046. def bgcolor(self, *args):
  1047. """Set or return backgroundcolor of the TurtleScreen.
  1048. Arguments (if given): a color string or three numbers
  1049. in the range 0..colormode or a 3-tuple of such numbers.
  1050. Example (for a TurtleScreen instance named screen):
  1051. >>> screen.bgcolor("orange")
  1052. >>> screen.bgcolor()
  1053. 'orange'
  1054. >>> screen.bgcolor(0.5,0,0.5)
  1055. >>> screen.bgcolor()
  1056. '#800080'
  1057. """
  1058. if args:
  1059. color = self._colorstr(args)
  1060. else:
  1061. color = None
  1062. color = self._bgcolor(color)
  1063. if color is not None:
  1064. color = self._color(color)
  1065. return color
  1066. def tracer(self, n=None, delay=None):
  1067. """Turns turtle animation on/off and set delay for update drawings.
  1068. Optional arguments:
  1069. n -- nonnegative integer
  1070. delay -- nonnegative integer
  1071. If n is given, only each n-th regular screen update is really performed.
  1072. (Can be used to accelerate the drawing of complex graphics.)
  1073. Second arguments sets delay value (see RawTurtle.delay())
  1074. Example (for a TurtleScreen instance named screen):
  1075. >>> screen.tracer(8, 25)
  1076. >>> dist = 2
  1077. >>> for i in range(200):
  1078. ... fd(dist)
  1079. ... rt(90)
  1080. ... dist += 2
  1081. """
  1082. if n is None:
  1083. return self._tracing
  1084. self._tracing = int(n)
  1085. self._updatecounter = 0
  1086. if delay is not None:
  1087. self._delayvalue = int(delay)
  1088. if self._tracing:
  1089. self.update()
  1090. def delay(self, delay=None):
  1091. """ Return or set the drawing delay in milliseconds.
  1092. Optional argument:
  1093. delay -- positive integer
  1094. Example (for a TurtleScreen instance named screen):
  1095. >>> screen.delay(15)
  1096. >>> screen.delay()
  1097. 15
  1098. """
  1099. if delay is None:
  1100. return self._delayvalue
  1101. self._delayvalue = int(delay)
  1102. def _incrementudc(self):
  1103. """Increment update counter."""
  1104. if not TurtleScreen._RUNNING:
  1105. TurtleScreen._RUNNING = True
  1106. raise Terminator
  1107. if self._tracing > 0:
  1108. self._updatecounter += 1
  1109. self._updatecounter %= self._tracing
  1110. def update(self):
  1111. """Perform a TurtleScreen update.
  1112. """
  1113. tracing = self._tracing
  1114. self._tracing = True
  1115. for t in self.turtles():
  1116. t._update_data()
  1117. t._drawturtle()
  1118. self._tracing = tracing
  1119. self._update()
  1120. def window_width(self):
  1121. """ Return the width of the turtle window.
  1122. Example (for a TurtleScreen instance named screen):
  1123. >>> screen.window_width()
  1124. 640
  1125. """
  1126. return self._window_size()[0]
  1127. def window_height(self):
  1128. """ Return the height of the turtle window.
  1129. Example (for a TurtleScreen instance named screen):
  1130. >>> screen.window_height()
  1131. 480
  1132. """
  1133. return self._window_size()[1]
  1134. def getcanvas(self):
  1135. """Return the Canvas of this TurtleScreen.
  1136. No argument.
  1137. Example (for a Screen instance named screen):
  1138. >>> cv = screen.getcanvas()
  1139. >>> cv
  1140. <turtle.ScrolledCanvas instance at 0x010742D8>
  1141. """
  1142. return self.cv
  1143. def getshapes(self):
  1144. """Return a list of names of all currently available turtle shapes.
  1145. No argument.
  1146. Example (for a TurtleScreen instance named screen):
  1147. >>> screen.getshapes()
  1148. ['arrow', 'blank', 'circle', ... , 'turtle']
  1149. """
  1150. return sorted(self._shapes.keys())
  1151. def onclick(self, fun, btn=1, add=None):
  1152. """Bind fun to mouse-click event on canvas.
  1153. Arguments:
  1154. fun -- a function with two arguments, the coordinates of the
  1155. clicked point on the canvas.
  1156. btn -- the number of the mouse-button, defaults to 1
  1157. Example (for a TurtleScreen instance named screen)
  1158. >>> screen.onclick(goto)
  1159. >>> # Subsequently clicking into the TurtleScreen will
  1160. >>> # make the turtle move to the clicked point.
  1161. >>> screen.onclick(None)
  1162. """
  1163. self._onscreenclick(fun, btn, add)
  1164. def onkey(self, fun, key):
  1165. """Bind fun to key-release event of key.
  1166. Arguments:
  1167. fun -- a function with no arguments
  1168. key -- a string: key (e.g. "a") or key-symbol (e.g. "space")
  1169. In order to be able to register key-events, TurtleScreen
  1170. must have focus. (See method listen.)
  1171. Example (for a TurtleScreen instance named screen):
  1172. >>> def f():
  1173. ... fd(50)
  1174. ... lt(60)
  1175. ...
  1176. >>> screen.onkey(f, "Up")
  1177. >>> screen.listen()
  1178. Subsequently the turtle can be moved by repeatedly pressing
  1179. the up-arrow key, consequently drawing a hexagon
  1180. """
  1181. if fun is None:
  1182. if key in self._keys:
  1183. self._keys.remove(key)
  1184. elif key not in self._keys:
  1185. self._keys.append(key)
  1186. self._onkeyrelease(fun, key)
  1187. def onkeypress(self, fun, key=None):
  1188. """Bind fun to key-press event of key if key is given,
  1189. or to any key-press-event if no key is given.
  1190. Arguments:
  1191. fun -- a function with no arguments
  1192. key -- a string: key (e.g. "a") or key-symbol (e.g. "space")
  1193. In order to be able to register key-events, TurtleScreen
  1194. must have focus. (See method listen.)
  1195. Example (for a TurtleScreen instance named screen
  1196. and a Turtle instance named turtle):
  1197. >>> def f():
  1198. ... fd(50)
  1199. ... lt(60)
  1200. ...
  1201. >>> screen.onkeypress(f, "Up")
  1202. >>> screen.listen()
  1203. Subsequently the turtle can be moved by repeatedly pressing
  1204. the up-arrow key, or by keeping pressed the up-arrow key.
  1205. consequently drawing a hexagon.
  1206. """
  1207. if fun is None:
  1208. if key in self._keys:
  1209. self._keys.remove(key)
  1210. elif key is not None and key not in self._keys:
  1211. self._keys.append(key)
  1212. self._onkeypress(fun, key)
  1213. def listen(self, xdummy=None, ydummy=None):
  1214. """Set focus on TurtleScreen (in order to collect key-events)
  1215. No arguments.
  1216. Dummy arguments are provided in order
  1217. to be able to pass listen to the onclick method.
  1218. Example (for a TurtleScreen instance named screen):
  1219. >>> screen.listen()
  1220. """
  1221. self._listen()
  1222. def ontimer(self, fun, t=0):
  1223. """Install a timer, which calls fun after t milliseconds.
  1224. Arguments:
  1225. fun -- a function with no arguments.
  1226. t -- a number >= 0
  1227. Example (for a TurtleScreen instance named screen):
  1228. >>> running = True
  1229. >>> def f():
  1230. ... if running:
  1231. ... fd(50)
  1232. ... lt(60)
  1233. ... screen.ontimer(f, 250)
  1234. ...
  1235. >>> f() # makes the turtle marching around
  1236. >>> running = False
  1237. """
  1238. self._ontimer(fun, t)
  1239. def bgpic(self, picname=None):
  1240. """Set background image or return name of current backgroundimage.
  1241. Optional argument:
  1242. picname -- a string, name of a gif-file or "nopic".
  1243. If picname is a filename, set the corresponding image as background.
  1244. If picname is "nopic", delete backgroundimage, if present.
  1245. If picname is None, return the filename of the current backgroundimage.
  1246. Example (for a TurtleScreen instance named screen):
  1247. >>> screen.bgpic()
  1248. 'nopic'
  1249. >>> screen.bgpic("landscape.gif")
  1250. >>> screen.bgpic()
  1251. 'landscape.gif'
  1252. """
  1253. if picname is None:
  1254. return self._bgpicname
  1255. if picname not in self._bgpics:
  1256. self._bgpics[picname] = self._image(picname)
  1257. self._setbgpic(self._bgpic, self._bgpics[picname])
  1258. self._bgpicname = picname
  1259. def screensize(self, canvwidth=None, canvheight=None, bg=None):
  1260. """Resize the canvas the turtles are drawing on.
  1261. Optional arguments:
  1262. canvwidth -- positive integer, new width of canvas in pixels
  1263. canvheight -- positive integer, new height of canvas in pixels
  1264. bg -- colorstring or color-tuple, new backgroundcolor
  1265. If no arguments are given, return current (canvaswidth, canvasheight)
  1266. Do not alter the drawing window. To observe hidden parts of
  1267. the canvas use the scrollbars. (Can make visible those parts
  1268. of a drawing, which were outside the canvas before!)
  1269. Example (for a Turtle instance named turtle):
  1270. >>> turtle.screensize(2000,1500)
  1271. >>> # e.g. to search for an erroneously escaped turtle ;-)
  1272. """
  1273. return self._resize(canvwidth, canvheight, bg)
  1274. onscreenclick = onclick
  1275. resetscreen = reset
  1276. clearscreen = clear
  1277. addshape = register_shape
  1278. onkeyrelease = onkey
  1279. class TNavigator(object):
  1280. """Navigation part of the RawTurtle.
  1281. Implements methods for turtle movement.
  1282. """
  1283. START_ORIENTATION = {
  1284. "standard": Vec2D(1.0, 0.0),
  1285. "world" : Vec2D(1.0, 0.0),
  1286. "logo" : Vec2D(0.0, 1.0) }
  1287. DEFAULT_MODE = "standard"
  1288. DEFAULT_ANGLEOFFSET = 0
  1289. DEFAULT_ANGLEORIENT = 1
  1290. def __init__(self, mode=DEFAULT_MODE):
  1291. self._angleOffset = self.DEFAULT_ANGLEOFFSET
  1292. self._angleOrient = self.DEFAULT_ANGLEORIENT
  1293. self._mode = mode
  1294. self.undobuffer = None
  1295. self.degrees()
  1296. self._mode = None
  1297. self._setmode(mode)
  1298. TNavigator.reset(self)
  1299. def reset(self):
  1300. """reset turtle to its initial values
  1301. Will be overwritten by parent class
  1302. """
  1303. self._position = Vec2D(0.0, 0.0)
  1304. self._orient = TNavigator.START_ORIENTATION[self._mode]
  1305. def _setmode(self, mode=None):
  1306. """Set turtle-mode to 'standard', 'world' or 'logo'.
  1307. """
  1308. if mode is None:
  1309. return self._mode
  1310. if mode not in ["standard", "logo", "world"]:
  1311. return
  1312. self._mode = mode
  1313. if mode in ["standard", "world"]:
  1314. self._angleOffset = 0
  1315. self._angleOrient = 1
  1316. else: # mode == "logo":
  1317. self._angleOffset = self._fullcircle/4.
  1318. self._angleOrient = -1
  1319. def _setDegreesPerAU(self, fullcircle):
  1320. """Helper function for degrees() and radians()"""
  1321. self._fullcircle = fullcircle
  1322. self._degreesPerAU = 360/fullcircle
  1323. if self._mode == "standard":
  1324. self._angleOffset = 0
  1325. else:
  1326. self._angleOffset = fullcircle/4.
  1327. def degrees(self, fullcircle=360.0):
  1328. """ Set angle measurement units to degrees.
  1329. Optional argument:
  1330. fullcircle - a number
  1331. Set angle measurement units, i. e. set number
  1332. of 'degrees' for a full circle. Default value is
  1333. 360 degrees.
  1334. Example (for a Turtle instance named turtle):
  1335. >>> turtle.left(90)
  1336. >>> turtle.heading()
  1337. 90
  1338. Change angle measurement unit to grad (also known as gon,
  1339. grade, or gradian and equals 1/100-th of the right angle.)
  1340. >>> turtle.degrees(400.0)
  1341. >>> turtle.heading()
  1342. 100
  1343. """
  1344. self._setDegreesPerAU(fullcircle)
  1345. def radians(self):
  1346. """ Set the angle measurement units to radians.
  1347. No arguments.
  1348. Example (for a Turtle instance named turtle):
  1349. >>> turtle.heading()
  1350. 90
  1351. >>> turtle.radians()
  1352. >>> turtle.heading()
  1353. 1.5707963267948966
  1354. """
  1355. self._setDegreesPerAU(2*math.pi)
  1356. def _go(self, distance):
  1357. """move turtle forward by specified distance"""
  1358. ende = self._position + self._orient * distance
  1359. self._goto(ende)
  1360. def _rotate(self, angle):
  1361. """Turn turtle counterclockwise by specified angle if angle > 0."""
  1362. angle *= self._degreesPerAU
  1363. self._orient = self._orient.rotate(angle)
  1364. def _goto(self, end):
  1365. """move turtle to position end."""
  1366. self._position = end
  1367. def forward(self, distance):
  1368. """Move the turtle forward by the specified distance.
  1369. Aliases: forward | fd
  1370. Argument:
  1371. distance -- a number (integer or float)
  1372. Move the turtle forward by the specified distance, in the direction
  1373. the turtle is headed.
  1374. Example (for a Turtle instance named turtle):
  1375. >>> turtle.position()
  1376. (0.00, 0.00)
  1377. >>> turtle.forward(25)
  1378. >>> turtle.position()
  1379. (25.00,0.00)
  1380. >>> turtle.forward(-75)
  1381. >>> turtle.position()
  1382. (-50.00,0.00)
  1383. """
  1384. self._go(distance)
  1385. def back(self, distance):
  1386. """Move the turtle backward by distance.
  1387. Aliases: back | backward | bk
  1388. Argument:
  1389. distance -- a number
  1390. Move the turtle backward by distance ,opposite to the direction the
  1391. turtle is headed. Do not change the turtle's heading.
  1392. Example (for a Turtle instance named turtle):
  1393. >>> turtle.position()
  1394. (0.00, 0.00)
  1395. >>> turtle.backward(30)
  1396. >>> turtle.position()
  1397. (-30.00, 0.00)
  1398. """
  1399. self._go(-distance)
  1400. def right(self, angle):
  1401. """Turn turtle right by angle units.
  1402. Aliases: right | rt
  1403. Argument:
  1404. angle -- a number (integer or float)
  1405. Turn turtle right by angle units. (Units are by default degrees,
  1406. but can be set via the degrees() and radians() functions.)
  1407. Angle orientation depends on mode. (See this.)
  1408. Example (for a Turtle instance named turtle):
  1409. >>> turtle.heading()
  1410. 22.0
  1411. >>> turtle.right(45)
  1412. >>> turtle.heading()
  1413. 337.0
  1414. """
  1415. self._rotate(-angle)
  1416. def left(self, angle):
  1417. """Turn turtle left by angle units.
  1418. Aliases: left | lt
  1419. Argument:
  1420. angle -- a number (integer or float)
  1421. Turn turtle left by angle units. (Units are by default degrees,
  1422. but can be set via the degrees() and radians() functions.)
  1423. Angle orientation depends on mode. (See this.)
  1424. Example (for a Turtle instance named turtle):
  1425. >>> turtle.heading()
  1426. 22.0
  1427. >>> turtle.left(45)
  1428. >>> turtle.heading()
  1429. 67.0
  1430. """
  1431. self._rotate(angle)
  1432. def pos(self):
  1433. """Return the turtle's current location (x,y), as a Vec2D-vector.
  1434. Aliases: pos | position
  1435. No arguments.
  1436. Example (for a Turtle instance named turtle):
  1437. >>> turtle.pos()
  1438. (0.00, 240.00)
  1439. """
  1440. return self._position
  1441. def xcor(self):
  1442. """ Return the turtle's x coordinate.
  1443. No arguments.
  1444. Example (for a Turtle instance named turtle):
  1445. >>> reset()
  1446. >>> turtle.left(60)
  1447. >>> turtle.forward(100)
  1448. >>> print turtle.xcor()
  1449. 50.0
  1450. """
  1451. return self._position[0]
  1452. def ycor(self):
  1453. """ Return the turtle's y coordinate
  1454. ---
  1455. No arguments.
  1456. Example (for a Turtle instance named turtle):
  1457. >>> reset()
  1458. >>> turtle.left(60)
  1459. >>> turtle.forward(100)
  1460. >>> print turtle.ycor()
  1461. 86.6025403784
  1462. """
  1463. return self._position[1]
  1464. def goto(self, x, y=None):
  1465. """Move turtle to an absolute position.
  1466. Aliases: setpos | setposition | goto:
  1467. Arguments:
  1468. x -- a number or a pair/vector of numbers
  1469. y -- a number None
  1470. call: goto(x, y) # two coordinates
  1471. --or: goto((x, y)) # a pair (tuple) of coordinates
  1472. --or: goto(vec) # e.g. as returned by pos()
  1473. Move turtle to an absolute position. If the pen is down,
  1474. a line will be drawn. The turtle's orientation does not change.
  1475. Example (for a Turtle instance named turtle):
  1476. >>> tp = turtle.pos()
  1477. >>> tp
  1478. (0.00, 0.00)
  1479. >>> turtle.setpos(60,30)
  1480. >>> turtle.pos()
  1481. (60.00,30.00)
  1482. >>> turtle.setpos((20,80))
  1483. >>> turtle.pos()
  1484. (20.00,80.00)
  1485. >>> turtle.setpos(tp)
  1486. >>> turtle.pos()
  1487. (0.00,0.00)
  1488. """
  1489. if y is None:
  1490. self._goto(Vec2D(*x))
  1491. else:
  1492. self._goto(Vec2D(x, y))
  1493. def home(self):
  1494. """Move turtle to the origin - coordinates (0,0).
  1495. No arguments.
  1496. Move turtle to the origin - coordinates (0,0) and set its
  1497. heading to its start-orientation (which depends on mode).
  1498. Example (for a Turtle instance named turtle):
  1499. >>> turtle.home()
  1500. """
  1501. self.goto(0, 0)
  1502. self.setheading(0)
  1503. def setx(self, x):
  1504. """Set the turtle's first coordinate to x
  1505. Argument:
  1506. x -- a number (integer or float)
  1507. Set the turtle's first coordinate to x, leave second coordinate
  1508. unchanged.
  1509. Example (for a Turtle instance named turtle):
  1510. >>> turtle.position()
  1511. (0.00, 240.00)
  1512. >>> turtle.setx(10)
  1513. >>> turtle.position()
  1514. (10.00, 240.00)
  1515. """
  1516. self._goto(Vec2D(x, self._position[1]))
  1517. def sety(self, y):
  1518. """Set the turtle's second coordinate to y
  1519. Argument:
  1520. y -- a number (integer or float)
  1521. Set the turtle's first coordinate to x, second coordinate remains
  1522. unchanged.
  1523. Example (for a Turtle instance named turtle):
  1524. >>> turtle.position()
  1525. (0.00, 40.00)
  1526. >>> turtle.sety(-10)
  1527. >>> turtle.position()
  1528. (0.00, -10.00)
  1529. """
  1530. self._goto(Vec2D(self._position[0], y))
  1531. def distance(self, x, y=None):
  1532. """Return the distance from the turtle to (x,y) in turtle step units.
  1533. Arguments:
  1534. x -- a number or a pair/vector of numbers or a turtle instance
  1535. y -- a number None None
  1536. call: distance(x, y) # two coordinates
  1537. --or: distance((x, y)) # a pair (tuple) of coordinates
  1538. --or: distance(vec) # e.g. as returned by pos()
  1539. --or: distance(mypen) # where mypen is another turtle
  1540. Example (for a Turtle instance named turtle):
  1541. >>> turtle.pos()
  1542. (0.00, 0.00)
  1543. >>> turtle.distance(30,40)
  1544. 50.0
  1545. >>> pen = Turtle()
  1546. >>> pen.forward(77)
  1547. >>> turtle.distance(pen)
  1548. 77.0
  1549. """
  1550. if y is not None:
  1551. pos = Vec2D(x, y)
  1552. if isinstance(x, Vec2D):
  1553. pos = x
  1554. elif isinstance(x, tuple):
  1555. pos = Vec2D(*x)
  1556. elif isinstance(x, TNavigator):
  1557. pos = x._position
  1558. return abs(pos - self._position)
  1559. def towards(self, x, y=None):
  1560. """Return the angle of the line from the turtle's position to (x, y).
  1561. Arguments:
  1562. x -- a number or a pair/vector of numbers or a turtle instance
  1563. y -- a number None None
  1564. call: distance(x, y) # two coordinates
  1565. --or: distance((x, y)) # a pair (tuple) of coordinates
  1566. --or: distance(vec) # e.g. as returned by pos()
  1567. --or: distance(mypen) # where mypen is another turtle
  1568. Return the angle, between the line from turtle-position to position
  1569. specified by x, y and the turtle's start orientation. (Depends on
  1570. modes - "standard" or "logo")
  1571. Example (for a Turtle instance named turtle):
  1572. >>> turtle.pos()
  1573. (10.00, 10.00)
  1574. >>> turtle.towards(0,0)
  1575. 225.0
  1576. """
  1577. if y is not None:
  1578. pos = Vec2D(x, y)
  1579. if isinstance(x, Vec2D):
  1580. pos = x
  1581. elif isinstance(x, tuple):
  1582. pos = Vec2D(*x)
  1583. elif isinstance(x, TNavigator):
  1584. pos = x._position
  1585. x, y = pos - self._position
  1586. result = round(math.atan2(y, x)*180.0/math.pi, 10) % 360.0
  1587. result /= self._degreesPerAU
  1588. return (self._angleOffset + self._angleOrient*result) % self._fullcircle
  1589. def heading(self):
  1590. """ Return the turtle's current heading.
  1591. No arguments.
  1592. Example (for a Turtle instance named turtle):
  1593. >>> turtle.left(67)
  1594. >>> turtle.heading()
  1595. 67.0
  1596. """
  1597. x, y = self._orient
  1598. result = round(math.atan2(y, x)*180.0/math.pi, 10) % 360.0
  1599. result /= self._degreesPerAU
  1600. return (self._angleOffset + self._angleOrient*result) % self._fullcircle
  1601. def setheading(self, to_angle):
  1602. """Set the orientation of the turtle to to_angle.
  1603. Aliases: setheading | seth
  1604. Argument:
  1605. to_angle -- a number (integer or float)
  1606. Set the orientation of the turtle to to_angle.
  1607. Here are some common directions in degrees:
  1608. standard - mode: logo-mode:
  1609. -------------------|--------------------
  1610. 0 - east 0 - north
  1611. 90 - north 90 - east
  1612. 180 - west 180 - south
  1613. 270 - south 270 - west
  1614. Example (for a Turtle instance named turtle):
  1615. >>> turtle.setheading(90)
  1616. >>> turtle.heading()
  1617. 90
  1618. """
  1619. angle = (to_angle - self.heading())*self._angleOrient
  1620. full = self._fullcircle
  1621. angle = (angle+full/2.)%full - full/2.
  1622. self._rotate(angle)
  1623. def circle(self, radius, extent = None, steps = None):
  1624. """ Draw a circle with given radius.
  1625. Arguments:
  1626. radius -- a number
  1627. extent (optional) -- a number
  1628. steps (optional) -- an integer
  1629. Draw a circle with given radius. The center is radius units left
  1630. of the turtle; extent - an angle - determines which part of the
  1631. circle is drawn. If extent is not given, draw the entire circle.
  1632. If extent is not a full circle, one endpoint of the arc is the
  1633. current pen position. Draw the arc in counterclockwise direction
  1634. if radius is positive, otherwise in clockwise direction. Finally
  1635. the direction of the turtle is changed by the amount of extent.
  1636. As the circle is approximated by an inscribed regular polygon,
  1637. steps determines the number of steps to use. If not given,
  1638. it will be calculated automatically. Maybe used to draw regular
  1639. polygons.
  1640. call: circle(radius) # full circle
  1641. --or: circle(radius, extent) # arc
  1642. --or: circle(radius, extent, steps)
  1643. --or: circle(radius, steps=6) # 6-sided polygon
  1644. Example (for a Turtle instance named turtle):
  1645. >>> turtle.circle(50)
  1646. >>> turtle.circle(120, 180) # semicircle
  1647. """
  1648. if self.undobuffer:
  1649. self.undobuffer.push(["seq"])
  1650. self.undobuffer.cumulate = True
  1651. speed = self.speed()
  1652. if extent is None:
  1653. extent = self._fullcircle
  1654. if steps is None:
  1655. frac = abs(extent)/self._fullcircle
  1656. steps = 1+int(min(11+abs(radius)/6.0, 59.0)*frac)
  1657. w = 1.0 * extent / steps
  1658. w2 = 0.5 * w
  1659. l = 2.0 * radius * math.sin(w2*math.pi/180.0*self._degreesPerAU)
  1660. if radius < 0:
  1661. l, w, w2 = -l, -w, -w2
  1662. tr = self._tracer()
  1663. dl = self._delay()
  1664. if speed == 0:
  1665. self._tracer(0, 0)
  1666. else:
  1667. self.speed(0)
  1668. self._rotate(w2)
  1669. for i in range(steps):
  1670. self.speed(speed)
  1671. self._go(l)
  1672. self.speed(0)
  1673. self._rotate(w)
  1674. self._rotate(-w2)
  1675. if speed == 0:
  1676. self._tracer(tr, dl)
  1677. self.speed(speed)
  1678. if self.undobuffer:
  1679. self.undobuffer.cumulate = False
  1680. ## three dummy methods to be implemented by child class:
  1681. def speed(self, s=0):
  1682. """dummy method - to be overwritten by child class"""
  1683. def _tracer(self, a=None, b=None):
  1684. """dummy method - to be overwritten by child class"""
  1685. def _delay(self, n=None):
  1686. """dummy method - to be overwritten by child class"""
  1687. fd = forward
  1688. bk = back
  1689. backward = back
  1690. rt = right
  1691. lt = left
  1692. position = pos
  1693. setpos = goto
  1694. setposition = goto
  1695. seth = setheading
  1696. class TPen(object):
  1697. """Drawing part of the RawTurtle.
  1698. Implements drawing properties.
  1699. """
  1700. def __init__(self, resizemode=_CFG["resizemode"]):
  1701. self._resizemode = resizemode # or "user" or "noresize"
  1702. self.undobuffer = None
  1703. TPen._reset(self)
  1704. def _reset(self, pencolor=_CFG["pencolor"],
  1705. fillcolor=_CFG["fillcolor"]):
  1706. self._pensize = 1
  1707. self._shown = True
  1708. self._pencolor = pencolor
  1709. self._fillcolor = fillcolor
  1710. self._drawing = True
  1711. self._speed = 3
  1712. self._stretchfactor = (1., 1.)
  1713. self._shearfactor = 0.
  1714. self._tilt = 0.
  1715. self._shapetrafo = (1., 0., 0., 1.)
  1716. self._outlinewidth = 1
  1717. def resizemode(self, rmode=None):
  1718. """Set resizemode to one of the values: "auto", "user", "noresize".
  1719. (Optional) Argument:
  1720. rmode -- one of the strings "auto", "user", "noresize"
  1721. Different resizemodes have the following effects:
  1722. - "auto" adapts the appearance of the turtle
  1723. corresponding to the value of pensize.
  1724. - "user" adapts the appearance of the turtle according to the
  1725. values of stretchfactor and outlinewidth (outline),
  1726. which are set by shapesize()
  1727. - "noresize" no adaption of the turtle's appearance takes place.
  1728. If no argument is given, return current resizemode.
  1729. resizemode("user") is called by a call of shapesize with arguments.
  1730. Examples (for a Turtle instance named turtle):
  1731. >>> turtle.resizemode("noresize")
  1732. >>> turtle.resizemode()
  1733. 'noresize'
  1734. """
  1735. if rmode is None:
  1736. return self._resizemode
  1737. rmode = rmode.lower()
  1738. if rmode in ["auto", "user", "noresize"]:
  1739. self.pen(resizemode=rmode)
  1740. def pensize(self, width=None):
  1741. """Set or return the line thickness.
  1742. Aliases: pensize | width
  1743. Argument:
  1744. width -- positive number
  1745. Set the line thickness to width or return it. If resizemode is set
  1746. to "auto" and turtleshape is a polygon, that polygon is drawn with
  1747. the same line thickness. If no argument is given, current pensize
  1748. is returned.
  1749. Example (for a Turtle instance named turtle):
  1750. >>> turtle.pensize()
  1751. 1
  1752. >>> turtle.pensize(10) # from here on lines of width 10 are drawn
  1753. """
  1754. if width is None:
  1755. return self._pensize
  1756. self.pen(pensize=width)
  1757. def penup(self):
  1758. """Pull the pen up -- no drawing when moving.
  1759. Aliases: penup | pu | up
  1760. No argument
  1761. Example (for a Turtle instance named turtle):
  1762. >>> turtle.penup()
  1763. """
  1764. if not self._drawing:
  1765. return
  1766. self.pen(pendown=False)
  1767. def pendown(self):
  1768. """Pull the pen down -- drawing when moving.
  1769. Aliases: pendown | pd | down
  1770. No argument.
  1771. Example (for a Turtle instance named turtle):
  1772. >>> turtle.pendown()
  1773. """
  1774. if self._drawing:
  1775. return
  1776. self.pen(pendown=True)
  1777. def isdown(self):
  1778. """Return True if pen is down, False if it's up.
  1779. No argument.
  1780. Example (for a Turtle instance named turtle):
  1781. >>> turtle.penup()
  1782. >>> turtle.isdown()
  1783. False
  1784. >>> turtle.pendown()
  1785. >>> turtle.isdown()
  1786. True
  1787. """
  1788. return self._drawing
  1789. def speed(self, speed=None):
  1790. """ Return or set the turtle's speed.
  1791. Optional argument:
  1792. speed -- an integer in the range 0..10 or a speedstring (see below)
  1793. Set the turtle's speed to an integer value in the range 0 .. 10.
  1794. If no argument is given: return current speed.
  1795. If input is a number greater than 10 or smaller than 0.5,
  1796. speed is set to 0.
  1797. Speedstrings are mapped to speedvalues in the following way:
  1798. 'fastest' : 0
  1799. 'fast' : 10
  1800. 'normal' : 6
  1801. 'slow' : 3
  1802. 'slowest' : 1
  1803. speeds from 1 to 10 enforce increasingly faster animation of
  1804. line drawing and turtle turning.
  1805. Attention:
  1806. speed = 0 : *no* animation takes place. forward/back makes turtle jump
  1807. and likewise left/right make the turtle turn instantly.
  1808. Example (for a Turtle instance named turtle):
  1809. >>> turtle.speed(3)
  1810. """
  1811. speeds = {'fastest':0, 'fast':10, 'normal':6, 'slow':3, 'slowest':1 }
  1812. if speed is None:
  1813. return self._speed
  1814. if speed in speeds:
  1815. speed = speeds[speed]
  1816. elif 0.5 < speed < 10.5:
  1817. speed = int(round(speed))
  1818. else:
  1819. speed = 0
  1820. self.pen(speed=speed)
  1821. def color(self, *args):
  1822. """Return or set the pencolor and fillcolor.
  1823. Arguments:
  1824. Several input formats are allowed.
  1825. They use 0, 1, 2, or 3 arguments as follows:
  1826. color()
  1827. Return the current pencolor and the current fillcolor
  1828. as a pair of color specification strings as are returned
  1829. by pencolor and fillcolor.
  1830. color(colorstring), color((r,g,b)), color(r,g,b)
  1831. inputs as in pencolor, set both, fillcolor and pencolor,
  1832. to the given value.
  1833. color(colorstring1, colorstring2),
  1834. color((r1,g1,b1), (r2,g2,b2))
  1835. equivalent to pencolor(colorstring1) and fillcolor(colorstring2)
  1836. and analogously, if the other input format is used.
  1837. If turtleshape is a polygon, outline and interior of that polygon
  1838. is drawn with the newly set colors.
  1839. For more info see: pencolor, fillcolor
  1840. Example (for a Turtle instance named turtle):
  1841. >>> turtle.color('red', 'green')
  1842. >>> turtle.color()
  1843. ('red', 'green')
  1844. >>> colormode(255)
  1845. >>> color((40, 80, 120), (160, 200, 240))
  1846. >>> color()
  1847. ('#285078', '#a0c8f0')
  1848. """
  1849. if args:
  1850. l = len(args)
  1851. if l == 1:
  1852. pcolor = fcolor = args[0]
  1853. elif l == 2:
  1854. pcolor, fcolor = args
  1855. elif l == 3:
  1856. pcolor = fcolor = args
  1857. pcolor = self._colorstr(pcolor)
  1858. fcolor = self._colorstr(fcolor)
  1859. self.pen(pencolor=pcolor, fillcolor=fcolor)
  1860. else:
  1861. return self._color(self._pencolor), self._color(self._fillcolor)
  1862. def pencolor(self, *args):
  1863. """ Return or set the pencolor.
  1864. Arguments:
  1865. Four input formats are allowed:
  1866. - pencolor()
  1867. Return the current pencolor as color specification string,
  1868. possibly in hex-number format (see example).
  1869. May be used as input to another color/pencolor/fillcolor call.
  1870. - pencolor(colorstring)
  1871. s is a Tk color specification string, such as "red" or "yellow"
  1872. - pencolor((r, g, b))
  1873. *a tuple* of r, g, and b, which represent, an RGB color,
  1874. and each of r, g, and b are in the range 0..colormode,
  1875. where colormode is either 1.0 or 255
  1876. - pencolor(r, g, b)
  1877. r, g, and b represent an RGB color, and each of r, g, and b
  1878. are in the range 0..colormode
  1879. If turtleshape is a polygon, the outline of that polygon is drawn
  1880. with the newly set pencolor.
  1881. Example (for a Turtle instance named turtle):
  1882. >>> turtle.pencolor('brown')
  1883. >>> tup = (0.2, 0.8, 0.55)
  1884. >>> turtle.pencolor(tup)
  1885. >>> turtle.pencolor()
  1886. '#33cc8c'
  1887. """
  1888. if args:
  1889. color = self._colorstr(args)
  1890. if color == self._pencolor:
  1891. return
  1892. self.pen(pencolor=color)
  1893. else:
  1894. return self._color(self._pencolor)
  1895. def fillcolor(self, *args):
  1896. """ Return or set the fillcolor.
  1897. Arguments:
  1898. Four input formats are allowed:
  1899. - fillcolor()
  1900. Return the current fillcolor as color specification string,
  1901. possibly in hex-number format (see example).
  1902. May be used as input to another color/pencolor/fillcolor call.
  1903. - fillcolor(colorstring)
  1904. s is a Tk color specification string, such as "red" or "yellow"
  1905. - fillcolor((r, g, b))
  1906. *a tuple* of r, g, and b, which represent, an RGB color,
  1907. and each of r, g, and b are in the range 0..colormode,
  1908. where colormode is either 1.0 or 255
  1909. - fillcolor(r, g, b)
  1910. r, g, and b represent an RGB color, and each of r, g, and b
  1911. are in the range 0..colormode
  1912. If turtleshape is a polygon, the interior of that polygon is drawn
  1913. with the newly set fillcolor.
  1914. Example (for a Turtle instance named turtle):
  1915. >>> turtle.fillcolor('violet')
  1916. >>> col = turtle.pencolor()
  1917. >>> turtle.fillcolor(col)
  1918. >>> turtle.fillcolor(0, .5, 0)
  1919. """
  1920. if args:
  1921. color = self._colorstr(args)
  1922. if color == self._fillcolor:
  1923. return
  1924. self.pen(fillcolor=color)
  1925. else:
  1926. return self._color(self._fillcolor)
  1927. def showturtle(self):
  1928. """Makes the turtle visible.
  1929. Aliases: showturtle | st
  1930. No argument.
  1931. Example (for a Turtle instance named turtle):
  1932. >>> turtle.hideturtle()
  1933. >>> turtle.showturtle()
  1934. """
  1935. self.pen(shown=True)
  1936. def hideturtle(self):
  1937. """Makes the turtle invisible.
  1938. Aliases: hideturtle | ht
  1939. No argument.
  1940. It's a good idea to do this while you're in the
  1941. middle of a complicated drawing, because hiding
  1942. the turtle speeds up the drawing observably.
  1943. Example (for a Turtle instance named turtle):
  1944. >>> turtle.hideturtle()
  1945. """
  1946. self.pen(shown=False)
  1947. def isvisible(self):
  1948. """Return True if the Turtle is shown, False if it's hidden.
  1949. No argument.
  1950. Example (for a Turtle instance named turtle):
  1951. >>> turtle.hideturtle()
  1952. >>> print turtle.isvisible():
  1953. False
  1954. """
  1955. return self._shown
  1956. def pen(self, pen=None, **pendict):
  1957. """Return or set the pen's attributes.
  1958. Arguments:
  1959. pen -- a dictionary with some or all of the below listed keys.
  1960. **pendict -- one or more keyword-arguments with the below
  1961. listed keys as keywords.
  1962. Return or set the pen's attributes in a 'pen-dictionary'
  1963. with the following key/value pairs:
  1964. "shown" : True/False
  1965. "pendown" : True/False
  1966. "pencolor" : color-string or color-tuple
  1967. "fillcolor" : color-string or color-tuple
  1968. "pensize" : positive number
  1969. "speed" : number in range 0..10
  1970. "resizemode" : "auto" or "user" or "noresize"
  1971. "stretchfactor": (positive number, positive number)
  1972. "shearfactor": number
  1973. "outline" : positive number
  1974. "tilt" : number
  1975. This dictionary can be used as argument for a subsequent
  1976. pen()-call to restore the former pen-state. Moreover one
  1977. or more of these attributes can be provided as keyword-arguments.
  1978. This can be used to set several pen attributes in one statement.
  1979. Examples (for a Turtle instance named turtle):
  1980. >>> turtle.pen(fillcolor="black", pencolor="red", pensize=10)
  1981. >>> turtle.pen()
  1982. {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
  1983. 'pencolor': 'red', 'pendown': True, 'fillcolor': 'black',
  1984. 'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
  1985. >>> penstate=turtle.pen()
  1986. >>> turtle.color("yellow","")
  1987. >>> turtle.penup()
  1988. >>> turtle.pen()
  1989. {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
  1990. 'pencolor': 'yellow', 'pendown': False, 'fillcolor': '',
  1991. 'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
  1992. >>> p.pen(penstate, fillcolor="green")
  1993. >>> p.pen()
  1994. {'pensize': 10, 'shown': True, 'resizemode': 'auto', 'outline': 1,
  1995. 'pencolor': 'red', 'pendown': True, 'fillcolor': 'green',
  1996. 'stretchfactor': (1,1), 'speed': 3, 'shearfactor': 0.0}
  1997. """
  1998. _pd = {"shown" : self._shown,
  1999. "pendown" : self._drawing,
  2000. "pencolor" : self._pencolor,
  2001. "fillcolor" : self._fillcolor,
  2002. "pensize" : self._pensize,
  2003. "speed" : self._speed,
  2004. "resizemode" : self._resizemode,
  2005. "stretchfactor" : self._stretchfactor,
  2006. "shearfactor" : self._shearfactor,
  2007. "outline" : self._outlinewidth,
  2008. "tilt" : self._tilt
  2009. }
  2010. if not (pen or pendict):
  2011. return _pd
  2012. if isinstance(pen, dict):
  2013. p = pen
  2014. else:
  2015. p = {}
  2016. p.update(pendict)
  2017. _p_buf = {}
  2018. for key in p:
  2019. _p_buf[key] = _pd[key]
  2020. if self.undobuffer:
  2021. self.undobuffer.push(("pen", _p_buf))
  2022. newLine = False
  2023. if "pendown" in p:
  2024. if self._drawing != p["pendown"]:
  2025. newLine = True
  2026. if "pencolor" in p:
  2027. if isinstance(p["pencolor"], tuple):
  2028. p["pencolor"] = self._colorstr((p["pencolor"],))
  2029. if self._pencolor != p["pencolor"]:
  2030. newLine = True
  2031. if "pensize" in p:
  2032. if self._pensize != p["pensize"]:
  2033. newLine = True
  2034. if newLine:
  2035. self._newLine()
  2036. if "pendown" in p:
  2037. self._drawing = p["pendown"]
  2038. if "pencolor" in p:
  2039. self._pencolor = p["pencolor"]
  2040. if "pensize" in p:
  2041. self._pensize = p["pensize"]
  2042. if "fillcolor" in p:
  2043. if isinstance(p["fillcolor"], tuple):
  2044. p["fillcolor"] = self._colorstr((p["fillcolor"],))
  2045. self._fillcolor = p["fillcolor"]
  2046. if "speed" in p:
  2047. self._speed = p["speed"]
  2048. if "resizemode" in p:
  2049. self._resizemode = p["resizemode"]
  2050. if "stretchfactor" in p:
  2051. sf = p["stretchfactor"]
  2052. if isinstance(sf, (int, float)):
  2053. sf = (sf, sf)
  2054. self._stretchfactor = sf
  2055. if "shearfactor" in p:
  2056. self._shearfactor = p["shearfactor"]
  2057. if "outline" in p:
  2058. self._outlinewidth = p["outline"]
  2059. if "shown" in p:
  2060. self._shown = p["shown"]
  2061. if "tilt" in p:
  2062. self._tilt = p["tilt"]
  2063. if "stretchfactor" in p or "tilt" in p or "shearfactor" in p:
  2064. scx, scy = self._stretchfactor
  2065. shf = self._shearfactor
  2066. sa, ca = math.sin(self._tilt), math.cos(self._tilt)
  2067. self._shapetrafo = ( scx*ca, scy*(shf*ca + sa),
  2068. -scx*sa, scy*(ca - shf*sa))
  2069. self._update()
  2070. ## three dummy methods to be implemented by child class:
  2071. def _newLine(self, usePos = True):
  2072. """dummy method - to be overwritten by child class"""
  2073. def _update(self, count=True, forced=False):
  2074. """dummy method - to be overwritten by child class"""
  2075. def _color(self, args):
  2076. """dummy method - to be overwritten by child class"""
  2077. def _colorstr(self, args):
  2078. """dummy method - to be overwritten by child class"""
  2079. width = pensize
  2080. up = penup
  2081. pu = penup
  2082. pd = pendown
  2083. down = pendown
  2084. st = showturtle
  2085. ht = hideturtle
  2086. class _TurtleImage(object):
  2087. """Helper class: Datatype to store Turtle attributes
  2088. """
  2089. def __init__(self, screen, shapeIndex):
  2090. self.screen = screen
  2091. self._type = None
  2092. self._setshape(shapeIndex)
  2093. def _setshape(self, shapeIndex):
  2094. screen = self.screen
  2095. self.shapeIndex = shapeIndex
  2096. if self._type == "polygon" == screen._shapes[shapeIndex]._type:
  2097. return
  2098. if self._type == "image" == screen._shapes[shapeIndex]._type:
  2099. return
  2100. if self._type in ["image", "polygon"]:
  2101. screen._delete(self._item)
  2102. elif self._type == "compound":
  2103. for item in self._item:
  2104. screen._delete(item)
  2105. self._type = screen._shapes[shapeIndex]._type
  2106. if self._type == "polygon":
  2107. self._item = screen._createpoly()
  2108. elif self._type == "image":
  2109. self._item = screen._createimage(screen._shapes["blank"]._data)
  2110. elif self._type == "compound":
  2111. self._item = [screen._createpoly() for item in
  2112. screen._shapes[shapeIndex]._data]
  2113. class RawTurtle(TPen, TNavigator):
  2114. """Animation part of the RawTurtle.
  2115. Puts RawTurtle upon a TurtleScreen and provides tools for
  2116. its animation.
  2117. """
  2118. screens = []
  2119. def __init__(self, canvas=None,
  2120. shape=_CFG["shape"],
  2121. undobuffersize=_CFG["undobuffersize"],
  2122. visible=_CFG["visible"]):
  2123. if isinstance(canvas, _Screen):
  2124. self.screen = canvas
  2125. elif isinstance(canvas, TurtleScreen):
  2126. if canvas not in RawTurtle.screens:
  2127. RawTurtle.screens.append(canvas)
  2128. self.screen = canvas
  2129. elif isinstance(canvas, (ScrolledCanvas, Canvas)):
  2130. for screen in RawTurtle.screens:
  2131. if screen.cv == canvas:
  2132. self.screen = screen
  2133. break
  2134. else:
  2135. self.screen = TurtleScreen(canvas)
  2136. RawTurtle.screens.append(self.screen)
  2137. else:
  2138. raise TurtleGraphicsError("bad canvas argument %s" % canvas)
  2139. screen = self.screen
  2140. TNavigator.__init__(self, screen.mode())
  2141. TPen.__init__(self)
  2142. screen._turtles.append(self)
  2143. self.drawingLineItem = screen._createline()
  2144. self.turtle = _TurtleImage(screen, shape)
  2145. self._poly = None
  2146. self._creatingPoly = False
  2147. self._fillitem = self._fillpath = None
  2148. self._shown = visible
  2149. self._hidden_from_screen = False
  2150. self.currentLineItem = screen._createline()
  2151. self.currentLine = [self._position]
  2152. self.items = [self.currentLineItem]
  2153. self.stampItems = []
  2154. self._undobuffersize = undobuffersize
  2155. self.undobuffer = Tbuffer(undobuffersize)
  2156. self._update()
  2157. def reset(self):
  2158. """Delete the turtle's drawings and restore its default values.
  2159. No argument.
  2160. Delete the turtle's drawings from the screen, re-center the turtle
  2161. and set variables to the default values.
  2162. Example (for a Turtle instance named turtle):
  2163. >>> turtle.position()
  2164. (0.00,-22.00)
  2165. >>> turtle.heading()
  2166. 100.0
  2167. >>> turtle.reset()
  2168. >>> turtle.position()
  2169. (0.00,0.00)
  2170. >>> turtle.heading()
  2171. 0.0
  2172. """
  2173. TNavigator.reset(self)
  2174. TPen._reset(self)
  2175. self._clear()
  2176. self._drawturtle()
  2177. self._update()
  2178. def setundobuffer(self, size):
  2179. """Set or disable undobuffer.
  2180. Argument:
  2181. size -- an integer or None
  2182. If size is an integer an empty undobuffer of given size is installed.
  2183. Size gives the maximum number of turtle-actions that can be undone
  2184. by the undo() function.
  2185. If size is None, no undobuffer is present.
  2186. Example (for a Turtle instance named turtle):
  2187. >>> turtle.setundobuffer(42)
  2188. """
  2189. if size is None or size <= 0:
  2190. self.undobuffer = None
  2191. else:
  2192. self.undobuffer = Tbuffer(size)
  2193. def undobufferentries(self):
  2194. """Return count of entries in the undobuffer.
  2195. No argument.
  2196. Example (for a Turtle instance named turtle):
  2197. >>> while undobufferentries():
  2198. ... undo()
  2199. """
  2200. if self.undobuffer is None:
  2201. return 0
  2202. return self.undobuffer.nr_of_items()
  2203. def _clear(self):
  2204. """Delete all of pen's drawings"""
  2205. self._fillitem = self._fillpath = None
  2206. for item in self.items:
  2207. self.screen._delete(item)
  2208. self.currentLineItem = self.screen._createline()
  2209. self.currentLine = []
  2210. if self._drawing:
  2211. self.currentLine.append(self._position)
  2212. self.items = [self.currentLineItem]
  2213. self.clearstamps()
  2214. self.setundobuffer(self._undobuffersize)
  2215. def clear(self):
  2216. """Delete the turtle's drawings from the screen. Do not move turtle.
  2217. No arguments.
  2218. Delete the turtle's drawings from the screen. Do not move turtle.
  2219. State and position of the turtle as well as drawings of other
  2220. turtles are not affected.
  2221. Examples (for a Turtle instance named turtle):
  2222. >>> turtle.clear()
  2223. """
  2224. self._clear()
  2225. self._update()
  2226. def _update_data(self):
  2227. self.screen._incrementudc()
  2228. if self.screen._updatecounter != 0:
  2229. return
  2230. if len(self.currentLine)>1:
  2231. self.screen._drawline(self.currentLineItem, self.currentLine,
  2232. self._pencolor, self._pensize)
  2233. def _update(self):
  2234. """Perform a Turtle-data update.
  2235. """
  2236. screen = self.screen
  2237. if screen._tracing == 0:
  2238. return
  2239. elif screen._tracing == 1:
  2240. self._update_data()
  2241. self._drawturtle()
  2242. screen._update() # TurtleScreenBase
  2243. screen._delay(screen._delayvalue) # TurtleScreenBase
  2244. else:
  2245. self._update_data()
  2246. if screen._updatecounter == 0:
  2247. for t in screen.turtles():
  2248. t._drawturtle()
  2249. screen._update()
  2250. def _tracer(self, flag=None, delay=None):
  2251. """Turns turtle animation on/off and set delay for update drawings.
  2252. Optional arguments:
  2253. n -- nonnegative integer
  2254. delay -- nonnegative integer
  2255. If n is given, only each n-th regular screen update is really performed.
  2256. (Can be used to accelerate the drawing of complex graphics.)
  2257. Second arguments sets delay value (see RawTurtle.delay())
  2258. Example (for a Turtle instance named turtle):
  2259. >>> turtle.tracer(8, 25)
  2260. >>> dist = 2
  2261. >>> for i in range(200):
  2262. ... turtle.fd(dist)
  2263. ... turtle.rt(90)
  2264. ... dist += 2
  2265. """
  2266. return self.screen.tracer(flag, delay)
  2267. def _color(self, args):
  2268. return self.screen._color(args)
  2269. def _colorstr(self, args):
  2270. return self.screen._colorstr(args)
  2271. def _cc(self, args):
  2272. """Convert colortriples to hexstrings.
  2273. """
  2274. if isinstance(args, str):
  2275. return args
  2276. try:
  2277. r, g, b = args
  2278. except (TypeError, ValueError):
  2279. raise TurtleGraphicsError("bad color arguments: %s" % str(args))
  2280. if self.screen._colormode == 1.0:
  2281. r, g, b = [round(255.0*x) for x in (r, g, b)]
  2282. if not ((0 <= r <= 255) and (0 <= g <= 255) and (0 <= b <= 255)):
  2283. raise TurtleGraphicsError("bad color sequence: %s" % str(args))
  2284. return "#%02x%02x%02x" % (r, g, b)
  2285. def clone(self):
  2286. """Create and return a clone of the turtle.
  2287. No argument.
  2288. Create and return a clone of the turtle with same position, heading
  2289. and turtle properties.
  2290. Example (for a Turtle instance named mick):
  2291. mick = Turtle()
  2292. joe = mick.clone()
  2293. """
  2294. screen = self.screen
  2295. self._newLine(self._drawing)
  2296. turtle = self.turtle
  2297. self.screen = None
  2298. self.turtle = None # too make self deepcopy-able
  2299. q = deepcopy(self)
  2300. self.screen = screen
  2301. self.turtle = turtle
  2302. q.screen = screen
  2303. q.turtle = _TurtleImage(screen, self.turtle.shapeIndex)
  2304. screen._turtles.append(q)
  2305. ttype = screen._shapes[self.turtle.shapeIndex]._type
  2306. if ttype == "polygon":
  2307. q.turtle._item = screen._createpoly()
  2308. elif ttype == "image":
  2309. q.turtle._item = screen._createimage(screen._shapes["blank"]._data)
  2310. elif ttype == "compound":
  2311. q.turtle._item = [screen._createpoly() for item in
  2312. screen._shapes[self.turtle.shapeIndex]._data]
  2313. q.currentLineItem = screen._createline()
  2314. q._update()
  2315. return q
  2316. def shape(self, name=None):
  2317. """Set turtle shape to shape with given name / return current shapename.
  2318. Optional argument:
  2319. name -- a string, which is a valid shapename
  2320. Set turtle shape to shape with given name or, if name is not given,
  2321. return name of current shape.
  2322. Shape with name must exist in the TurtleScreen's shape dictionary.
  2323. Initially there are the following polygon shapes:
  2324. 'arrow', 'turtle', 'circle', 'square', 'triangle', 'classic'.
  2325. To learn about how to deal with shapes see Screen-method register_shape.
  2326. Example (for a Turtle instance named turtle):
  2327. >>> turtle.shape()
  2328. 'arrow'
  2329. >>> turtle.shape("turtle")
  2330. >>> turtle.shape()
  2331. 'turtle'
  2332. """
  2333. if name is None:
  2334. return self.turtle.shapeIndex
  2335. if not name in self.screen.getshapes():
  2336. raise TurtleGraphicsError("There is no shape named %s" % name)
  2337. self.turtle._setshape(name)
  2338. self._update()
  2339. def shapesize(self, stretch_wid=None, stretch_len=None, outline=None):
  2340. """Set/return turtle's stretchfactors/outline. Set resizemode to "user".
  2341. Optional arguments:
  2342. stretch_wid : positive number
  2343. stretch_len : positive number
  2344. outline : positive number
  2345. Return or set the pen's attributes x/y-stretchfactors and/or outline.
  2346. Set resizemode to "user".
  2347. If and only if resizemode is set to "user", the turtle will be displayed
  2348. stretched according to its stretchfactors:
  2349. stretch_wid is stretchfactor perpendicular to orientation
  2350. stretch_len is stretchfactor in direction of turtles orientation.
  2351. outline determines the width of the shapes's outline.
  2352. Examples (for a Turtle instance named turtle):
  2353. >>> turtle.resizemode("user")
  2354. >>> turtle.shapesize(5, 5, 12)
  2355. >>> turtle.shapesize(outline=8)
  2356. """
  2357. if stretch_wid is stretch_len is outline is None:
  2358. stretch_wid, stretch_len = self._stretchfactor
  2359. return stretch_wid, stretch_len, self._outlinewidth
  2360. if stretch_wid == 0 or stretch_len == 0:
  2361. raise TurtleGraphicsError("stretch_wid/stretch_len must not be zero")
  2362. if stretch_wid is not None:
  2363. if stretch_len is None:
  2364. stretchfactor = stretch_wid, stretch_wid
  2365. else:
  2366. stretchfactor = stretch_wid, stretch_len
  2367. elif stretch_len is not None:
  2368. stretchfactor = self._stretchfactor[0], stretch_len
  2369. else:
  2370. stretchfactor = self._stretchfactor
  2371. if outline is None:
  2372. outline = self._outlinewidth
  2373. self.pen(resizemode="user",
  2374. stretchfactor=stretchfactor, outline=outline)
  2375. def shearfactor(self, shear=None):
  2376. """Set or return the current shearfactor.
  2377. Optional argument: shear -- number, tangent of the shear angle
  2378. Shear the turtleshape according to the given shearfactor shear,
  2379. which is the tangent of the shear angle. DO NOT change the
  2380. turtle's heading (direction of movement).
  2381. If shear is not given: return the current shearfactor, i. e. the
  2382. tangent of the shear angle, by which lines parallel to the
  2383. heading of the turtle are sheared.
  2384. Examples (for a Turtle instance named turtle):
  2385. >>> turtle.shape("circle")
  2386. >>> turtle.shapesize(5,2)
  2387. >>> turtle.shearfactor(0.5)
  2388. >>> turtle.shearfactor()
  2389. >>> 0.5
  2390. """
  2391. if shear is None:
  2392. return self._shearfactor
  2393. self.pen(resizemode="user", shearfactor=shear)
  2394. def settiltangle(self, angle):
  2395. """Rotate the turtleshape to point in the specified direction
  2396. Argument: angle -- number
  2397. Rotate the turtleshape to point in the direction specified by angle,
  2398. regardless of its current tilt-angle. DO NOT change the turtle's
  2399. heading (direction of movement).
  2400. Examples (for a Turtle instance named turtle):
  2401. >>> turtle.shape("circle")
  2402. >>> turtle.shapesize(5,2)
  2403. >>> turtle.settiltangle(45)
  2404. >>> stamp()
  2405. >>> turtle.fd(50)
  2406. >>> turtle.settiltangle(-45)
  2407. >>> stamp()
  2408. >>> turtle.fd(50)
  2409. """
  2410. tilt = -angle * self._degreesPerAU * self._angleOrient
  2411. tilt = (tilt * math.pi / 180.0) % (2*math.pi)
  2412. self.pen(resizemode="user", tilt=tilt)
  2413. def tiltangle(self, angle=None):
  2414. """Set or return the current tilt-angle.
  2415. Optional argument: angle -- number
  2416. Rotate the turtleshape to point in the direction specified by angle,
  2417. regardless of its current tilt-angle. DO NOT change the turtle's
  2418. heading (direction of movement).
  2419. If angle is not given: return the current tilt-angle, i. e. the angle
  2420. between the orientation of the turtleshape and the heading of the
  2421. turtle (its direction of movement).
  2422. Deprecated since Python 3.1
  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()