Blog
Setting up folders and survey.
Ms. Martin : February 2, 2010 9:10 pm : 2009 Fall Creative Computing 1Once again, welcome to Creative Computing! I’m really looking forward to another fun semester learning Python with all of you.
First of all, spend a second to create a folder for this class in your My Documents folder. I’ll be coming by to make sure you’ve got that set up properly.
Then, spend some time answering this survey. The first part is just background that will help me get to know you better and hopefully serve you better as an instructor. The second part is to encourage you to get to know the website well.
Robot vision
Ms. Martin : January 10, 2010 6:50 pm : 2009 Fall Creative Computing 1Activity 1: horizontal line
Write a function that will make your robot take a picture and display it with a horizontal line drawn across it at a height of your choice. This should be very similar to the drawVerticalRedLine function described below.
Activity: Color follower
Write a program that will turn your robot towards objects of a particular color. If someone is wearing a bright colored shirt, for example, make your robot turn towards it. Another good option is to make your robot turn towards other robots by looking for blue objects.
The last section of this tutorial will be most helpful.
In order to complete this activities, you will need all or part of the following information. Read carefully!
Basic Components of an Image
You can think of an image or a picture as a rectangular object which has a specific size determined by its width and its height. Each picture is composed of tiny components called pixels. You can calculate the number of pixels in an image by using the following formula:
number of pixels in an image = width of image * height of image
Each pixel has a red, green and blue component (an RGB value). Each of these colors has a value that ranges from 0 to 255. For instance, a completely red pixel would be represented as (255,0,0), or full red, and zero green and zero blue components. Similarly, a green pixel would be represented as (0,255,0) and a blue pixel would be represented as (0,0,255). Other colors are made by mixing various values of red, green, and blue. For example, white is made by combining all of the colors (255,255,255), and black is made by an absence of any color (0,0,0). If you combine green and blue with no red (0,255,255) you would get a teal color, while a combination of red and green with no blue (255,255,0) would produce yellow. Also, each pixel has a specific (x,y) location in an image.
Taking Pictures
Recall that pictures are taken in the following way:
>>> pic = takePicture() >>> show(pic)
You can determine the size of the image by using the getWidth() and getHeight() functions.
Try the following:
picWidth = getWidth(pic) picHeight = getHeight(pic) print "The Picture is", picWidth , "pixels wide and", picHeight, "pixels high."
Drawing a Line
NOTE: If you would like to use a copy of the apple picture rather than using your own picture in the examples below, replace:
takePicture()
with:
makePicture("http://wiki.roboteducation.org/wiki/images/2/2b/Apple.jpg")
If you want to change a lot of pixels all at once, you can use a loop. For example, the following loop will change all pixels that have an X value of 10 and a Y value anywhere between 0 and 100 (but not including 100) to be red:
for yValue in range(0,100): aPixel = getPixel(newPic, 10, yValue) setRed(aPixel,255) setGreen(aPixel,0) setBlue(aPixel,0) show(newPic)
The result is a vertical red line (at X position 10). Note that this piece of code will only work correctly for pictures that are exactly 100 pixels high (because you loop from zero to 100). But you can generalize this code to work on pictures of any size by replacing the 100 with a function call that tells us the actual height of the picture as follows:
for yValue in range(0, getHeight(newPic) ): aPixel = getPixel(newPic, 10, yValue) setRed(aPixel,255) setGreen(aPixel,0) setBlue(aPixel,0)
Drawing a line could be a useful function to use later, so you should prepare to re-use the code above by putting it into a function. But since you don’t know the exact X position that the user will want to draw their line, you should make that into a parameter that the user can specify. Also, since you don’t know the name of the variable that will hold the picture, that should also be a parameter:
def drawVerticalRedLine( picture, xPos ):
for yPos in range(0, getHeight(picture) ):
aPixel = getPixel( picture, xPos, yPos)
setRed(aPixel,255)
setGreen(aPixel,0)
setBlue(aPixel,0)
Now you have a function that will draw a vertical red line on a picture of any height. Note that your function does NOT show the image, so a user would have to call our function, and then call the show() function to display the line on screen:
pic = takePicture() show(pic) wait(1) drawVerticalRedLine(pic, 25) show(pic)
Because the above code does not change the green or blue values of the pixels, the picture is still recognizable, but all pixels have a reddish tint.

