My Invaders Game
Week 1
This week, we are going to build a simple game using object-oriented programming techniques with
Python. Have a look at My Invaders Project - [Link]
Import Pygame
First, we need to import the pygame module
import pygame
Create Player Class
We need to create a class to represent the player. We use the __init__() constructor to
initialise all our variables and load the [Link] image.
class Rocket():
def __init__(self, screen):
[Link] = screen
[Link] = [Link]('[Link]')
[Link] = [Link].get_rect()
self.screen_rect = screen.get_rect()
[Link] = self.screen_rect.centerx
[Link] = self.screen_rect.bottom
We also need a method that will draw the player’s ship – the rocket – on the screen.
def draw(self):
[Link]([Link], [Link])
Create Main Program
Now we need to create the main program. First we initialise pygame and create a screen.
[Link]()
screen = [Link].set_mode((800, 600))
Create a rocket object from the class Rocket. We pass our “screen” we created above to the Rocket
class.
rocket = Rocket(screen)
Load our background image
background = [Link]("[Link]")
Create our clock so the game runs at a specific speed
clock = [Link]()
Turn on keyboard repeat, so the rocket continues to move if you hold down the key
[Link].set_repeat(1, 25)
Initialise our running variable to 1 which means the game is running
running = 1
Create the Game Loop
Here we need to create a while loop to keep the game running. We’ll run the program until the
variable running = 0. We’ll set the clock to 25 which means that for every second 25 frames should
pass.
while running:
[Link](25)
[Link](background, (0, 0))
Next, we need an event handler that will check for key presses. We want to monitor the left and
right arrow keys.
for event in [Link]():
if [Link] == [Link]:
running = 0
elif [Link] == [Link]:
if [Link] == pygame.K_RIGHT:
[Link] += 10
if [Link] == pygame.K_LEFT:
[Link] -= 10
Now, we can draw our rocket on the screen
[Link]()
Then update the screen
[Link]()
Run the Program
When you run the program, you’ll be able to move your ship left and right.
Week 2
This week, we are going to add some UFOs to the project and make them fly around the screen.
Have a look at My Invaders Project - [Link]
We can do this by adding a new class for the UFO.
class UFO():
def __init__(self, screen):
super(UFO, self).__init__()
[Link] = screen
[Link] = [5, 5]
We can create some attributes for the x and y direction and current position on the screen
#ufo direction
self.ufo_X_dir = 0
self.ufo_Y_dir = 0
#ufo position
self.ufo_X_pos = 0
self.ufo_Y_pos = 0
We can also add an image of the UFO
[Link] = [Link]('[Link]')
[Link] = [Link].get_rect()
We set the UFO to appear in a random position on the screen between 100 and 600 pixels for x and
y
[Link].x = [Link](100,600)
[Link].y = [Link](100,600)
Add attributes to store the exact position on the screen.
self.x = float([Link].x)
Now we can add a method to draw the UFO at a position
def draw(self):
[Link]([Link], [Link])
Add another method to move the UFO by given x and y coords
def move(self):
[Link].move_ip([Link]) #ufo_rect.move_ip (x, y)
We need to make sure the UFO bounced off the 4 edges of the screen
Left edge
if [Link] < 0:
[Link][0] = -[Link][0]
self.ufo_X_dir=self.ufo_X_dir-1
Right edge
if [Link] > 800:
[Link][0] = -[Link][0]
self.ufo_X_dir=self.ufo_X_dir+1
Top edge
if [Link] < 0:
[Link][1] = -[Link][1]
self.ufo_Y_dir=self.ufo_Y_dir-1
Bottom edge
if [Link] > 600:
[Link][1] = -[Link][1]
self.ufo_Y_dir=self.ufo_Y_dir+1
Now set position of UFO center to the UFO rectangle
self.ufo_X_pos = [Link]
self.ufo_Y_pos = [Link]
In our code, we can create some UFOs
ufo = UFO(screen)
ufo2 = UFO(screen)
Run the Program
When you run the program, you’ll be able to move your ship left and right. The UFOs will float
around the screen.
Week 3
This week, we are going to add some bullets to the rocket ship for the player to fire at the UFOs.
Have a look at My Invaders Project - [Link]
We can add another class to create the bullets
class Bullet():
def __init__(self, screen, rocket):
[Link] = screen
Load the image of the bullet and assign to a rectangle
[Link] = [Link]('[Link]')
[Link] = [Link].get_rect()
Store the bullet’s y start position ie at nose of rocket ship
self.y = 480
We need to know if the bullet has been fired or not… Initialise the state to not fired (nofire)
[Link]='nofire'
Now add a method to draw the bullet on the screen.
def draw(self):
# Draw the ufo at its current location.
[Link]([Link], [Link])
Add another method to fire the bullet, starting at the rocket’s x position on the screen.
def fire(self, rocketxpos):
[Link]([Link], (rocketxpos, self.y))
self.y -= 10
if self.y < 0:
[Link] = 'nofire'
self.y = 480
Run the Program
When you run the program, you’ll be able to move your ship left and right. The UFOs will float
around the screen. You can also fire a bullet from the rocket ship
Week 4
This week, we are going to add some collision detection to the bullets and UFO. Have a look at My
Invaders Project - [Link]
To do this, first we need to add a new method to the bullets to check to see if they collide with the
UFO. We take the x pos and y pos of the UFO, along with the x and y position of the bullet and run it
through a formula to calculate the distance between them.
𝑑𝑖𝑠𝑡𝑎𝑛𝑐𝑒 ufo_X_pos bullet_X ² ufo_Y_pos bullet_Y ²
We can write a method as follows. If the distance is below 35 pixels, then the function will return
true.
def isCollision(self, ufo):
distance = [Link]([Link](ufo.ufo_X_pos - self.x, 2) +
([Link](ufo.ufo_Y_pos - self.y, 2)))
if distance < 35:
return True
else:
return False
Then in the main code we can call the method in the bullet object. This method returns true if it’s a
hit as we saw above. If the isCollision method returns true we draw the [Link] image on the
screen at the same position of the UFO.
if [Link](ufo):
[Link](exp, ([Link].x, [Link].y)) #show explosion image
After a hit, we place UFO back on screen in random position
[Link].x = [Link](0, 736)
[Link].y = [Link](50, 300)
Run the Program
When you run the program, you’ll be able to move your ship left and right. The UFOs will float
around the screen. You can also fire a bullet from the rocket ship. When a bullet hits the UFO you’ll
see the explosion and the UFO will re-appear on a random position.