Game Speed

To adjust the speed of the game you need to change the delay between moving the aliens. In the following code snippet we show the run method in the SpaceInvaders.java file. This method is the workhorse of the game. Basically it waits for a number of milliseconds, moves the aliens and then draws their new position on the screen. Therefore to adjust the speed of the game we need to alter the value of the variable gameSpeed. This is located at the top of the SpaceInvaders.java file. Try some different values but remember to save and recompile each time.

public void run() {
    int count = 0;
    while(true) {
        try {
            Thread.sleep(gameSpeed);
        } catch(InterruptedException ie) {
            //Ignore this exception
        }
        //If the game is currently running, move the aliens
        if (!paused) {
            if (count >= 5) {
                moveAliens();
                count = 0;
            }
        }
        repaint();//Update the screen
        count ++;
    }
}

To compile your code type:

javac *.java

If you don't encounter any errors then you can run your game with this command:

java -cp . SpaceInvaders

As before, if you get any errors just ask your lab tutor.

Return to the start to make more changes <here>.