Check this page regularly for notes from classes in both sections. These will include code examples and slides, where presented.
Introduction (see Chapters 1-2)
An algorithm for making an omelette written in a programming style. Note the use of colons and indentation to indicate the algorithm's structure, where steps get repeated, etc.
First three-line function to pick a picture file and show it: pickAndShow
Some simple program fragments to illustrate programming, variable names, comments, etc. (Fill in the gaps during lecture)
Pictures
Some Powerpoint slides (in PDF format, 4 slides per page) about encoding of pictures and colors: PicturesAndColors.pdf (see Chapter 3.1)
Three functions to demonstrate whole-picture manipulations: (1) a code template for ANY picture manipulation in which you want to do exactly the same thing to every pixel in the picture; (2) the template filled in with a block of code that makes every pixel darker; (3) the template filled in with a block of code that makes every pixel negative.
Colin's class: Friday, Jan 18: How to transform a picture by doing exactly the same thing to every pixel in it. Different transformations include making the picture darker, making it negative, two varieties of grayscale (a boring average and a "snappier" version that simulates an old-fashioned orange contrast filter for you black-and-white film photographers out there), posterizing (but not the homework!).
Monica's class. Friday Jan 18: Trippy visit to the 70s with posterize.txt (see it) posterize.py (or download it) (Shows the driver I was using to help run posterize more easily.)
Wild color transformations. Psychedelia!! (Colin's class, of course)
Try out the Blast function which is a blast because it blasts the pixel values. Go into the Edit/Options menu and compare the effects of running this function with the "...Modulo 256" option checked and unchecked. We will discuss what this means and why it has the effect it does in class.
A different type of transformation:
Making a copy of a picture (This isn't really a "transformation", but we will use this when we do things like tiling, reflection, enlargements and reductions, which are).
How to copy a picture explained in stages: (1) Cloning the entire picture using a getPixels() loop; (2) Partial clone that copies only the left-hand column of pixels (not shown in class); (3) Partial clone that copies only the middle column of pixels; (4) Partial clone that copies the four leftmost columns of pixels (easier to see than just one column, but very repetitive and boring and obviously impractical when you want to copy all the columns and don't know in advance how many there are), and (4) FINALLY, cloning the entire picture using nested row and column loops. The final version is similay to the Making a copy of a picture shown earlier.
Flipping and rotating images: mirrorLR copies the left-hand side onto the RHS in reverse. flipLR is a full left-right reflection. upside-down is what it says: a top-bottom reflection. rot180 turns the image upside down by rotating through 180 degrees. It does this by doing two reflections.
Monica's class week 3. range function to generate sequences and processing a rectangular area of an image. Fixing red eye, mirroring, even repairing the ruined temple roof. 09PixelsByIndexNumber.ppt and 11MorePixelsByIndexNumber.ppt
Here's the purple rinse and hair transplant code you cruelly made me do in class.... including the five-minute fix that makes it really work. And here is the resulting picture:
Simulating pool table by bouncing ball off all sides of picture.
Simulating sunset by making a landscape photograph redder by a small amount on each successive frame. (Try this using the beach-smaller.jpg image in the mediasources, but allow 20-30 minutes, because this takes a long time to run).
Beam Me Up, Scotty: Bobby's chromakey code used to make a movie that gradually materializes the chromakeyed character onto the background. Great for tacky StarTrek special effects. (After class, I made a correction and added a commented-out line to make foreground character dematerialize. There is a second way that we can make the bg person dematerialize: just run the materialization code as before, but write the frames out in reverse order, so that the first frame is written to the last-numbered file. That way, MovieMaker assembles the movie in reverse order. See if you can work out how to do this.) Edit: I noticed a slight bug in the original version and it has been corrected - Nick
John Cleese silly walk movie. Here is the code that I started to illustrate in class in which Cleese does a Silly Walk and Gets Crushed by a Falling Weight. The weight drops only when it is time for it to fall, and that means that the frame number has reached the value dropTime (which is 90, by the way).
You can find the john_cleese_N.png sprites in the downloadable sprite library (see homework #3 requirements for link). I found the 100kg weight by using google Images and searching for "16 ton weight". One of the images (from the University of Dundee in Scotland) was just what I needed. It took me 30 seconds. You can find it too.
There is another way to do this, which might make more sense in your homework, if you have a number of changes of direction or motion to program. This second strategy has two frame generation loops, not one. If you think like a director, rather than a programmer, these correspond to "scenes" of the movie. In the first scene (the loop that generates frames 0 to 89), Cleese is doing his silly walk. In the second scene (a loop that generates frames 90 to 99), he is doing his silly walk AND the weight is falling. Work out how you would do that, and I'll show it in class on Friday.
Digressions on Design, Coding and Debugging Skills
For excellent examples of detective work and diagnosis skills in action, you can download free copies of NPR's Car Talk shows from http://cartalk.com/ or from the Podcast area of the iTunes store. Or you can listen live on WABE (90.1 FM) Saturdays, 10-11 am.
It's important not just to be able to write functions but also to understand how invoking (calling, executing) a function with arguments (inputs) is related to a function's definition and its parameters (its inputs). It's also important to understand the difference between functions like a sausage maker, which transform their inputs (e.g. pigs) destructively and true mathematical functions like tangent(angle) which have (or give back) values but don't change their inputs.
All is explained in these slides on functions: functionsPosted.pdf (Sorry! These were initially placed right at the bottom of this page, not here.)
And here is the software for the wedding android that we used to marry Brad and Angelina and Charles and Camilla. (Try it out with Homer and Marge or any other matches you want to make.)
Sound
Some slides on the fundamentals of sound and digitized sound in JES: sound1.pdf
Sound manipulations
More advanced slides on procedures for making sounds louder and quieter, normalizing sounds, splicing them, making echoes, changing frequencies, etc. sound2.pdf
addInto adds one sound into a second, changing the second sound as a result
blendCopy returns a third sound which is a blending of the two sounds passed in as arguments
echo copies a sound onto itself after a delay, returning the sound with echo and leaving the sound passed in unchanged. (Bug fix and more comments added on Tuesday.)
Function that (nearly) creates a musical scale (slightly revised, Tuesday, to correct misleading comment.) To make this work, you need the directory/folder that contains all the notes of a scale played on a string (e.g. string-a4.wav). You would need to create a double-frequency version of the first note (the tonic?!) to add to the end and round off the scale, and we will discuss changes to frequency on Wednesday/Friday.
Sustain, a function that takes a sound (preferably one of the string sounds with a pronounced "attack") and splices in a long sustain. The second argument is the length of the attack phase (i.e. the sample number at which the sustain starts), and the third argument is the length of the sustain in samples. The bigger the sustainLength, the more likely you will be able to go and get a bite while it plays.
Changing the frequency of a sound (also contained in the second set of slides above): doubleFrequency transposes up one octave; halveFrequency transposes down one octave. Both these functions make the destination sound exactly the same duration as the source by starting with the same audio file. See if you can do something similar by passing in a sound rather than a file name.
Illustrative web page, showing table, pictures, embedded lists, and links: cartoons.html. Use your browser's "view source" menu item to figure out how the HTML is composed.
Update on the CODE tag. <code> only works for single lines in raw HTML. (The Coweb will format more than one line using this tag.) To show indented code (e.g. Python) on a page, use the <pre> tag (stands for "pre-formatted") instead.
Colin is webmaster for the GA Chess Association's website, so we may use that to illustrate HTML concepts: http://www.georgiachess.org/mainframe.html. Check out its HTML by visiting the site and using the "view source" menu item on your browser of choice.
CSS is the language for designing style sheets, and is far superior to controlling layout and appearance directly in HTML. We aren't covering CSS in this course, but it's important to know that it exists and what it is for. If you are interested in looking at examples of CSS style sheets, or just want to be wowed by the variety of looks that CSS can provide to an identical raw HTML page, visit the CSS Zen Garden site, http://www.csszengarden.com/
Modules, text and list processing
Modules, the reserved word import, and dot notation.
Here is a link to an index of Python standard modules: http://docs.python.org/modindex.html If you click on the links math, random, and time, you can find out what else is in these modules. There is also a module called string that we may use. Be brave and explore!
Text strings, indexing and slices
Here are three date manipulation functions day, month and year that use time.ctime and slices
Writing programs that generate and process HTML (slides in PDF):html2.pdf
A program that generates the simplest possible (and unchanging) web page: page.py
Here is another version, homePage.py of that that (1) generates Brad Pitt's web page, (2) generates any person's web page as long as you supply the person's name, their interests, and the filename or address of their picture.
Homework :) Try the above with a person other than Brad Pitt (maybe even yourself!)
Here is a bit of drill practice to double-check your understanding of indexing, slicing, etc with strings and sequences. stringsAndSequences.txt
Turtles
Basic turtle commands
The best advice when you are programming turtles (or doing any object-oriented programming) is to ignore the computer and tell yourself that you are communicating directly with the turtle. Imagine that you are the turtle and you are following instructions.
Here are some mystery turtle functions (a.k.a. pop quiz) and a test program that runs them one after another. If you got any of these wrong, trace out the turtle paths. The final position and orientation of the turtle is just as important as the shape that it draws.
Turtle methods
There are more turtle methods available in Jython/JES than are documented in the JES function menu. Here is a more complete list of methods with brief explanations if the purpose is not obvious. Experiment with these.
Turtle choreography
You can put several turtles to work simultaneously and move them in a coordinated fashion: dancers, predator/prey, batter/baseball, etc.
First, the simple square-dancing turtles. Here dexter and elliott draw complementary squares. In choreography1(), first one draws a square, then the other does. In choreography2() they move together. This is accomplished by interleaving the parts of the square - having dexter then elliott move forward and then having them turn in opposite directions, repeating this pair of operations four times. Instead of using forward(dist), we use myForward(dist) which does a forward(1) dist times with a short delay to give the impression of smooth animation.
Here is a predator/prey simulation. It's quite complicated in details but simple in principle and is worth studying.
Computer science topics
Object-oriented programming (class and method definition)
Simple illustration of animals. Dogs, cats and alligators are all kinds of animal. In this program, at least, reptiles are not animals, and pythons and dinosaurs are animals, but alligators are not. Can you make this program more biologically correct by changing the subclass definitions?
More complex illustration of OOP using dogs. This time, the methods include constructors (the mysteriously named __init__(self) method).
Turtles are naturally object-oriented, and you can make special types of turtles that can execute unique methods. Here is a pond of noisy frogs, which are just turtles that croak occasionally.
Recursion
The Factorial (n!) function can be written using a for loop or recursively. The factorial(n) function in this example has a loop, and the fact(n) function is recursive.
cCurve a famous example of letter C containing smaller C's. Try cCurve(10, 10). (It's drawn on its side, so the C is facing downward.)
tree draws a symmetrical tree as follows: draw a trunk, then draw a smaller subtree to the left and a smaller subtree to the right. You can add randomness to the tree drawing, and it starts to look like a natural growth process (blood vessels? trees? river deltas?)
Speed and programming languages
One factor that affects speed of execution is the algorithm that you're using. Here are two functions for finding a needle (a number) in a haystack (a list). Try these by creating a long list of numbers, such as range(0, 10000, 2) (i.e. 5,000 odd numbers) and trying to find small, medium and large odd and even numbers in the list. The binarySearch function is much more efficient than the simpler linearSearch function, and as the list gets longer, the difference in efficiency grows.
Slides on factors that affect speed (algorithms, languages and hardware): speed-posted.pdf
The Javascript functions that we used in class: javascriptExamples.txt. (The final one that brings up the popup dialogs was not enclosed in script tags (Duh) which was why it did not originally work. - This deliberate error on my part ;) illustrates the need for good error messages when we test programs, something that browsers that execute Javascript generally don't provide.) Insert the Javascript examples from this text file in the head of any web page, and invoke them in the body of the page as shown in the slides and in class.