Processing Month, Day 18 - Finishing the Game

Posted on 2011-05-18 by Jan Vantomme
Tags: processing, tutorial

We'll finish our little "Avoid the Asteroids" game today. I've changed the render method for the spaceship so we can draw a star when the spaceship gets hit by an asteroid. To calculate if our spaceship is colliding with the asteroids, we'll use the collide() and circleLineIntersect() functions which can be found in the functions tab of today's sketch. I won't go over these functions in detail. I borrowed the circleLineIntersect() function form Casey Reas, who borrowed it from Paul Bourke.

We also need some code to check if our player hasn't died. This is some pseudo code for the game structure.

if ( life > 0 ) {
    // draw asteroids   
    // draw spaceship
    // if ship was hit by asteroid, draw star and reset game
} else {
    // draw "game over" to the screen
}

If our spaceship is hit by an asteroid, we'll draw the explosion as an animated star. If the explosion reaches its maximum radius, we'll need to do reset all the asteroids, the spaceship, remove a life from the counter and delay the game for a second.

void resetAfterHit()
{
    for (Asteroid a : asteroids ) {
        a.reset();
    }
    spaceShip.reset();
    life--;
    delay(1000);
}

If our player lost, we can let him play again by pressing the space bar. We need to reset the asteroids and the spaceship, and set the life and score variables to their initial values.

void resetGame()
{
    for (Asteroid a : asteroids ) {
        a.reset();
    }
    spaceShip.reset();
    life = 3;
    score = 0;
}

Exercises

  • Give the player an extra life each time he reaches a score that is divisible by 1000 (tip: use %)
  • Keep a list of high scores in a text file.

Download

Download the sketch for Processing Month, Day 18 - Finishing the Game.

Tweet this article