PageRenderTime 183ms CodeModel.GetById 9ms RepoModel.GetById 0ms app.codeStats 1ms

/Lib/lib-tk/turtle.py

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