5.2.GRAPHICSPROGRAMMING 63
Figure5.1:Screenshotwitha Pythonwindow anda GraphWin
Alloftherestofthegraphicsexampleswillassumethattheentiregraphicsmodulehasbeenimported
usingfrom.
Let’s tryourhandatsomedrawing. Agraphicswindowisactuallya collectionoftiny pointscalled
pixels(shortforpictureelements). Bycontrollingthecolorofeachpixel,wecontrolwhatisdisplayed
inthewindow. Bydefault,aGraphWinis 200 pixelstalland 200 pixelswide. Thatmeansthereare
40,000pixelsintheGraphWin. Drawinga picturebyassigninga colortoeachindividualpixel wouldbea
dauntingchallenge.Instead,wewillrelyona libraryofgraphicalobjects.Eachtypeofobjectdoesitsown
bookkeepingandknowshow todraw itselfintoaGraphWin.
ThesimplestobjectinthegraphicsmoduleisaPoint. Ingeometry, a pointis a dimensionless
locationinspace.Apointislocatedbyreferencetoa coordinatesystem. OurgraphicsobjectPointis
similar;it canrepresenta locationin aGraphWin. We definea pointbysupplyingxandycoordinates
xy.
Thexvaluerepresentsthehorizontallocationofthepoint,andtheyvaluerepresentsthevertical.
Traditionally, graphicsprogrammerslocatethepoint
0 0 intheupper-leftcornerofthewindow. Thus
xvaluesincreasefromlefttoright,andyvaluesincreasefromtoptobottom. Inthedefault 200 x 200
GraphWin, thelower-rightcornerhasthecoordinates
199 199 . DrawingaPointsetsthecolorofthe
correspondingpixel intheGraphWin. Thedefaultcolorfordrawingis black.
Hereis a sampleinteractionwithPythonillustratingtheuseofPoints.
p = Point(50,60)
p.getX()
50
p.getY()
60
win = GraphWin()
p.draw(win)
p2 = Point(140,100)
p2.draw(win)
ThefirstlinecreatesaPointlocatedat
50 60 . AfterthePointhasbeencreated,itscoordinatevaluescan
beaccessedbytheoperationsgetXandgetY. APointis drawnintoa window usingthedrawoperation.
Inthisexample,two differentpointobjects(pandp2) arecreatedanddrawnintotheGraphWincalled
win. Figure5.2showstheresultinggraphicaloutput.
Inadditiontopoints,thegraphicslibrarycontainscommandsfordrawinglines,circles,rectangles,ovals,