AnimationsTopNumbingly boring

Numbingly boring

We can see examples where we can get interesting behavior through repeating the same instructions without depending on changes in the mouse position to make things interesting. Consider the following program which draws a set of railroad tracks one tie at a time.

    object {
       inherits graphicApplication.size(400,400)
       ...    
       var tieXPosition:Number := firstTieX

       method onMousePress(pt: Point) -> Done {
          if (tieXPosition < canvas.width) then {
              def tie:Graphic2D = 
                  filledRect.at(tieXPosition @ tieTop) size (tieWidth,tieLength)on(self.canvas)
              tie.color:=tieColor
              tieXPosition := tieXPosition + tieWidth + tieSpacing
          }
          
          topRail.sendToFront
          bottomRail.sendToFront
       }
    }
    

It is painful to have to click repeatedly to get the ties drawn. Instead we would like the computer to continue drawing ties while they are still on the screen. Grace provides the while statement, or while loop, to perform repeated actions. Grace includes other looping constructs that we will see later in the semester.

The syntax of a while statement is:

    while {condition} do {
        ...
    }

The condition needs to be written surrounded by { and } because it will be evaluated many times rather than just when it is first encountered.

Now we can draw all of our railroad ties using a while loop, WhileRailroad drawing all of the ties at once.

We talked about while loops where more than one variable changes. The example involved drawing a laundry basket


AnimationsTopNumbingly boring