Planetalia - Java Training

Training and Consulting

Home

Tutorial - Writing a Space Invaders game in Java

  Previous Page - The Game Main Loop Current Page - 08 - Cleaning the Screen   Next Page - Controlled movement
  Return to the index of free Java tutorials  

Cleaning the Screen

(c) Alexander Hristov

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


           . . .  
76      
77 public void paint(Graphics g) { 78 g.setColor(getBackground()); 79 g.fillRect(0,0,getWidth(),getHeight());
80 g.drawImage(getSprite("bicho.gif"), posX, posY,this); . . .

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

  1. Update the "state of the world" or "stage"
  2. Refresh the screen (redraw the world)
  3. Wait some time
  4. Go back to point 1

The wainting period will be a global constant and that will be initially set at 10 ms:


           . . .  
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());
92 try { 93 Thread.sleep(SPEED); 94 } catch (InterruptedException e) {}
95 } 96 } . . .


Do you want to be notified when new tutorials or lessons are published? Press here


Full list of Java source files for this step

Invaders.java      

Full list of resources

explosion.wav disparo2.gif bombUL.gif oceano.gif
bombDR.gif disparo0.gif bicho0.gif bombD.gif
missile.wav test.gif disparo1.gif bombU.gif
bombDL.gif bombL.gif bicho.gif Thumbs.db
bombR.gif bicho2.gif bicho1.gif disparo.gif
musica.wav bombUR.gif photon.wav misil.gif
nave.gif      

  Previous Page - The Game Main Loop Current Page - 08 - Cleaning the Screen   Next Page - Controlled movement
  Return to the index of free Java tutorials  

(c) 2004 Planetalia S.L. All rights reserved. Unauthorized reproduction and/or mirroring is not permitted