Robot Vision
Operating on a single pixel in an image
Myro has a set of functions that allow you to get the individual red, green, and blue values from a pixel, as well as set the values to any number you want. But before you get or set the value of a pixel, you need to select a specific pixel to change.
The getPixel command returns the pixel at the specified x and y locations in the picture. setColor sets the given pixel’s color to any specified color. You can create a new color by specifying its RGB values in the command:
myRed = makeColor(255, 0, 0)
The following example picks the pixel at X location 10 and Y location 5 using the getPixel() function then sets its red value to full on (255) with the setRed() function.
onePixel = getPixel(newPic,10,5) print getRed(onePixel) #initial red value setRed(onePixel,255) print getRed(onePixel) #new red value show(newPic)
Operating on all pixels in an image
The getPixel() function returns a pixel at a specific location in the picture. However, sometimes you want to do something to all pixels in the picture. In such cases you can use the getPixels() method which returns a a list of all the pixels. You can use the getPixels() method in a for loop to perform an operation on all pixels in the image. For example, you can turn the red color of all pixels all the way on with the following code:
myPic = takePicture() show(myPic) for eachPixel in getPixels(myPic): setRed(eachPixel,255) show(myPic)
This should give your image a red tint.
Locate Bright Areas in an image
By making a decision about each pixel in an image, you can locate specific areas in an image. For example, by looking for pixels that have a large value, you can locate bright areas in the image. You can even modify the image to outline bright areas. For example:
myPicture = takePicture()
show(myPicture)
for pixel in getPixels(myPicture):
redValue = getRed(pixel)
greenValue = getGreen(pixel)
blueValue = getBlue(pixel)
averageValue = ( redValue + greenValue + blueValue) / 3.0
if averageValue > 175 :
#Turn the pixel white
setRed(pixel,255)
setGreen(pixel,255)
setBlue(pixel,255)
else:
#Otherwise, turn it black.
setRed(pixel,0)
setGreen(pixel,0)
setBlue(pixel,0)
show(myPicture)
Locate Red Areas in an image
By changing the conditional test, you can instead look for areas that have a large amount of the color red. Red areas are characterized by having large red values, but smaller blue and green values.
myPicture = takePicture()
show(myPicture)
for pixel in getPixels(myPicture):
redValue = getRed(pixel)
greenValue = getGreen(pixel)
blueValue = getBlue(pixel)
if redValue > 175 and greenValue < 175 and blueValue < 175 :
#Turn the pixel white
setRed(pixel,255)
setGreen(pixel,255)
setBlue(pixel,255)
else:
#Otherwise, turn it black.
setRed(pixel,0)
setGreen(pixel,0)
setBlue(pixel,0)
show(myPicture)
Pixels with red values larger than 175 highlighted in white.
Pixels with green values lower than 175 highlighted in white.
Pixels that have both red values larger than 175 and green and blue values lower than 175 highlighted in white.
Represent Red Areas in an image as White Areas
You can then define a function to find red pixels and return a black and white picture with white pixels representing “red” areas.
def findRedAreas(picture):
for pixel in getPixels(picture):
redValue = getRed(pixel)
greenValue = getGreen(pixel)
blueValue = getBlue(pixel)
if redValue > 175 and greenValue < 175 and blueValue < 175 :
#Turn the pixel white
setRed(pixel,255)
setGreen(pixel,255)
setBlue(pixel,255)
else:
#Otherwise, turn it black.
setRed(pixel,0)
setGreen(pixel,0)
setBlue(pixel,0)
return picture
The result of testing for “red areas” is an image where most of the apple has been detected, but a lot of other pixels scattered around the image are also somewhat “reddish”. If you want the robot to turn towards the direction with the most red pixels, you need to calculate the average X (horizontal) location of the pixels that have been marked (by turning them white).
Drawing a Line in the Red Area
If you examine every pixel in the image, and average the X coordinates of all the “detected” (or white) pixels, you can determine the middle of the red areas. To do this, you use two loops (one for the Y positions, and one for the X positions) to look at every pixel, and add up the X positions of all pixels that are turned “on” (or white). Because a white pixel has values of (255,255,255) and an “off” or black pixel has values of (0,0,0) you can take a shortcut and only test the value of one of the three colors.
def AverageXofWhitePixels(picture):
sumX = 0.0 # Use floating point values
counter = 0.0 # Use floating point values
for xPos in range(0, getWidth(picture) ):
for yPos in range(0, getHeight(picture) ):
pixel = getPixel(picture,xPos,yPos)
value = getGreen(pixel)
if value > 0 :
sumX = sumX + xPos
counter = counter + 1
averageX = sumX / counter
return int(averageX) #Return an Integer
Now, you can use the functions you have defined so far to locate the average X location of red pixels, and draw a line at that position:
myPicture = takePicture() picture = copyPicture(myPicture) picture = findRedAreas(picture) XposAvg = AverageXofWhitePixels(picture) drawVerticalRedLine(myPicture,XposAvg) show(myPicture)
Because of all the other “red” pixels detected that were not on the apple, the red line is not exactly centered on the apple, but it is close enough that you could use the value in the XposAvg variable to figure out which way to turn the robot to face the apple.
Robot activities
Ms. Martin : January 2, 2010 5:52 pm : 2009 Fall Creative Computing 1You are responsible for completing these activities in your group by Friday. If you are done early, GREAT! I want to see you continuing to work with the robots in cool ways. Can you use what you know about pygame to make a neat graphical program using the robot?
Activity 0: song
Write a song function as outlined in the tutorial.
Activity 1: go function
Write a function named go that takes distance as a parameter and makes the robot go that many inches. To do this, you will need to experiment with how much distance a robot covers over different amounts of time and write an equation to relate distance to time. To do this, you may want to get a marker and have your robot draw lines that you can then measure with a ruler.
The call go(6) should make your robot go 6 inches, the call go(0) shouldn’t do anything and a call on go(1.5) should make your robot go 1.5 inches. Try to be as precise as you can, but don’t worry too much about it. It’s going to be impossible to get it exactly right!
Activity 2: random movement
Write a function that makes your robot go forward a random number of inches between 1 and 6, then turns a random amount (range of your choice) and repeats. Your function should take one parameter: how long the robot should repeat this for. For example, the call rand_moves(10) should make your robot make random moves for 10 seconds. Similarly, a call on rand_moves(15) should make your robot move randomly for 15 seconds.
Activity 3: pictures
Write a function that will take a picture, show it, wait 3 seconds, go forward 1 second. Your function should take one parameter: the number of times to repeat this. For example, a call on pictures(10) should make your robot take a picture, display it, wait 3 seconds, go forward 1 second and repeat the whole thing 10 times.
Activity 4: random pictures
Write a function that will make your robot go forward and turn randomly and then take a picture. Once the picture is shown on the screen, the user should be asked whether the picture shows what they’re looking for. Your robot should repeat this behavior until the user says that yes, they saw what they were looking for. For example, if your robot is meant to be looking for a whiteboard eraser that’s a couple of feet away, you might have to say no to three or four pictures before the robot orients itself such that your camera takes a picture of the eraser.
Activity 5: creep bot!
Combine your knowledge of the joyStick() command with taking pictures to have your robot repeatedly take pictures as you drive it around. How well can you navigate without seeing your robot?
Activity 6: “Theremin”
You will write a program that beeps at different pitches based on the light sensor values. For example, I wrote one that just adds up the three sensor values and uses that as the beep frequency. I had mine loop for 20 seconds so that as I approach my hand to the robot, the pitch gets higher and higher. This behavior is roughly based off of an interesting instrument called the Theremin. Look it up!
Activity 7: Cockroach function
Your cockroach function will take one value as a parameter: the length of time the robot should move for. Your cockroach should flee light and go towards darker places. So, for example, if you start it near the edge of the shadow of a table, it should go under the table. There are a few ways to implement this, but here is a simple one:
- read all three light sensor values
- if the left light sensor gives a value less than both the middle and the right light sensor, move right (remember, a low value means a bright light)
- if the right light sensor gives a value less than both the middle and the left light sensor, move left
- otherwise, go forward
Activity 8: Obstacle avoidance
The following code is the start to an obstacle avoidance program. See if you can figure out what it does from reading it, then save it and run it.
while timeRemaining(30):
if getObstacle("right"):
backward(1, .1)
turnLeft(0.7, .1)
elif getObstacle("left"):
backward(1, .1)
turnRight(0.7, .1)
else:
forward(.5)
wait(.1)
stop()
Right now, it’s not so hot. What happens if you make your robot run this program while it’s directly facing a wall? It just crashes, right? That’s because we’re totally ignoring obstacles right in front of us! Add a case for when there’s something right in front. Your robot should go backwards then pick randomly with equal probability to either turn right or left.
Next, make your robot beep when it sees an obstacle. You should use three different pitches and tone lengths for the three different obstacle positions so you can hear what your robot is doing.
Finally, make your robot stop and take a picture whenever it runs into an obstacle.
Introduction to Scribblers
Ms. Martin : January 2, 2010 5:50 pm : 2009 Fall Creative Computing 1Robots are one of those things we all think we know something about but that are surprisingly difficult to define. Broadly, a robot is a program that runs automatically without a human needing to interfere. Robots have logic of varying complexity that allow it to react to different situations on its own. Given this definition, a robot doesn’t technically need to be a physical machine like the Wall-Es and Transformers found in movies. One type of robot all of us depend on without necessarily realizing it is a webcrawler which indexes web content automatically to make search engines like Google possible.
For the next few days, we’ll be learning to program the Scribbler robots. These are simple little “tank” robots that have a number of sensors including a color camera, infrared sensors and light sensors. Our computers will connect to them using bluetooth which is short-range and reasonably fast.
I HIGHLY ENCOURAGE YOU TO CHECK OUT SAMPLE PROGRAMS!

