We had a monster overload in our previous step which we must take care of. As a first attempt at solving our problem,
we can try erasing the window manually before drawing the monster.
The only lines that change are the ones inside the paint()method
Invaders.java
. . .
76
77 public void paint(Graphics g) {
78 g.setColor(getBackground());
79 g.fillRect(0,0,getWidth(),getHeight());
If now we run the program, we see that the critter changes its position so fast that it's almost impossible
to see it. It's clear that we must insert an artificial delay inside the main loop, to give the user some
time to see the world before it changes again. Our main loop now becomes
Update the "state of the world" or "stage"
Refresh the screen (redraw the world)
Wait some time
Go back to point 1
The wainting period will be a global constant and that will be initially set at 10 ms:
Invaders.java
. . .
24
25 public class Invaders extends Canvas {
26 public static final int WIDTH = 640;
27 public static final int HEIGHT = 480;
28 public static final int SPEED = 10;
29
. . .
87
88 public void game() {
89 while (isVisible()) {
90 updateWorld();
91 paint(getGraphics());