#$$$$r W Sm ple Draw ng wh Turle Graph CS TURTLE GRAPHCS S A SMPLE WAY TO DO GRAPHCS THAT DATES BACK TO THE 19605. module has been ncluded wh sandard dsrbuons of Pyhon, sarng wh A urle Pphon 2. The "urle" s a cursor ha you can conrol o draw on a wo-dmensonal palee. The las half cenury of experence ndcaes ha s relavely easy for novce programmers o conrol a urle by magnng ha hey are he urle as moves around. The Trrle Graphcs module provdes an easy way o do rwo-dmensonal drawng n Pyhon. B.1.1 Wha ls a Turle? The programmng language Loco was creaed n he 1960s as a eachng ool for chldren o expermen wh mah and programmng. One of s man feaures was a 'urle robor." Lerally, hey magned ha a ehered robo could be conrolled from a worlsaon, wh a pen aached o he robo, so ha chldren could draw. Typcally hey used an arfcal urle (a cursor on he screen) as a way o learn o conrol he robo. Ths approach o drawng was a very mporan concep. All he drawng was done relaue o he presen poson of he unle. could urn, move forward and poson he pen o creae drawngs. Ths approach has proven o be smpler han rjang o each he conceps of Caresan absolue coordnaes. Chldren could lerally "be dre urde" and magne wha would be drawn. Thus was born Trrle Graphcs. fu such, our arfcal Trrle Graphcs sysem has a number of characerscs:.. A wo-dmensonal drawng screen One (or more) urles; each urle has: - A poson - An orenaon or drecon - A pen, wh arbues such as color, wdh, up/down, ec. 709
710 AppENDrx g o smple DRAWTNG wrh TURTLE GRAPHcS \7hen Trrle Graphcs are sared, wh he mpore urle lne, a wndow s creaec wh a small "urde" cursor n he cener. The defaul screen s 400 x 300, hough can b: modfed. The defaul urle s acually an arrow ha pons n he drecon of s curren: orenaon. The urle sars n he mddle of he screen facng eas (rgh$, wh ncreasns angles gong counerclockwse (urle facng 0 degrees, sandard Caresan angle seng-(. See Fgure B.1.1 B.'l The n a urle screen. [Screensho by Pyhon. Copyrgh @ 200L Pyhon Sofware Fou ndaon. Al R ghs Reserved. Reprned wh perm sson.l FGURE 1 All fg,rres n hs chaper were done on Mac OS X. - 201C
SMPLE DRAWNG WTH TURTLE GRAPHCS 711 \7e creae drawngs on he screen by gvng he urde(s) a seres of commands. Le emqdor!m look a some of hose commands. mr,rfff rqg& 8.1.2 Moon As menoned, commands move a urde relave o s curren poson---e.g., "move forward 10 pxels" or "urn ndl 45 degrees." The dsance moved (p*.k) or degrees urned can be neger or floang-pon numbers. These values can be posve or negave as well. Many of he commands have shorcus, bu hese end o be a b crypc (fd for forward, bk for backrvard) so we only show he frrll command names. See he offcal Pyhon documenaon (np:// docs. pyhorr. org / py3k/1 brary/ur 1e. hml#module - ur 1e). Thble B. shows some of hese commands. TABTE B.1 Turle Movemen Commands Speed can be a parculary usefrl arbue. Frs, callng speed ( ) wh no.ugumenrs wll yeld he presen seng. Ths s rue for mos of he arbue sengs of he Trrle Graphcs module: callng hem whour argumens yelds he presenr seng. Second, he urde s purposefully se o be anmaed so you ca.n see dre process of drawng. Howwer, wh longer, more complcaed drawngs, he anmaon can be edous. The defaul seng s 3, wh he range 1-10 ndcang slower o faser. Howwer, a seng of 0 (zero) should mean no anmaon, makng 10 he fases seng. However, f he drvng program self s slow, he urle can sll look slow, bu hs s no because of he speed seng. B.1.3 Drawng Drawng s wha Trrde Graphcs s all abou, and he urle module provdes many commands for jus ha purpose. \7e ls he mporan ones n Thble 8.2.
712 AppENDX B. SMPLE DRAWNG WTH TURTLE GRAPHCS Pu *hs p!n, d.ow' up-no Sb rh lherh.me* Pull he pen PenuP0 pensze "dre kadh) cr cle(radus, exen do(s ze - Vo n - Vo n e, s ep s= Vo n e) Draw a crcle g' #hen''movng. drawng when mov,g' *; posve n. o; (see below). \\ speec -- - penur forwa:: pend.c-.,.:: e, colo r) Samp a copy of he urle a he presen poson. samp0 Reurns a samp-d. Remove sar np uh sg'**n* Clear he screen. clear0 rgh=,'. crc=. crce penup rgh,'. forwa:: Leave he urle poson and orenaon pendc-,.,:- unchanged. rese0 Rese urle o nal confguraon (e (0,0 ucnf;asl); ' rghc :. crc- e : crc-= - : penup TABLE The crcle B.2 Turle Drawng Commands command s a lle rcky. Here are some deals ha are good o kno"' when usng :.. :, Draws a crcle of sze radus. Turle poson s unchanged and he crcle cener poso:: he no orenaon, jus he changng radus dsance lef of heurle. Thus, of he urle draws a dfferen crcle. The argumenr exen s an angle. By seng hs value, you can draw semcrcles, rn'he:= s he number of degres compleed. Boh he urle poson and orenac':' are changed when exen s provded' B-' The argu-.rren seps s he number of sragh lne segmens.used o draw he crcle. parcu;': a o value he by seng (many bu seps), smoohly defaul] he crcle s drawn exlen. number, you can creae polygons. For example, seps=6 wll draw a hexagon. of r:= Code Lsng B.1 exercses some of hese commands. Fgure B.2 s he resul process. rghr: forwa=: rgh: ) forwa:: pencc-,,;- lef,{= f orw'a:: forwa=: rg:-- forwa:: penup rgh: forwa=: rgh:, forwa:: lef,lpend.c-,,,:- # draw a smley face frqn urle mpor rrqror.me * crc-= me. s-
SMPLE DRAWNG WTH TURTLE GRAPHCS Fl'-.:.- -ln-ct,-w, -; ; :!:B:L:- rm[ speed(10) # draw fas! penupo forward(75) # rgh sde of face pendown ( ) rgh (e0) crcle crcle ( # draw a? ey e 25) (1-0) penup0 rgh (e0) # lefr scle of face forward(150) pendown ( ) rgh (e0) crcle crcle ( # draw dx y e 25) (10) penup0 rgh (e0) # cener and down forward(75) rgh ( e0 ) forward(50) pendownfl lef (4s ) # draw d nose forward(40) rgh (13s) forward(56.56) rgh (13s) forward(40) penup0 rgh (135) # cener,, down, /en 100 lef forward(50) rgh (e0) forward(100) lefr (90) pendown # rceed o face as () crcle (100, 180) # smle me.sleep(3) # hold fo, 3 seconrjs s0 we cdn see 713
114 AppENDX g o SMpLE DRAWNG WTH TURTLE GRAPHCS,/\_/\ L \,/ -\""-**.F/ FGURE B.2 Our frs urle fgures. [Screensho by Pyhon. Copyrgh @ 2001 Pyhon Sofware Foundaon. All Rghs Reserved. Reprned wh permsson.j - 2010 b- 8.1.4 Color ffha would good drawng be whou color! The Lurle module provdes ways o spec color and o apply color o your drawng. Specfyng Color There are hree ways o specfy color n Pyhon Turle Graphcs, wo ofwhch are very commorl. A colorsrng. A uple ofhree values, each value n he range 0--255 (usually as rn, bu floa s acceped. A uple of hree values, each value n he range 0.0-1.0 (less common, so no dscusse
SMPLE DRAWNG WTH TURTLE GRAPHCS 715 For colorsrngs, Pyhon acceps any ofhe sandard color srngs provded by Pyhon bul-n drawng module, Tk. Tk provdes a long ls of predefned color srngs, where as n all hngs Pyhon he case of he srng maers. Common srngs such as "green," "blue," "red," and "yellow'are obvous, bu ohers such as "BlanchedAlmond" or "CornfowerBlue" are less so. The full ls can be found a hp: / /wvrw.c1..k/man/cla.5/tkcmd/ colors. hm. n general, color can be complcaed o specfy, and here are varous ways o do. One way s addue color, where a mxure of red, green, and blue s suffcen o reproduce any color. Therefore, a common way o specfy a color s o provde he mxure of he color red, green, and blue conen, ofen referred o as he rgb color. The use ofrgb specfcaons as mos elevson and monors ypcally use lrese hree pxel colors o creae color. Specfyng color as hree neger values beween 0-255 s a common way o represen color n compuer applcaons. Thus, specfyng a uple of (0,0,0) (zero red, zero green, and zero blue) s anoher way o specfy black. Blue would be (0,0,255), red of color s common, (255,0,0), yellow (255,255,0), and CornfowerBlue (100, 149,237). B.1.5 Drawng wh Golor You can specfy wo dfferen drawng colors: he color of he pen and he color used o fll a regon drawn on he screen. No suprsngly, he frs s se by he pencolor command and he second by he f 1lco1or command. Thble B.3 lss he commands. l:': l., L 20lO by TABTE 8.3 Turle Pen Commands Some hngs o noe. el-s o specfy efl'common: ar s acceped) Lo dscussed) color command wll se boh colors n one call. f you provde one argumen, boh he pen and fll colors are se o he argumen color. fyou provde rwo argumens, he frs s he pen color and he second s he fll color. Fllng an area s done by brackeng he drawng wh he rwo commands, begn_ f l ( ) and end-f 1l O. The area flled s whaever occurs beween he rwo calls. \W.hen end-f 11 ( s execured, he area s flled usng he lne beween end and ) begn as he fnal par ofhe flled area. As wh mos of he commands we have seen, callng any of hese commands whou argumens wll yeld he presen values. The
716 AppENDX g o SMpLE DRAWTNG WTH TURTr-ElcnAPHlCS Code Lsng B.2 exercses some of hese calls. Fgure B.3 shows he resul of usns r:.: code. # draw squdr s, chang he pen sze # j us o slow off arud color from urle npor * npor me colormode(2ss) # colors n range 0-255 : def square (lengh, fll*uple) rr Draw d sqluare, sde lengh, color fll-uple f 1lcolor ( f 1 -uple) begn_f11 ( ) for n range (a) : forward ( lengh) rgh ( e0 ) end_f}l ( ) # n ualues, fun o red = 100 green = 0 blue = 50 color-nc = 10 sde-lengh = 50 pen-wdh = 1 pen-nc = 1 pen-lm. = 5 change speed (0 ) for n range(36) square (sde-lengh, : (red, green, blue) ) rgh (10) # range 0-254 red = (red + color-nc) A 255 bue = (b1ue + color-nc) Z 255 green = (green + color-nc) % 255 sde-eng,h +- 3 # rdnge L-p en - lm pen-wdh = ((pen-wdh + pen-nc) Z pen_lm) + 1 pens r-ze (pen-wdh) me.sleep(5)
SMPLE DRAWNG WTH TURTLE GRAPHCS *: -.: l..l /:! al'-",,/h,:': 717 1 :...1..... '1, 'l, j : l l,l, :l :l : :ll, :1 4 'r '.l '1 rl :, : : l ' r ' :, l', '1. : ;!,!: :x 'l ),.; 4 N,,,1 1, 1 : 1 L l,,,! 1. r ' 'r ; ' ;.,,1 B.3 Turle squares. [Screensho by Pyhon. copyrgh @ 2001 Sofware Foundaon. All Rghs Reserved. Reprned wh permsson.j FGURE 8.1.6-2oro by pyhon Oher Gommands There are over 90 urle commands, so here are many hngs you can do wh Trrle Graphcs. Here are some commands we have no ye menroned. The wre command s a b rcky n ha you have o know somehng abou fons o use. A ypcal fon uple would be somehng lke (' AraL,,, 74,,normaf ), bu you need o know wha fons you have on your sysem. The hde and show urle funcons are useful. \7hen you hde he urle, drawng goes much fasrer. Also, you can hde he urle and move he pen somewhere o wre a srng and hen move back and show he urle agan.
718 AppENDrx g o srmple DRAWTNG wrh TURTLE GRAPHcS Se he urle o one of he 6 shapes: shape(a -shape) "classc wre (a r, fon," "arowr" "urler" "rangler" "squae," "crcle. *fo n -wp le onclck (clck{n) Clck on urle, runs he clck-fru. onrelea se(release"l Release mouse hdeurle0 Hde he urle. on urle, calls release{n showurle0 TABTE 8.4 Oher Commands Fnally, you can subclass ha Turl-e class and creae new knds of urles. You car also creae mulple urles on he screen and move hem around n parallel. Code Lsng B.3 shows makng an "explodng" urle, one ha you can clck on anc does a bref anmaon of an exploson, fnally wrng a srng on he screen. Fgure B.= shows he resul of clckng on a urle (whch s n he shape of a urle). frqn urle npor rqpr Lme * clasg Ne^fl\rr.le (Turle) : def --n--(se7f, shape=' ctassc', color=' red' ) : "' sore boorn color, call?aren wh he res Tur e. _- j-nl _ - ( se 7 f,shape=shape sel f. boom-color=color ) def explodelsetf,x,y) : "' quch anrnaon, draw expandng dos, hen clear "' se-f.do (5, sel.f.boom-color) sef f.do (20, setf.boom-co1or) sef f.do (50, sef.boom-co1or) # clear he color self.do (50, 'whe' ) boooom!', fon= (uara7", " 14", nomat') ) self.wre ( ' 1 = Newlurle (shape='urle') l-. onclck (1. explode) 1. forr,rard (100) me. sleep (4 ) B.2TDE
8.2 o TDBTS *,#,fu*,,2,,,u.&f 719 &1,e,,,,, ff,:,ew:wl & $ kc#cm! ::1 ' 1,.,!1 1. 1 1!1,:r 1, ',!,:,ll,lf;!..{,, FGURE B.4 Turle exploson! [Screensho by Pyhon. Copyrgh @ 2001 Sofware Foundaon. All Rghs Reserved. Reprned wh permsson.j - 2010 by Pyhon B.2TDBTS 8.2.1 Keepng he Wndow 0pen The drawng wndow has a endency o dsappear very quckly. One way o "hold" he wndow s o use he sleep funcon n he me module, as follows: alpor me me. sleep ( seconds ) The program wll wa he number of seconds ndcaed before ends.
724 APPENDX B o SMPLE DRAWNG WTH TURTLE GRAPHCS 8.2.2 Workng Ncely wh DLE DLE can be a b ouchy when workng wh oher graphcs programs, such as Tur:-. Graphcs. Subsequenly, afer you open a program n DLE ha does graphcs (such.' Trrle), some of he wndows may hang, or no close. To ge around hs, you can u:: he os. -ex ( ) funcon from he os module. Noe he underlne n he name. lrla.:. he os.*ex(1) funcon he las lne n he program. Usng he me.sleep c''. rgh before he os. -ex (1) call works well so ha he wndow wll say open for son= number of seconds and hen close. mpor os. _ex (1) os