In order to start using your robot, you have to make sure that your bluetooth dongle is connected to the computer with the matching number in the upper right corner of the screen. You also need to make sure the numbers on the robot, green board and dongle match.
Once you are sure all numbers match, you will need to click on the desktop icon that says ‘Python for ROBOTS.’
Once IDLE loads up, type in these commands:
from myro import *
init("com3") # or whatever com port your bot has
Unfortunately, the com port seems to change all the darn time. In order to find it for your particular connection, you will need to right-click on the bluetooth icon in the system tray then select ‘Add bluetooth device.’ Find the serial number of your robot, click next, then you should use whatever outgoing com port is displayed in your call on the init function.
Your screen should look like the following:
You should get a popup asking you to accept the bluetooth communication. Click on it:
You should then be asked for a bluetooth passkey. Type in 1234 as follows:
To personalize your robot, you can give it a name. For example, to name a robot “Terminator”
>>> setName(”Terminator”)
You are now ready to send commands to your robot! For today, I want us to make sure there are no technical hurdles and then experiment with some of the basic commands. To start, try typing in joyStick() and use the mouse to direct your robot around the room. How far can it get before it is out of range? Make sure you’re doing this on the floor so your bot doesn’t fall off the table!!
Your robot can produce songs! This is going to get pretty annoying, but it’s in the name of learning, right? Each group is going to write a robot song. The basic idea is that you will be using a beep command. Try this:
>>> beep(1, 440)
You should have heard a tone play for 1 second at 440Hz. Hz? Hertz is a mesure of frequency. beep is a function that creates waves at specified frequencies. It turns out that 440 is the frequency of an A. Try creating a beep at a higher frequency:
>>> beep(1, 800)
It sounds higher-pitched, right? The human ear can hear roughly between 20 Hz – 20 kHz. Can you hear a beep(1, 20000)? What about beep(1, 20)?
In order to create your song, you will create a function. For example, I will call mine mySong. Here is what my code looks like:
I encourage you to download robotsong.py (just click on the link at left or on the calendar) and play it yourself. To play the song, go to ‘Run Module’ as follows:
When you are ready to write your own robot song, go to ‘File > New Window’ and get a new program file. Save it using a descriptive name of your choice and make sure it has .py at the end!
Once you’ve written your song, explore the following functions and complete the questions at the end. Keep in mind that all the Python you already know still applies!
Movement
joyStick()
Pops up a window that allows you to move the robot using a mouse-driven joystick.
backward(SPEED, SECONDS)
Move backwards at SPEED (value in the range -1.0…1.0) for a time given in SECONDS, then stop.
forward(SPEED, TIME)
Move forward at SPEED (value in the range -1.0…1.0) for a time given in seconds, then stop.
stop()
Stops the robot.
turnLeft(SPEED, SECONDS)
Turn left at SPEED (value in the range -1.0..1.0) for a time given in seconds, then stops.
turnRight(SPEED, SECONDS)
Turn right at SPEED (value in the range -1.0..1.0) for a time given in seconds, then stops.
wait(TIME)
Pause for the given amount of TIME seconds. TIME can be a decimal number.
Pictures
pic = takePicture() show(pic)
The first line commands the robot to take a picture and save it in a variable called pic. The second line displays this picture on the screen.
grayPic = takePicture("gray")
show(grayPic)
This example is very similar to the previous but the picture is black and white. Taking a black and white picture is less time-demanding.
Sensors
Your robot has sensors that senses different aspects of its environment. The image below shows two types of sensors that your robot has – proximity and light sensors. Notice that they’re on the opposite side of the robot as the camera so you will have to drive backward to use them!

