SPACE INVADERS 2
In this project, we continue the development of our Space Invaders game by initializing and drawing our ship at the correct location.
I/O (Input/Output) RaspberrySTEM Cell
LED Matrix RaspberrySTEM Cell
Accelerometer RaspberrySTEM Cell
Having issues? Check out the Troubleshooting Guide.

Now that we have the framebuffer initialized and have verified that the LED Matrix is working, let's put our spaceship where it's supposed to be located -- in the middle of the LED Matrix horizontally (along the x-axis) and at the bottom of the LED Matrix vertically (y=0).

To determine the middle of the LED Matrix, we could take the known length of it (8 pixels) and divide that by two -- that would give us our middle dot (x=4). But, what if you later want to use this code on a smaller or larger LED Matrix display? For example, let's say you put four LED Matrices together to build a 16x16 display. If you put x=4 right into your code, when you run the program on your new 16x16 display, your spaceship will no longer be in the middle of the display.

Luckily, we have a way to handle this. There is a FrameBuffer attribute called width that will determine how many LED Matrices you have chained together and will tell you the width of your LED Matrix display. We can use that attribute to determine the actual width of the display, and then divide that actual width by 2 to get the starting position of our spaceship.

Here is what the initialization code for the initial position of the ship would look like:



In our previous project, we just drew the ship at x=3, y=0. But, now we have the actual x-coordinate from our calculation above, so we can draw the ship at its actual starting position.

But, there's one thing we need to keep in mind -- now that we're using a calculation to determine the position of the ship, it's possible that the result of our calculation won't be a whole number (for example, if we were using an LED Matrix that was 7 pixels wide, our initial position would be x=3.5). To accomodate for that, we need to round our calcuation to the nearest whole number, and that is where we will display our ship.

We do that using the built-in math function called round(). Here is what the code will look like:



Finally, now is as good a time as any to put our pause at the end of the game loop. We had discussed trying a pause of of between .001 and .01 seconds. Let's start with the smaller number and see if that poses any problems as we're continuing to develop the game:



Here is the full code for our game at this point:



home | prev | next