In Unit 3,
we developed a simple animation (Animate1) where a
black cell ‘moved’ across the middle row of a 5x3 board. We saw that even with such a small board,
our code was starting to look redundant as we repeatedly invoked the methods turnOn, pause, and turnOff in sequence
to create the desired effect. The only
thing that was different every time is the x coordinate
of the cell. If we want to program
this using a loop, we would simply need a variable that represents the
x-coordinate value that needs to change with every
iteration. Here’s the code for
a Board object with 30 columns. public class Animate2 { public static void main(String[] args) { // create a board with 30 columns, 3 rows Board b = new Board(30, 3); // start at x-coordinate 0 (or column 0) int x = 0; // while the last column hasn't been
reached while (x < 30) { // turn on the cell at column i, row 1 b.turnOn(x,
1); b.pause(500); // turn off cell b.turnOff(x,
1); // go to the next column x++; } } } |