The following is a list of external stimuli that the robot can sense and a description of how the robot senses them.
- Light: There are three light sensors on your robot. These are located in the three holes on the front of your robot. These sensors can detect the levels of brightness (or darkness). Your robot can use these sensors to detect variations in ambient light in a room.
- Proximity: At the front of the robot you will see two tiny lamps on each side of the robot. These are IR emitters. If the light that is emitted by these sensors get reflected by the presence of an obstacle, then the light will bounce back towards the robot and is captured by the IR sensor that is present in the tiny notch in the middle of the two IR emmiters (see figure above).
- Line: If you look at the front portion of the Scribbler’s chassis (away from the third wheel), you will notice two pairs of tiny holes. These are also IR emitters and receivers and can be used to detect lines on the floor. THIS SENSOR IS REALLY FLAKY! USE AT YOUR OWN RISK.
Once you are familiar with your robot’s sensors, you can use them to create interesting creature-like behaviors for your Scribbler.
Enter the following command in the Python Shell:
>>> senses()
Scribbler Sensor Values:
- Light: The values being reported by the three light sensors are: 135 (left), 3716 (center), and 75 (right). In general, the lower the values, the brighter the light being sensed. This snapshot was taken when the center light sensor was covered by a finger.
- Line: In the presence of a line under the Scribbler (the line has to be aligned with the length of the robot) the Scribbler can detect a bright edge against a dark edge (that forms a line). The display shows the values of left and right sensors (both are 1). If the right sensor is on a dark area of an edge or a line and the left sensor is on a lighter area or edge, the sensor values would be (left=0, right=1). If the edge is reversed, the values would be (left=1, right=0).
- IR: The IR values displayed are also left and right (in the same orientation as the light). Their values will be either 1 or 0. If there is an obstacle detected, the value will be 0. It is 1 otherwise.
Unfortunately, some of the sensors are pretty flaky. Try to get the line sensor to get different values for left and right, for example. It doesn’t really happen, so it’s not very useful!
Obtaining Sensory Information
In addition to using the senses operation, you can use various functions in the Myro library to obtain these sensor values. You can use these functions as tests for loops or conditionals to make your robot react to its environment.
Light Sensors
- getLight(<POSITION>): This returns the current value in the <POSITION> light sensor. Your Scribbler has three light sensors (see picture above). <POSITION> can either be ‘left’, ‘center’, ‘right’ or one of the numbers 0, 1, 2. The positions 0, 1, and 2 correspond to the left, center, and right sensors. For example, keep your robot in the same position and try the following:
>>> getLight('left')
>>> getLight(0)
>>> getLight('center')
>>> getLight(1)
>>> getLight('right')
>>> getLight(2)
Proximity Sensors
- getIR(<POSITION>): This returns the values of the IR sensors. <POSITION> can be 0 or ‘left’ and 1 or ‘right’. Try the following:
>>> getIR('left')
>>> getIR('right')
>>> getIR(0)
>>> getIR(1)
Obstacle Sensor


