SPACE INVADERS 5
In this project, we add missile firing using our button.
I/O (Input/Output) RaspberrySTEM Cell
LED Matrix RaspberrySTEM Cell
Accelerometer RaspberrySTEM Cell
Having issues? Check out the Troubleshooting Guide.

In this project, we're going to add the ability to fire missiles.

The first step is to initialize the button that we'll use to fire the missiles in our initialization section. We do this by importing the function that we will use, creating a Button object associated with our firing button and then initializing the position of our missile (we'll only allow one missile to be on the screen at a given time so we only need one set of X, Y coordinates for the missile). We also will want to create two other variables -- one that will define the color of the missile (we can make it less bright than the other objects on the LED Matrix screen to give it a unique look) and one that will define how quickly the missile will move (in terms of number of seconds between drawing updates).

Here is what this piece of code will look like:

Next, we need to make changes to our game loop to support the missiles. This involves three parts of the loop:

1. Getting inputs:

In terms of getting inputs, we'll first want to check the button to determine when it's pressed. And we'll then want to get the current time to determine if enough time has elapsed that we need to move any existing missiles on the screen:

2. Changing the world:

To change the world, we'll first need to check if either:

  1. A missile was already launched and it's time to move it: We'll know this if missile_x >= 0, and MISSILE_STEP_TIME time has passed since the missile last moved. If so, we'll move the missile up, but if it goes past the top of the LED Matrix display, we'll remove it.

  2. The fire button was pressed: If so, we'll create a new missile, just above the ship.

3. Show the world:

To show the world, we'll check to see if there is an existing missile on the screen, and if there is, we'll draw its current location.

If we integrate those snippets of code into our current code for the project, our full project will look like this -- when you run it, try pressing the button and watching the missile fire:

home | prev | next