img
.
After the pattern has been displayed, the player must now take the mouse and duplicate the
sequence. If the game flashed blue, green, red, green, the player must mouse blue, green, red,
green. Pretty simple.
The question comes up: How can we arrange for the flashing colors to be displayed to the player?
If we ran this game entirely in the main applet thread, it wouldn't work. All painting happens in
the main applet thread, so if you made a box bright blue, you could then request a repaint, but that
repaint would not occur until your function returned. If you tried to have your function sleep, the
repainting would have to wait.
So running the snippet of code shown in Code Example 17-2 in the main applet thread would
brighten a box, request a repaint, sleep, then dim the box, etc. After you were all done with this,
your method would return and then the repaints would happen all at once. Not very useful.
Example 17-2 How to Display Something for a Short Time
private void reset() {
for (int i = 0; i < patternLength; i++) {
// Select random cell
int randomX = (int)((Math.random() * 10) % numCellsOnSide);
pattern[i] = Cell.cells[randomX];
// Display the pattern square by redrawing it briefly in a
// brighter version of its current color.
chosenCell = Cell.cells[randomX];
chosenCell.brighten();
repaint();
// Sleep so the user can see the bright color before we
// darken it again.
InterruptibleThread.sleep(sleepTime);
// Redraw the square in its original color before going to
// the next square.
chosenCell.darken();
repaint();
// Sleep between squares.
InterruptibleThread.sleep(sleepTime);
}
}
Search WWH :
Custom Search
Previous Page
Multithreaded Programming with JAVA - Topic Index
Next Page
Multithreaded Programming with JAVA - Bookmarks
Home