Disturbance moves randomly around the window
CHAPTER 4. SUBROUTINES 153
Turning to the changeToRandomColor subroutine, we already have a method in the Mosaic class, Mosaic.setColor(), that can be used to change the color of a square. If we want a ran-dom color, we just have to choose random values for r, g, and b. According to the precondition of the Mosaic.setColor() subroutine, these random values must be integers in the range from 0 to 255. A formula for randomly selecting such an integer is “(int)(256*Math.random())”.
if (currentRow < 0) currentRow = 9; break;
case 1: // move right currentColumn++;// CurrentRow is outside the mosaic; // move it to the opposite edge.
/**
* This program opens a window full of randomly colored squares. A "disturbance" * moves randomly around in the window, randomly changing the color of each* square that it visits. */
*/
public static void main(String[] args) {
Mosaic.open(10,20,15,15);
fillWithRandomColors();
currentRow = 5; // start at center of window currentColumn = 10;
while (Mosaic.isOpen()) {
changeToRandomColor(currentRow, currentColumn); randomMove();
Mosaic.delay(20);
}
} // end main/**
* Fills the window with randomly colored squares.* Precondition: The specified rowNum and colNum are in the valid range * of row and column numbers.
* Postcondition: The square in the specified row and column has