Priority Queues

Teaching Loops
Facilitated by introducing simple threads
• Few interesting loop examples before arrays
–
–
–
–
Boring calculations
Interaction
Drawing
Animation
• Bad idea to postpone loops until arrays
Simple While Loops
• Repetition in drawing
– Grass, bricks
– Laundry basket
grassX = 0;
while ( grassX < SCREEN_WIDTH ){
new Line(grassX, GR_BASE,
grassX, GR_TOP,
canvas).setColor(GRASSGREEN);
grassX = grassX + GR_SPACING;
}
Relate Loops to Familiar
Concepts
int grassX = 0;
public void onMousePress (Location pt){
if ( grassX < SCREEN_WIDTH ){
new Line(grassX, GR_BASE,
grassX, GR_TOP,
canvas).setColor(GRASSGREEN);
grassX = grassX + GR_SPACING;
}
}
More Simple While Loops
Animation
• Balls (leaves, snow) fall down
• Cars move left to right (or vice versa)
• Balls bounce
Exercise: other examples that don’t require
arrays?
Animations
• Natural way to introduce looping
• Interesting to students
• Requires introduction of threads
– Introduction of threads at this stage sounds
crazy!
– But a natural way to get sophisticated behaviors
with fairly simple programs.
Active Objects
• Students extend ActiveObject
• Syntax simplified
• ActiveObjects (Threads) registered for
appropriate clean-up.
ActiveObject
• Methods
– public void run() - overridden by students
– public void start() - called by students
– public void pause(double) - exceptionless
• “start()” at end of constructor
A Simple ActiveObject
public FallingBall(DrawingCanvas canvas) {
ball = new FilledOval(SCREENWIDTH/2 ,TOP,
BALLSIZE, BALLSIZE, canvas);
start();
}
public void run() {
while (ball.getY() < BOTTOM ) {
ball.move(0, Y_SPEED);
pause(DELAY_TIME);
}
ball.hide();
}
Interactions
Interactions between ActiveObjects and other
objects yield more interesting loop conditions.
• With single non-active object
• Between different active objects
– Active objects as generators of others
– More complex interactions
Interactions
• Pong
• Falling snow (or leaves)
• Hungry ball
Boxball: a Simple First Exercise
• Falling ball is familiar
• Interaction with a single non-active object
(the box)
• Opportunity for thinking about parameters
Frogger: a Second Exercise
Purpose of lab: to consider a variety of simple
interactions that appear quite sophisticated.
• Lanes create cars
• Cars know about frog
• Frog knows whether its dead or alive
• Most difficult component of the exercise is
management of parameters.
Additional topics
• Smooth animation
– Interesting
– Necessary for Frogger
• Visible Images
– Many more interesting examples
– Necessary for Frogger
– Good time with respect to our syllabus, but could be
done earlier
A Gentle Reminder
• Don’t compare threads to “the old way”
• Many simple but interesting examples… but
some simple examples aren’t so simple