Robots and lists

posted by: Ms. Martin 23 May 2010 No Comment

In the coming days, we will be coming back to lists to perform interesting data manipulation. To ease our way back, let’s do a few list exercises involving robots.

Activity 1: Home movie

Get your robot to film and display a “movie” by storing then showing a list of pictures.  I’ll have shown you the basic idea in lecture but it will be up to you to figure out appropriate timing to get about 10 seconds of video without blurring while your robot is moving.

Activity 2: Note list

You all wrote songs using a series of beeps.  Didn’t that look repetitive?  Create a list of beep frequencies then loop through that list to write a song more efficiently.

Notice that if you only have a list of frequencies, you’re somewhat limited because the length of each beep stays the same.  Write code to use two lists to define a song: one of frequencies and one of beep lengths.

Activity 3: Images as lists of pixels

It can be very useful to think of images as lists of pixels or picture elements, the tiny dots pictures are made of.  Given this view, we can loop over the pixels in an image and manipulate then in certain ways.

We can use two functions, getWidth(<picture>) and getHeight(<picture>) to know what loop bounds to use.  For example, the following code will loop through a picture the robot just took and make a horizontal line 20 pixels from the top of the image green-tinted:

for i in range(getWidth(pic)):
    pixel = getPixel(pic, i, 20)
    setGreen(pixel, 255)
    repaint()

Try it! Notice that the i variable gets values from 0 to the width of the whole picture. We fetch a particular pixel and tint it. In this case, we repaint the image as the line is being drawn. Modify the code to repaint the picture only after the line is drawn.

What if we wanted to tint the whole image?  We need to vary both the x and the y coordinates of the pixel we are fetching.  To do this, we’ll need to nest two for loops, one changing the x coordinate and another modifying the y:

for i in range(getWidth(pic)):
	for j in range(getHeight(pic)):
		pixel = getPixel(pic, i, j)
		setGreen(pixel, 255)
repaint()

In the example above, I repaint only after the whole image is tinted. Change the position of repaint() to change when the image is updated.

What is the 255 business?  Colors of pixels are represented as a combination of red, green and blue.  Each color can have a value between 0-255.  In this case, we are asking the computer to make each pixel in the image have as much green as possible.  Experiment with different values of green.

Can you tint the video you made in the first exercise?

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Loading ... Loading ...

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>