SPACE INVADERS 6
In this project, we're going to continue building our Space Invaders game by starting to animate the aliens and add some collision detection for the missiles we're firing at them.
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 move the aliens to the right. Moving the aliens is going to look very similar to how we moved the missile in the previous project -- we'll track time to determine when to move the aliens, we'll define how quickly to move them, we'll move them when the time is right.

Here is our initialization code:

We'll move the aliens to the right, and for now, we'll never move them left. So, of course, that means that once they move off of the screen, they aren't coming back!

Here is our code to move the aliens when the time is right:

List Comprehensions

In the above code, we snuck in a completely new concept in the line:

alien_columns = [column + 1 for column in alien_columns]
It's called a list comprehension, and it's a handy tool in Python that combines the features of lists and for loops into one. They are useful in cases where you want to create a list using a loop. For example, perhaps you want to create a list of the first five perfect squares (the product of a number multiplied by itself):

[1, 4, 9, 16, 25]

You could easily do this in a loop, by creating a list and appending to it:

squares = []
for i in range(1, 6):
    squares += [i * i]

List comprehensions provide a way to do the same thing, in a much more concise (and faster!) format:

squares = [i * i for i in range(1, 6)]

In English, the above list comprehension would read something like:

a list where each item equals (i * i) for i in the range 1 to 5

Another thing we're going to want to do in this project is to detect whether the aliens have collided with an existing missile, and if one of them has, remove it from the screen (and from the array). And if we remove an alien, we need to check if that's the last alien (if the array is empty), in which case we drop through the loop and end the game:

Lastly, once we drop through the loop to end the game, we'll want to test if the alien array is empty (in which case the player wins) or if the array is still populated with one or more aliens (in which case the player loses):

Here is the full project code to this point -- when you run it, you should be able to fire missiles and destroy the aliens:

home | prev | next