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 an 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 missle 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 missles on the screen:
2. Changing the world:
To change the world, we'll first need to check to see if there is an existing missile on the screen (we'll know there is if the X coordinate is not -1). If there's a missile on the screen, we'll need to evaluate if enough time has passed since the last screen update to move the missile and update the screen again. If the time has come to move the missile, we'll want to update the Y coordinate, check to see if the missile has reached the top of the LED Matrix screen (in which case, we'll reset the X coordinate to -1 to indicate there is no current missile on the screen) and we'll want to reset the timer for the next move.
Now, if there is no current missile on the screen, we'll need to evaluate whether the fire button is being pressed -- if it is, we need to set the X coordinate location for the missle (equal to the current X coordinate location of the ship), set the Y coordinate location for the missile to 1 and start tracking the time that the missile was launched.
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 it's current location.
If we integrate those snippets of code into our current code for the project, our full project will currently look like this: