Difference between revisions of "CS110:Lab08"

From IPRE Wiki
Jump to: navigation, search
('''Copying and Pasting an Image ''')
Line 1: Line 1:
='''Lab 08: Graphics Part II: Making Photoshop Functions''' =
+
='''Lab 07: Introduction to Graphics''' =
  
  
 
=='''Objective'''==
 
=='''Objective'''==
* Create functions to manipulate images
+
* Use various Myro commands to create and manipulate graphical objects
  
== '''Image Transformations ''' ==
+
==To Do==
 +
* Execute and modify the pieces of code introduced in this session
 +
* Read Chapter 8 of your text
  
You've probably used a variety of graphics editors such as ''Paint, Adobe Photoshop, GIMP'',
+
== Useful Links ==
etc. to manipulate or enhance your pictures. In this lab session, you will be exploring and
+
creating functions to transform your images in the same way these image editors are able to. <br>
+
  
''Image transformations'' are operations that change the appearance of an image or its spatial location.
+
[[Myro_Reference_Manual#Graphics_Objects_Interface| Myro Graphics Objects Interface]] <br>
Common image transformations include '''resize (shrink''' or '''enlarge)''', '''rotate''', '''crop''',
+
[http://cs.brynmawr.edu/~dkumar/Myro/Text/June09/PDF/Chapter8.pdf| Chapter 8 of your Text]
'''translate (i.e''' '''move'''), and '''flip'''. There are also functions to change the color or brightness
+
of an image. <br>
+
  
In this lab, we will explore four functions: resize, colorize, translate and paste. At the end of this session,
+
== Creating a Graphics Window ==
you will be able to use this functions (and create your own) to transform your images into beautiful mosaics. Once again, you are
+
only limited by your imagination and creativity.
+
  
== '''Resizing an Image: Shrinking and Enlarging ''' ==
+
You have probably used different computer programs such as ''Paint'' or ''GIMP'' to draw different shapes and edit images.
 +
In this lab session you will be creating and manipulating various drawings.
 +
The Myro module provides various commands you can use to draw objects, color them and
 +
manipulate them in other ways. In order to draw anything you first need to create a window or canvas
 +
to draw it on. You can create such a window using the following command:
  
Below is a program that takes an image and shrink it by a specified factor, F.
+
<pre>
For instance, if the original image is 1000x1000 pixels and you wanted to shrink
+
myCanvas = GraphWin()
it by a factor of 5, you would end up with an image of size 200x200.
+
</pre>
  
 +
When you enter this command. A window similar to the one below should appear:
 +
[[Image:Graphwin.GIF|center]]
 +
 +
To close the window, use the following command:
 
<pre>
 
<pre>
def main():
+
myCanvas.close()
    # read an image and display it
+
    oldPic = makePicture(pickAFile())
+
    show(oldPic, "Before")
+
    X = getWidth(oldPic)
+
    Y = getHeight(oldPic)
+
    # Input the shrink factor and computer size of new image
+
    F = int(ask("Enter the shrink factor."))
+
    newx = X/F
+
    newy = Y/F
+
    # create the new image
+
    newPic = makePicture(newx, newy)
+
    for x in range(newx):
+
        for y in range(newy):
+
            setPixel(newPic, x, y, getPixel(oldPic, x*F, y*F))
+
    show(newPic, "After")
+
 
</pre>
 
</pre>
  
The image below on the right is 425x400 pixels in dimension. After shrinking it by a factor of 2,
+
By default, the size of the window is 200 pixels high and 200 pixels wide and its name is
the result is the image on the right with dimensions 212x200. <br>
+
“Graphics Window”. To change the size of the window and to rename it, you can execute the command below:
 +
<pre>
 +
myCanvas = GraphWin(“My BigCanvas”, 300, 300)
 +
</pre>
  
[[image:Asimo2.GIF|Original Image (425x400)]] [[Image:Asimo3.GIF|After Shrinking (212x200, F=2)]]
+
The command above creates a window called “My BigCanvas” that is 300 pixels wide and 300 pixels tall.
 +
You can change the background color of your graphics window to yellow as shown below:
 +
<pre>
 +
myCanvas.setBackground(“yellow”)
 +
</pre>
 +
[[Image:YellowWin.GIF|center]]
 +
 
 +
Examples of colors you can use are: “red”, “blue”, “gray”, “yellow”, “AntiqueWhite”, “LavenderBlush”, “WhiteSmoke”.
 +
There are several thousand color names to choose from. To see a list of these colors, Google: "color names list".
 +
 
 +
You can also create your own colors by specifying their red, green, and blue components.
 +
Recall from previous labs and lectures that each color is made up of three values: '''RGB''' or red, green and blue color
 +
values. Each of the these values can be in the range 0 to 255. For instance, the RGB values of pure red are: (255, 0, 0).
 +
White is defined as (255,255, 255), black as (0, 0, 0) and pink as (255, 175, 175). There are as many as 256x256x256 colors
 +
(i.e. over 16 million colors!). Given specific RGB values, you can create a new color by using the
 +
command, color_rgb:
 +
<pre>
 +
myColor = color_rgb(255, 175, 175)
 +
</pre>
  
'''Exercise 1: ''' Write a function ('''resize''') that gives the user the option to '''enlarge'''
+
== Drawing Objects on your Canvas ==
or '''shrink''' an image by some factor. The user should have the option to choose this factor as well.
+
Your function should display the new image after it has been resized.
+
  
== '''Changing Colors in your Image ''' ==
+
Once you've created a window, you can then draw a variety of geometrical objects (points, lines, circles, rectangle, and
 +
even text and images) on your canvas. Before you draw an object, however, you must first ''create'' it.
 +
Before you can do this, you should become familiar with the coordinate system of the graphics window.
  
In the previous labs, you've manipulated the pixels in the pictures your robot take
+
In a graphics window with width, W=200 and height H=400 (i.e WxH pixels) the pixel
to identify various objects such as the orange pyramid. In this section you will  
+
(0, 0) is at the top left corner and the pixel (199, 399) will be at the bottom
experiment with changing colors in other images (these do not have to be pictures your robots take).
+
right corner. That is, x-coordinates increase as you go right and y-coordinates
Recall that you can define your own colors using the makeColor function. For instance,
+
increase as you go down. <br>
to define a color called awesomeness with RGB values 156,120,47 you would use the following code:
+
  
 +
The simplest object that you can ''create'' is a point. This is done as follows:
 
<pre>
 
<pre>
awesomeness = makeColor(156,120,47)
+
p = Point(100, 50)
 
</pre>
 
</pre>
  
Also, you can load pictures from your computer with the makePicture() function:
+
In the above command, p is an object that is a Point whose x-coordinate is at 100 and y-coordinate
 +
is at 50. This command ''creates'' a Point object. In order to draw it on the canvas, you
 +
have to enter the command:
 +
<pre>
 +
p.draw(myCanvas)
 +
</pre>
  
 +
In python, objects such as points, strings, lists etc. have standard operations that can be
 +
performed on them. The general syntax for carrying out an operation on an object is: <br>
 +
 +
<object>.<function>(<parameters>)
 +
 +
In the example above, <object> is the name p which was earlier
 +
defined to be a Point object, <function> is draw, and <parameters> is
 +
myCanvas. The draw function requires the graphics window as the parameter.
 +
That is, you are asking the point represented by p to be drawn in the window
 +
specified as its parameter. The Point objects have other useful functions.
 +
For instance, you can use the following commands to get the  x- and y-coordinates
 +
of the point:
 
<pre>
 
<pre>
mySavedPicture = makePicture("robots.jpg")
+
>>> p.getX()
show(mySavedPicture)
+
100
 +
>>> p.getY()
 +
50
 
</pre>
 
</pre>
  
To navigate and then select the image to load, use the following combination:
+
Objects are created using their ''constructors'' like the Point(x, y) constructor above. You
 +
will use lots of constructors in this section for creating other graphics objects. For instance,
 +
you can create a line object in a similar manner. To create a line, you must specify the location the two end
 +
points of the line. Therefore a line that starts from the point (0, 0) and ends at the point
 +
(100, 200) can be created and drawn as follows:
 +
 
 
<pre>
 
<pre>
mySavedPicture = makePicture(pickAFile())
+
L = Line(Point(0,0), Point(100,200))
show(mySavedPicture)
+
L.draw(myCanvas)
 
</pre>
 
</pre>
  
When you call the pickAFile command, a navigational dialog box is displayed. You can
+
The image below shows the canvas with the objects drawn so far.
use this to navigate to any folder and select a file to open as any JPEG image.  
+
  
The red pixels in the first butterfly below have been changed to blue and its yellow pixels
+
[[Image:WinLine.GIF|center]]
to red.  
+
You can then draw the line using the same draw command as above:
 +
<pre>
 +
L.draw(myCanvas)
 +
</pre>
  
[[Image:Butterfly1.JPG]]<--- '''Butterfly1''' [[Image:Butterfly2.JPG]]<--- '''Butterfly2'''
+
To get the values of a line’s end points, use the following commands:
 +
<pre>
 +
>>> start = L.getP1()
 +
>>> start.getX
 +
0
 +
>>> end = L.getP2()
 +
>>> end.getY()
 +
200
 +
</pre>
  
You can get the original butterfly (on the left) with this command:
+
Here is a small Python loop that can be used to create and draw several lines:
 +
<pre>
 +
for n in range(0, 200, 5):
 +
  L=Line(Point(n,25),Point(100,100))
 +
  L.draw(myCanvas)
 +
</pre>
  
>>> butterfly = makePicture("http://wiki.roboteducation.org/Image:Butterfly1.JPG")
+
[[Image:LinesWin.GIF|center]]
  
'''Exercise 2: ''' Write a program that takes butterfly1 and changes two or more of the colors in the image
+
In the loop above the value of n starts at 0 and increases by
to produce an output like butterfly2. To use image butterfly1, right click on the image and select ''Save Image As''.
+
5 after each iteration all the way up to but not including 200 (i.e. 195). For each value of
 +
n a new Line object is created with starting co-ordinates (n,25) and end point at (100, 100).
  
== '''Translating an Image ''' ==
+
'''Do This:''' Try out all the commands introduced in this lab. Then observe the
 +
effects produced by the loop above. Change the increment 5 in the loop above
 +
to different values (1, 3, etc.) and observe the effect. Next, try out the
 +
following loop:
 +
<pre>
 +
for n in range(0, 200, 3):
 +
L = Line(Point(n, 100), Point(180, 180))
 +
L.draw(myCanvas)
 +
wait(0.3)
 +
L.undraw()
 +
</pre>
 +
 
 +
The ''undraw'' function, as the name implies, undraws a particular object. In the above for loop,
 +
a line is created for each value of n, drawn, an after 0.3 seconds, erased.
 +
Once again, you should modify different values in this loop, such as the increment or the wait time
 +
to see the effect.
 +
 
 +
== Drawing Other Geometric Objects ==
  
In this section you will apply what you already know about Graphics to another type of image
+
You can draw several other geometrical shapes such as: circles, rectangles, ovals, and
transformation, translation. A ''translation'' is simply a movement in the x,y plane of your window.
+
polygons. Once again, in order to draw any of these shapes, you must first create it. For instance,
When you were introduced to graphics, you created a variety of polygons as well as points and lines,
+
to draw a circle, you can issue the commands:
drew these objects in a graphics window and then manipulated them
+
in various ways. You can also treat an image like an object and move it around in your canvas in the same way
+
you did with rectangles, circles etc. To convert a picture your robot takes into an ''image'', use the following:
+
  
 
<pre>
 
<pre>
picture = takePicture()
+
centerPoint = Point(100, 150)
pixmap  = makePixmap(picture)
+
radius = 30
image = Image(Point(x, y), pixmap)
+
C = Circle(centerPoint, radius)
 +
C.draw(myCanvas)
 
</pre>
 
</pre>
  
If the picture was taken by your camera or downloaded from the web, you will need to use the  
+
centerPoint is a Point object and radius is specified in pixels. Thus, the circle C is
makePicture command first so that the Myro commands will work on it. The code below creates two pixmap
+
centered at (100, 150) and has a radius of 30. For details on how other shapes are drawn,
images, draws these images on a canvas and then translates them within the canvas using the move command.  
+
you can go to the link to ''Myro Graphics Objects Interface'' above. <br><br>
  
 +
All the geometrical objects have several functions in common. For instance,
 +
you can get the center point of a circle, (as well as a rectangle, or an oval) by
 +
using the command:
 +
<pre>
 +
centerPoint = C.getCenter()
 +
</pre>
  
 +
By default, all objects are drawn in black (this may be white if you are using a Mac).
 +
There are a number of ways to modify colors for objects. For each object you can specify a color for its
 +
outline as well as a color to fill it with. For example, to draw a circle centered
 +
at (100, 150), radius 30, and outline color red, and fill color yellow:
 
<pre>
 
<pre>
myCanvas = GraphWin("My BigCanvas", 400, 400)
+
C = Circle(Point(100, 150), 30)
oldPic = makePicture(pickAFile())
+
C.draw(myCanvas)
#show(oldPic)
+
C.setOutline(“red”)
pixmap  = makePixmap(oldPic)
+
C.setFill(“yellow”)
butterfly1 = Image(Point(50, 50), pixmap)
+
butterfly2 = Image(Point(300, 300), pixmap)
+
butterfly1.draw(myCanvas)
+
butterfly2.draw(myCanvas)
+
butterfly1.move(50,50)
+
butterfly2.move(-50,-50)
+
 
</pre>
 
</pre>
  
The picture you choose must be smaller than your canvas. An ideal size is 100x100.
+
Note: setFill and setOutline have the same effect on Point and Line objects
The images below show the translation of two butterflies. As specified by the code above,
+
(since there is no place to fill any color). Also, the line or the
butterfly1 starts out in the upper left corner and is translated 50 pixels along the x axis and the y axis.
+
outline drawn is always 1 pixel thick. You can change the thickness by using
Butterfly2 starts out near the lower right corner and is translated -50 pixels along the x axis and the y axis.
+
the command setWidth(<pixels>). For example to change the width of the circle’s outline to 5 pixels:
 +
<pre>
 +
C.setWidth(5)
 +
</pre>
  
[[Image:Translate1.JPG]] <--- Before Translation [[Image:Translate2.JPG]] <--- After Translation
+
== Drawing Random Circles ==
  
== '''Copying and Pasting an Image ''' ==
+
'''Do This:''' The program below draws several circles of random sizes with
 +
random colors. Try it out! A sample output is shown below.
  
Copying an image can prove useful in image transformations and other applications. Below you will find functions for copying and pasting an image onto a canvas.
 
  
 +
[[Image:RandomCircles.GIF|center]]
 
<pre>
 
<pre>
from myro import *
+
# File: randomCirles.py
 +
# Description: Program to draw a bunch of random colored circles
  
def createCanvas():
+
from random import *
    canvas = GraphWin("My BigCanvas", 200, 200)
+
    pic = makePicture(pickAFile())
+
    return [pic, canvas]
+
  
def makeGray(pic):
+
def makeCircle(x, y, r):
     pic2 = copyPicture(pic)
+
     # creates a Circle centered at point (x, y) of radius r
     for pix in getPixels(pic2):
+
     return Circle(Point(x, y), r)
        r, g, b = getRGB(pix)
+
        gray = (r + g + b) / 3
+
        setRGB(pix, [gray, gray, gray])
+
    return pic2
+
  
def paste(pic1, x, y, pic2):
+
def makeColor():
     newpic = copyPicture(pic1)
+
     # creates a new color using random RGB values
     for col in range(getWidth(pic2)):
+
    red = randrange(0, 256)
        for row in range(getHeight(pic2)):
+
     green = randrange(0, 256)
            setPixel(newpic, col + x, row + y,
+
    blue = randrange(0, 256)
                    getColor(getPixel(pic2, col, row)))
+
    return color_rgb(red, green,blue)
    return newpic
+
  
 +
def main():
 +
    # Create and display a graphics window
 +
    width = 300
 +
    height = 300
 +
    myCanvas = GraphWin(" Random Circles",width,height)
 +
    myCanvas.setBackground("white")
 +
    # draw a bunch of random circles with random colors
 +
    N = 200
 +
    for i in range(N):
 +
        # pick random center point and radius in the window
 +
        x = randrange(0,width)
 +
        y = randrange(0,height)
 +
        r = randrange(5, 25)
 +
        c = makeCircle(x, y, r)
 +
        # select a random color
 +
        c.setFill(makeColor())
 +
        c.draw(myCanvas)
 +
main()
 +
</pre>
  
 +
'''Do This:''' Modify the program to input (specify) the number of circles
 +
to be drawn. Recall: randrange(m,n) returns a random number in range [m to n-1].
 +
Modify the program to create other geometric shapes and draw them randomly.
 +
 +
== Animating Geometric Objects ==
 +
You can move any geometric object you draw in the graphics window by using the command
 +
'''move(dx, dy)'''. For example, to move the circle, C, 10 pixels to the right and 5
 +
pixels down you can use the command (Note: C must have already been predefined):
 +
<pre>
 +
C.move(10, 5)
 +
</pre>
 +
'''Do This:''' Write a program that moves a circle about (randomly) in the
 +
graphics window. First, enter this following program and try it out.
 +
<pre>
 +
# Moving a circle
 +
 +
from random import *
 
def main():
 
def main():
  butterfly = makePicture("http://wiki.roboteducation.org/Image:Butterfly1.JPG")
+
    # create and draw the graphics window
  bigpic = makePicture(500, 500)
+
    w = GraphWin("Moving Circle", 500, 500)
  bigpic = paste(bigpic, 10, 10, butterfly)
+
    w.setBackground("white")
  bigpic = paste(bigpic, 200, 200, makeGray(butterfly))
+
    # Create a red circle
  show(bigpic)
+
    c = Circle(Point(250, 250), 50)
 +
    c.setFill("purple")
 +
    c.draw(w)
 +
    # Do a simple animation for 200 steps
 +
    for i in range(200):
 +
        c.move(randrange(-4, 5), randrange(-4, 5))
 +
        wait(0.2)
 +
main()
 
</pre>
 
</pre>
 +
'''Do This:''' Write a program to move different geometric objects around in
 +
your graphics window.
 +
==Drawing Text and Images==
 +
 +
You can also insert '''text''' into your graphics window just like you did with geometric shapes.
 +
You will first have to create the text using the command:
 +
<pre>
 +
myText = Text(<anchor point>, <string>)
 +
</pre>
 +
 +
and then draw it. You can specify the type face, size, and style of the text. See the Myro graphics reference
 +
at the end of chapter 8 in your text or on the link provided above to get more details about the
 +
different features of texts. <br>
 +
 +
'''Images''' can also be treated like the geometric objects you have been creating and drawing. You can create an
 +
image using the Image command:
 +
<pre>
 +
myPhoto = Image(<centerPoint>, <file name>)
 +
</pre>
 +
 +
You have to have an already prepared image in one of the common image
 +
formats (like JPEG, GIF, etc.) and stored in a file (<file name>). Once the
 +
image object is created, it can be drawn, undrawn, or moved just like other
 +
shapes. <br>
 +
 +
You can use a combination of texts, images, and geometric objects to create
 +
simple and more advanced graphical programs such as making plots, creating art,
 +
developing video games or graphical user interfaces, or even an
 +
animated story. What you do with this knowledge is only limited by your creativity.
 +
 +
= Assignment 07 =
 +
 +
'''*** Exercise 6 will be graded as a BONUS''' worth 4 points. Exercises 1-4 will be graded out of 10. <br>
 +
 +
---------------------------------------------------------------------------------------------------
 +
'''***Original Assignment below'''<br>
 +
 +
'''Chapter 8, Exercises 1 - 4, and 6. ''' '''Note: ''' Question 6 is modified.  These exercises are detailed below: <br>
 +
 +
'''Exercise 1: ''' Using the graphics commands learned in this session (and detailed in your text), write a
 +
program to generate a seasonal drawing: winter, summer, beach, or a festival scene. <br>
  
[[Image:CopyPaste.JPG]]
+
'''Exercise 2: ''' Write a program that has a function drawRobot(x, y, w) such that it draws the
 +
figure of a robot shown on the right (see your text for this image, pg. 212). The robot is anchored at (x, y) and is drawn in the window, w. Also notice that the robot is entirely made up of rectangles (8 of them). <br>
  
= Assignment 08: Adding More Functions to your Photoshop Library =
+
'''Exercise 3: ''' Using the drawRobot function from the previous exercise, draw a pyramid of robot as shown on the right
 +
(see your text for this image, pg. 212).
  
'''Part I '''<br>
+
'''Exercise 4: ''' Suppose that each robot from the previous exercise is colored using one of
Exercises 1 and 2 of Lab 8 <br>
+
the colors: red, blue, green, and yellow. Each time a robot is drawn, it uses the
 +
next color in the sequence. Once the sequence is exhausted, it recycles. Write
 +
a program to draw the above pyramid so robots appear in these colors as they
 +
are drawn. You may decide to modify drawRobot to have an additional
 +
parameter: drawRobot(x, y, c, w) or you can write it so that drawRobot
 +
decides which color it chooses. Complete both versions and compare the
 +
resulting programs. Discuss the merits and/or pitfalls of these versions with
 +
friends. [Hint: Use a list of color names.] Note: You only need to ensure that each robot on the same level of the pyramid has the same color. <br>
  
'''Part II'''<br>
+
'''Exercise 6: ''' Do a web search on fractals and write programs to draw '''two''' simple
'''1. Horizontal Flip: ''' Write a function that will flip an image horizontally as displayed below: <br>
+
fractals. For example, ''Koch Snowflakes, Sierpinski Triangles, Mandelbrot
[[Image:HorizonFlip.jpg]] <br>
+
Sets, Julia Sets,'' etc.
  
'''2. Collage: ''' Write a program to create a mosaic of images on your canvas. Your functions should utilize the translate, horizontal flip and the colorize function you create in class. ''The colorize function can be found on the link to Photolib on the main course page.''
+
= Links =
  
= Links to Course-Related Pages =
 
 
* Back to [http://wiki.roboteducation.org/CS110_Lab Lab Home Page]  
 
* Back to [http://wiki.roboteducation.org/CS110_Lab Lab Home Page]  
 
* Back to [http://cs.brynmawr.edu/Courses/cs110/fall2009/ Course Home Page]
 
* Back to [http://cs.brynmawr.edu/Courses/cs110/fall2009/ Course Home Page]

Revision as of 15:37, 18 February 2010

Lab 07: Introduction to Graphics

Objective

  • Use various Myro commands to create and manipulate graphical objects

To Do

  • Execute and modify the pieces of code introduced in this session
  • Read Chapter 8 of your text

Useful Links

Myro Graphics Objects Interface
Chapter 8 of your Text

Creating a Graphics Window

You have probably used different computer programs such as Paint or GIMP to draw different shapes and edit images. In this lab session you will be creating and manipulating various drawings. The Myro module provides various commands you can use to draw objects, color them and manipulate them in other ways. In order to draw anything you first need to create a window or canvas to draw it on. You can create such a window using the following command:

myCanvas = GraphWin()

When you enter this command. A window similar to the one below should appear:

Graphwin.GIF

To close the window, use the following command:

myCanvas.close()

By default, the size of the window is 200 pixels high and 200 pixels wide and its name is “Graphics Window”. To change the size of the window and to rename it, you can execute the command below:

myCanvas = GraphWin(“My BigCanvas”, 300, 300)

The command above creates a window called “My BigCanvas” that is 300 pixels wide and 300 pixels tall. You can change the background color of your graphics window to yellow as shown below:

myCanvas.setBackground(“yellow”)
YellowWin.GIF

Examples of colors you can use are: “red”, “blue”, “gray”, “yellow”, “AntiqueWhite”, “LavenderBlush”, “WhiteSmoke”. There are several thousand color names to choose from. To see a list of these colors, Google: "color names list".

You can also create your own colors by specifying their red, green, and blue components. Recall from previous labs and lectures that each color is made up of three values: RGB or red, green and blue color values. Each of the these values can be in the range 0 to 255. For instance, the RGB values of pure red are: (255, 0, 0). White is defined as (255,255, 255), black as (0, 0, 0) and pink as (255, 175, 175). There are as many as 256x256x256 colors (i.e. over 16 million colors!). Given specific RGB values, you can create a new color by using the command, color_rgb:

myColor = color_rgb(255, 175, 175)

Drawing Objects on your Canvas

Once you've created a window, you can then draw a variety of geometrical objects (points, lines, circles, rectangle, and even text and images) on your canvas. Before you draw an object, however, you must first create it. Before you can do this, you should become familiar with the coordinate system of the graphics window.

In a graphics window with width, W=200 and height H=400 (i.e WxH pixels) the pixel (0, 0) is at the top left corner and the pixel (199, 399) will be at the bottom right corner. That is, x-coordinates increase as you go right and y-coordinates increase as you go down.

The simplest object that you can create is a point. This is done as follows:

p = Point(100, 50)

In the above command, p is an object that is a Point whose x-coordinate is at 100 and y-coordinate is at 50. This command creates a Point object. In order to draw it on the canvas, you have to enter the command:

p.draw(myCanvas)

In python, objects such as points, strings, lists etc. have standard operations that can be performed on them. The general syntax for carrying out an operation on an object is:

<object>.<function>(<parameters>)

In the example above, <object> is the name p which was earlier defined to be a Point object, <function> is draw, and <parameters> is myCanvas. The draw function requires the graphics window as the parameter. That is, you are asking the point represented by p to be drawn in the window specified as its parameter. The Point objects have other useful functions. For instance, you can use the following commands to get the x- and y-coordinates of the point:

>>> p.getX()
100
>>> p.getY()
50

Objects are created using their constructors like the Point(x, y) constructor above. You will use lots of constructors in this section for creating other graphics objects. For instance, you can create a line object in a similar manner. To create a line, you must specify the location the two end points of the line. Therefore a line that starts from the point (0, 0) and ends at the point (100, 200) can be created and drawn as follows:

L = Line(Point(0,0), Point(100,200))
L.draw(myCanvas)

The image below shows the canvas with the objects drawn so far.

WinLine.GIF

You can then draw the line using the same draw command as above:

L.draw(myCanvas)

To get the values of a line’s end points, use the following commands:

>>> start = L.getP1()
>>> start.getX
0
>>> end = L.getP2()
>>> end.getY()
200

Here is a small Python loop that can be used to create and draw several lines:

for n in range(0, 200, 5):
   L=Line(Point(n,25),Point(100,100))
   L.draw(myCanvas)
LinesWin.GIF

In the loop above the value of n starts at 0 and increases by 5 after each iteration all the way up to but not including 200 (i.e. 195). For each value of n a new Line object is created with starting co-ordinates (n,25) and end point at (100, 100).

Do This: Try out all the commands introduced in this lab. Then observe the effects produced by the loop above. Change the increment 5 in the loop above to different values (1, 3, etc.) and observe the effect. Next, try out the following loop:

for n in range(0, 200, 3):
	L = Line(Point(n, 100), Point(180, 180))
	L.draw(myCanvas)
	wait(0.3)
	L.undraw()

The undraw function, as the name implies, undraws a particular object. In the above for loop, a line is created for each value of n, drawn, an after 0.3 seconds, erased. Once again, you should modify different values in this loop, such as the increment or the wait time to see the effect.

Drawing Other Geometric Objects

You can draw several other geometrical shapes such as: circles, rectangles, ovals, and polygons. Once again, in order to draw any of these shapes, you must first create it. For instance, to draw a circle, you can issue the commands:

centerPoint = Point(100, 150)
radius = 30
C = Circle(centerPoint, radius)
C.draw(myCanvas)

centerPoint is a Point object and radius is specified in pixels. Thus, the circle C is centered at (100, 150) and has a radius of 30. For details on how other shapes are drawn, you can go to the link to Myro Graphics Objects Interface above.

All the geometrical objects have several functions in common. For instance, you can get the center point of a circle, (as well as a rectangle, or an oval) by using the command:

centerPoint = C.getCenter()

By default, all objects are drawn in black (this may be white if you are using a Mac). There are a number of ways to modify colors for objects. For each object you can specify a color for its outline as well as a color to fill it with. For example, to draw a circle centered at (100, 150), radius 30, and outline color red, and fill color yellow:

C = Circle(Point(100, 150), 30)
C.draw(myCanvas)
C.setOutline(“red”)
C.setFill(“yellow”)

Note: setFill and setOutline have the same effect on Point and Line objects (since there is no place to fill any color). Also, the line or the outline drawn is always 1 pixel thick. You can change the thickness by using the command setWidth(<pixels>). For example to change the width of the circle’s outline to 5 pixels:

C.setWidth(5)

Drawing Random Circles

Do This: The program below draws several circles of random sizes with random colors. Try it out! A sample output is shown below.


RandomCircles.GIF
# File: randomCirles.py
# Description: Program to draw a bunch of random colored circles

from random import *

def makeCircle(x, y, r):
    # creates a Circle centered at point (x, y) of radius r
    return Circle(Point(x, y), r)

def makeColor():
    # creates a new color using random RGB values
    red = randrange(0, 256)
    green = randrange(0, 256)
    blue = randrange(0, 256)
    return color_rgb(red, green,blue)

def main():
    # Create and display a graphics window
    width = 300
    height = 300
    myCanvas = GraphWin(" Random Circles",width,height)
    myCanvas.setBackground("white")
    # draw a bunch of random circles with random colors
    N = 200
    for i in range(N):
        # pick random center point and radius in the window
        x = randrange(0,width)
        y = randrange(0,height)
        r = randrange(5, 25)
        c = makeCircle(x, y, r)
        # select a random color
        c.setFill(makeColor())
        c.draw(myCanvas)
main()

Do This: Modify the program to input (specify) the number of circles to be drawn. Recall: randrange(m,n) returns a random number in range [m to n-1]. Modify the program to create other geometric shapes and draw them randomly.

Animating Geometric Objects

You can move any geometric object you draw in the graphics window by using the command move(dx, dy). For example, to move the circle, C, 10 pixels to the right and 5 pixels down you can use the command (Note: C must have already been predefined):

C.move(10, 5)

Do This: Write a program that moves a circle about (randomly) in the graphics window. First, enter this following program and try it out.

# Moving a circle

from random import *
def main():
    # create and draw the graphics window
    w = GraphWin("Moving Circle", 500, 500)
    w.setBackground("white")
    # Create a red circle
    c = Circle(Point(250, 250), 50)
    c.setFill("purple")
    c.draw(w)
    # Do a simple animation for 200 steps
    for i in range(200):
        c.move(randrange(-4, 5), randrange(-4, 5))
        wait(0.2)
main()

Do This: Write a program to move different geometric objects around in your graphics window.

Drawing Text and Images

You can also insert text into your graphics window just like you did with geometric shapes. You will first have to create the text using the command:

myText = Text(<anchor point>, <string>)

and then draw it. You can specify the type face, size, and style of the text. See the Myro graphics reference at the end of chapter 8 in your text or on the link provided above to get more details about the different features of texts.

Images can also be treated like the geometric objects you have been creating and drawing. You can create an image using the Image command:

myPhoto = Image(<centerPoint>, <file name>)

You have to have an already prepared image in one of the common image formats (like JPEG, GIF, etc.) and stored in a file (<file name>). Once the image object is created, it can be drawn, undrawn, or moved just like other shapes.

You can use a combination of texts, images, and geometric objects to create simple and more advanced graphical programs such as making plots, creating art, developing video games or graphical user interfaces, or even an animated story. What you do with this knowledge is only limited by your creativity.

Assignment 07

*** Exercise 6 will be graded as a BONUS worth 4 points. Exercises 1-4 will be graded out of 10.


***Original Assignment below

Chapter 8, Exercises 1 - 4, and 6. Note: Question 6 is modified. These exercises are detailed below:

Exercise 1: Using the graphics commands learned in this session (and detailed in your text), write a program to generate a seasonal drawing: winter, summer, beach, or a festival scene.

Exercise 2: Write a program that has a function drawRobot(x, y, w) such that it draws the figure of a robot shown on the right (see your text for this image, pg. 212). The robot is anchored at (x, y) and is drawn in the window, w. Also notice that the robot is entirely made up of rectangles (8 of them).

Exercise 3: Using the drawRobot function from the previous exercise, draw a pyramid of robot as shown on the right (see your text for this image, pg. 212).

Exercise 4: Suppose that each robot from the previous exercise is colored using one of the colors: red, blue, green, and yellow. Each time a robot is drawn, it uses the next color in the sequence. Once the sequence is exhausted, it recycles. Write a program to draw the above pyramid so robots appear in these colors as they are drawn. You may decide to modify drawRobot to have an additional parameter: drawRobot(x, y, c, w) or you can write it so that drawRobot decides which color it chooses. Complete both versions and compare the resulting programs. Discuss the merits and/or pitfalls of these versions with friends. [Hint: Use a list of color names.] Note: You only need to ensure that each robot on the same level of the pyramid has the same color.

Exercise 6: Do a web search on fractals and write programs to draw two simple fractals. For example, Koch Snowflakes, Sierpinski Triangles, Mandelbrot Sets, Julia Sets, etc.

Links