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