The Fluke dongle has an additional set of obstacle sensors on it. These are also IR sensors but behave very differently in terms of the kinds of values they report. The following functions are available to obtain values of the obstacle IR sensors:
- getObstacle() Returns a list containing the two values of all IR sensors
- getObstacle(<POSITION>) Returns the current value in the <POSITION> IR sensor. <POSITION> can either be one of ‘left’, ‘center’, or ‘right’ or one of the
numbers 0, 1, or 2. The positions 0, 1, and 2 correspond to the left, center, and
right sensors. Try the following:>>> getObstacle() >>> getObstacle('center') >>> getObstacle(1) >>> getObstacle('right') >>> getObstacle(2) >>> getObstacle('left') >>> getObstacle(0)
Repetition
You can use any of the loop techniques we’ve discussed so far. Using them with sensor values is particularly powerful. For example, you may want your robot to keep going forward while the light sensor gives values below a particular threshhold.
One very useful Scribbler-specific way of looping allows your robot to do things for a certain amount of time. To do so, you’ll want to use the Scribbler timeRemaining(SECONDS) function. For example:
# make the 'bot print a message and go forward for 10 seconds. while(timeRemaining(10)): print "Gogogo!" forward(1) # this makes your 'bot go forward at full speed forever! Until the stop() command is called. stop()
On to ACTIVITIES!
PyGame tutorial
Ms. Martin : December 14, 2009 9:23 pm : 2009 Fall Creative Computing 1PyGame is a series of Python modules specially designed to make game creation a breeze. We’re only going to skim the surface in the next couple of weeks but I hope you will be encouraged to do some exploration on your own! Read more about the package on its website.
We’ll start today by going through a line-by-line tutorial. Do your best to understand what is going on and experiment as much as possible. As you go through, think about how this compares to Turtle Graphics. What is easier? Harder? More elegant? Similar?
A lot of this is “stolen” from http://rene.f0o.com/mywiki/LectureThree – thanks!!
Import Modules
The first thing you’ll need to do is bring all the pygame code into your program by importing the appropriate modules. Recall, modules are a grouping of code, or a library.
For the rest of the tutorial, I’ll assume you’re working at the prompt, but feel free to open a new program and work in there instead. You will need the following lines whenever you want to use pygame:
>>> import pygame, sys,os >>> from pygame.locals import *
You can look up the documentation for these modules: pygame, os, sys.
You may also want to try using dir() and help() functions on those modules to learn more.
>>> dir(pygame) >>> help(pygame)
Initializing pygame
Next we initialize all imported pygame modules. This is done with the pygame.init() function.
>>> pygame.init() (6,0)
We’ve now initialized the video, the sound, and a number of other pygame modules. If you type it into the interpreter you’ll see that 6 modules have initialized correctly, and none have failed.
Setting up the screen
We need to create a window by giving it a width and height. For example, I’ll create a wide, short window of 500 pixels in width and 100 in height.
window = pygame.display.set_mode((500, 100))
Check out the documentation for pygame.display.set_mode.
Now we set a caption on the window. The caption is the text in the middle of the window bar. Set the text to what ever you like!
pygame.display.set_caption('Go Bulldogs!!")
Check out the documentation for pygame.display.set_caption.
Finally we get the display surface representing a screen.
screen = pygame.display.get_surface()
A surface represents either the screen or an area in memory where images are held.
Check out the documentation for pygame.Surface.
Loading an image
Loading an image in pygame is much easier and awesome than in Turtle Graphics. First of all, pygame supports many formats including jpg, png, bmp…
Find an image of your choice and load it:
>>> bulldog_pic = "bulldog.jpg" >>> bulldog_surface = pygame.image.load(bulldog_pic)
Have a look at the documentation for the pygame.image.load function.
Drawing the image onto the screen.
screen.blit(monkey_surface, (0,0))
What we are doing on this line is drawing the image, which in this case is contained in the bulldog_surface variable, onto the screen. blit is just another word for draw.
The second argument to the function is telling blit to draw the monkey at coordinates (0,0). The top left of the screen.
Pygame uses a coordinate system for the screen where x= 0, y=0 is the top left of the screen. (0,20) is twenty pixels below the top of the screen. Careful — this is not the same as Turtle Graphics!!
Fliping the display
pygame.display.flip()
Here is where we flip the display surface. This updates the whole screen.
There are more complicated things which you can do with updating the display, which you will discover soon. If you want to learn more about updating the display you can find out here – http://pygame.org/docs/ref/pygame_display.html#flip
Why do you have to flip the display? To see your graphics drawn. Flipping the display is your way of telling pygame that you have finished making changes for that frame, now please show the changes.
For now just be content that you should flip the display after having drawn to it.
Adding a way to quit.
def input(events):
for event in events:
if event.type == QUIT:
sys.exit(0)
else:
print event
We are defining a function with this code. This function does two things:
- looks for a quit event.
- prints other events.
An event is:
- Something that takes place; an occurrence.
- A significant occurrence or happening.
Our games may be told that the mouse has moved, that certain keys have been pressed or the joystick has been moved.
These are the types of events that happen within our program.
The input() function above loops over the input sequence events, and does a test on each event.
Once a quit event happens the program exits. A quit event can happen by clicking on the close window, or pressing ALT+F4.
If it is not a quit event it prints the event to the console(command line window).
The main loop
while True: input(pygame.event.get())
Here we have an infinite loop. While True is true it will keep looping. As true is going to stay true for a long time, it will keep going on(probably until the program exits).
pygame.event.get is used to see what is happening in the program. It returns a list of events. We pass this list to the input function we defined above.
All the code together.
Once you’ve successfully put the program together, run it, and see all the events fly by on the console! Try pressing a few keys. You will notice the events being printed out to the console. If you press a mouse button you will get events for that.
Read the pygame docs for events — http://pygame.org/docs/ref/event.html
Things to try at this point
- Place your image in a different location.
- Load two images.
- See if you can figure out how to make your program quit when the user presses any keyboard key. You’ll need to look at the events documentation.
Adding music
my_music = "crazybeats.wav" sound = pygame.mixer.Sound(my_music) sound.play()
Sounds are loaded by creating pygame.mixer.Sound objects. One of the Sound objects’ methods is play(). Unfortunately, pygame is limited to OGG and WAV files.
What if you wanted to make your sond play every time the user clicked the mouse? Add a condition to your event testing as follows. This code should go after the if statement that allows the user to quit.
elif event.type == MOUSEBUTTONDOWN: sound.play()
Drawing text
Drawing text is pretty involved in pygame! I’ll explain it line by line. Try typing these in somewhere in your program (probably after drawing your image(s)) to see how it works.
font = pygame.font.Font(None, 36)
Load a particular font in a set size. Usually, using the default font by passing in None will be good enough.
text = font.render("YEAH AWESOME!", 1, (0, 0, 255))
To actually create the text, pass it in along with a one and a color. The color is three values for red, green and blue between 0 and 255.
textpos = text.get_rect()
We need to get the rectangle the text will occupy in order to position it.
textpos.centerx = screen.get_rect().centerx
You can center the text on the window by setting the text’s center to be equal to the screen’s center.
background.blit(text, textpos)
Finally, you’re ready to draw the text!
Play around for now — more next time!!
Object-oriented work
Ms. Martin : December 13, 2009 9:15 pm : 2009 Fall Creative Computing 1You should be ready to turn in three examples of object-oriented work by Wednesday.
1. Animal Class
Your animal must have at least three methods and three pieces of state. You must have written client code that creates objects of your animal type and tests what they can do. You will turn in both the class and your client.
2. Pyramid Seeker
See the creating turtle objects handout for requirements.
3. Turtle Inheritance
For this, you should demonstrate an understanding of creating classes that inherit behavior from Turtles. You have three options, ordered by complexity and interestingness.
Option 1: some kind of critter on the screen
Create some sort of interactive class whose objects add interesting behavior or visuals to turtles. See my frog example for the bare minimum. Ideas include creating a button class that can be placed in different locations when created or creating a zoo of multiple animal types that can interact with each other.
Option 2: the coin collector
The coin collector is a type of turtle that roams around randomly “eating” coins and getting points for each one it gets. Starter code found here sets up all the coins. You may either create a new type of CoinCollectors that have state for coins collected and other specialized behavior or work with plain turtles. Your creature should roam collecting coins and getting bigger with each one until it exits the coin grid. Then, it should stop and print how many points it got (one per coin).
Option 3: etch-a-sketch
Create an etch a sketch program. You should create a new type called something like EtchCursor that represents a hidden turtle controlled by keyboard arrow keys. For extra awesomeness, clicking somewhere (either on a button you draw or just on the screen) should refresh the drawing.
Dictionaries and tuples
Ms. Martin : November 18, 2009 4:58 pm : 2009 Fall Creative Computing 1A few of you have been attempting the Star Map program. It’s challenging, interesting and hopefully really rewarding so I strongly encourage you to do so, even if you’re not sure to finish! My initial intent was that you would learn to use dictionaries and tuples by looking at online reference. That turns out to be more challenging and less fun than I thought it would be, so here is some reference I think you might find useful.
Dictionaries
Dictionaries are used to map values called keys to data or values. In a “real world” dictionary, the words are keys and the values are the definitions. Dictionaries are a lot like lists but can use arbitrary values as indexes rather than being limited to integers. Here’s how you could visualize a dictionary that maps people’s names to their favorite foods:
---------------------------------------- |"Anna" | "Joe" | "Lisa" | "Bart" | ---------------------------------------- |"Pasta" | "Candy" | "Nuts" | "Pears"| ----------------------------------------
This is very similar to how we would visualize a list, but the indexes are “Anna”, “Joe”, “Lisa” and “Bart” instead of being 0, 1, 2, 3.
Here’s a shorthand way of building this dictionary:
>>> foods = {"Anna":"Pasta", "Joe":"Candy", "Lisa":"Nuts", "Bart":"Pears"}
>>> type(foods)
>>> <type 'dict'>
Try it at the console. You need a series of key-value pairs separated by commas. You can use any type for key and value. For example, you could map a name to a list of foods they like or names to phone numbers.
In order to find out what Anna likes, you can use the following command:
>>> foods["Anna"]
See how that’s just like indexing into a list, but using a str index instead of an int?
What if you want to print what each person likes without the name? You can loop over all the keys and use them to index into the dictionary as follows:
>>> for name in foods: # for each person in the dictionary
>>> print foods[name] # prints a favorite food without the name
You can check to see if some value is a key in a given dictionary using the in keyword:
>>> if "Helene" in foods:
>>> print "The teacher's favorite food is: ", foods["Helene"]
>>> else:
>>> print "No clue what the teacher likes"
No clue what the teacher likes
Exercises
1. Write a function that reads the words in a file and stores them as keys in a dictionary. It doesn’t matter what the values are. Then you can use the in operator as a fast way to check whether a string is in the dictionary.
2. Write a function named get_letter_inventory which, given a string, returns a dictionary of letter frequencies.
Here’s how it works:
>>> h = get_letter_inventory('brontosaurus')
>>> print h
{'a': 1, 'b': 1, 'o': 2, 'n': 1, 's': 2, 'r': 2, 'u': 2, 't': 1}
Tuples
Tuples are also related to lists but like strings, they are immutable (cannot be changed). Tuples are commonly surrounded in parentheses when created (this isn’t strictly necessary, but it makes things clearer).
>>> coords = (500, 200)
>>> type(coords)
<type 'tuple'>
Elements of tuples are accessed just like list elements using their 0-based index values:
>>> coords[0]
500
>>> coords[1]
200
Baby Names
Ms. Martin : November 7, 2009 10:40 am : 2009 Fall Creative Computing 1On Thursday, you started work on a project to graph baby name popularity based on Social Security Administration data. This is a challenging project combining all you’ve learned — file reading, loops, functions, variables, type, user input… wow! I know it’s hard but hopefully you’re seeing how all the pieces work together and feeling satisfaction at how far we’ve come along. Being able to read in and process external data sources is both highly creative and extremely useful. I hope you’re thinking about some of the possibilities that would be relevant to you and that you might be interested in pursuing for an open-ended project.
When I returned from the (interesting and eye-opening conference) I attended, the first thing I did was go straight to your progress reports. It’s nerve-wracking to be out, especially for our first big program, but I was really pleased by what I read from you guys. It sounds like the difficulty level is right and that you’re making a lot of progress. Don’t worry, I want this to be a good experience for everyone, so we’ll have more time on it. I’m excited to be back and to see all that you have done!
Creative Computing Quiz
Ms. Martin : October 25, 2009 11:34 am : 2009 Fall Creative Computing 1Quizzes looked good overall. You guys have demonstrated good understanding of basic Python constructs and I’m excited to be moving on to more advanced topics! I loved the extra credit poems — they really make grading easier. Here were some of my favorites:
Too much programming
Not seen daylight for ten days
May be addicted
Programming is like poker
when I see syntax error I fold
I add zeros to my check
like binary code
Typing in the text,
switches flip, the machine hums,
and look at what you’ve made!
Programming is fun.
Now I don’t feel like a bum.
Computing is fun.
Just need seven syllables
Just finished my test
Creative computing, programming and learning
Way too much to remember in all of one week!
Conditionals, loops and variables
All about syntax and programmables!
Python oh Python
You’re full of tedious calls
while here and print there
At first, Creative Computing wasn’t a class I wish I had,
but after 5 weeks I’ve learned that it’s not that bad
Programing is hard but fun
I’m so glad this quiz is done
Making shapes is so cool,
Especially when you can make a jewel!
Writing lots of code
Learning new applications
Programming is fun
Human Computer Interaction
Ms. Martin : October 15, 2009 8:03 pm : 2009 AP CS A, 2009 Fall Creative Computing 1Programming may be the best way to learn computational thinking and gain skills transferable to many domains but the kind of programming we have been doing doesn’t capture the full breadth and excitement of computer science. We spent the day talking about a hot area of research and development: human-computer interaction. The goal was to expose you to some of the different kinds of challenges that software designers face and get you thinking about less well-known career opportunities. We saw that interface designers need a broad range of skills and so come from fields as different as graphic design, psychology or informatics. If you enjoy thinking about technology but aren’t sure programming is for you, you may want to look into becoming a usability expert.
We talked about some of the theory behind interface design and usability and looked at various examples of bad interfaces. Paper prototyping is often used to cheaply lay out different options for an interface. Since it is one of the most important stages in the design process, we did a couple of paper prototyping exercises. I encourage you to look at the software and hardware you use on a daily basis through the eyes of a designer: what decisions were made? Why? What could have been designed differently?








