0% found this document useful (0 votes)
23 views18 pages

Oop 6 Course 2

The document describes adding aliens to the Alien Invasion game. It discusses creating an Alien class and instance, determining how many aliens can fit in a row based on screen width, and generating a full row of aliens by looping and setting each alien's x position so they are evenly spaced. The fleet of aliens is created and can now be advanced sideways and down.

Uploaded by

mageedarbe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views18 pages

Oop 6 Course 2

The document describes adding aliens to the Alien Invasion game. It discusses creating an Alien class and instance, determining how many aliens can fit in a row based on screen width, and generating a full row of aliens by looping and setting each alien's x position so they are evenly spaced. The fleet of aliens is created and can now be advanced sideways and down.

Uploaded by

mageedarbe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

OBJECT ORIENTED PROGRAMMING

WITH PYTHON
Second Class
2st Semester

Lecture 6
SECOND PHASE
In this phase:
• we’ll add aliens to Alien Invasion.

• We’ll add one alien near the top of the screen

• and then generate a whole fleet of aliens.

• We’ll make the fleet advance sideways and down,

• and we’ll get rid of any aliens hit by a bullet.

• Finally, we’ll limit the number of ships a player has.

• and end the game when the player runs out of ships.

2
Creating the First Alien

Creating an Instance of the Alien

Building the Alien Fleet

Determining How Many Aliens Fit in a Row

Creating a Row of Aliens

Refactoring _create_fleet()

Adding rows

3
SECOND PHASE
Creating the Alien Class

Creating the
First Alien Creating an Instance of the Alien

Determining How Many Aliens Fit


Building the in a Row
Alien Fleet
Second
Phase Creating a Row of Aliens
Making the
Fleet Move
Refactoring _create_fleet()
Shooting Aliens
Adding Rows
Ending the
Game
4
CREATING THE FIRST ALIEN
• Placing one alien on the screen is like placing a ship on the screen. Each alien’s
behavior is controlled by a class called Alien, which we’ll structure like the Ship class.
• Make sure you save the image file you choose in the images folder.

5
CREATING THE ALIEN CLASS
• Now we’ll write the Alien class and save it as alien.py:
• Most of this class is like the Ship class except for the aliens’ placement on the screen.
Alien.py
import pygame 1• We initially place each alien near
from pygame.sprite import Sprite the top-left corner of the screen;
class Alien(Sprite): • we add a space to the left of it
"""A class to represent a single alien in the fleet.""" that’s equal to the alien’s width
def __init__(self, sj_game): and a space above it equal to its
"""Initialize the alien and set its starting position.""" height u so it’s easy to see.
super().__init__()
self.screen = sj_game.screen 2• We’re mainly concerned with the
# Load the alien image and set its rect attribute. aliens’ horizontal speed, so we’ll
self.image = pygame.image.load('images/alien.bmp') track the horizontal position of
self.rect = self.image.get_rect() each alien precisely.
# Start each new alien near the top left of the screen.
1 self.rect.x = self.rect.width • Note: This Alien class doesn’t need
self.rect.y = self.rect.height a method for drawing it to the
# Store the alien's exact horizontal position. screen; instead, we’ll use a
2 self.x = float(self.rect.x) Pygame group method that
automatically draws all the
elements of a group to the screen. 6
CREATING AN INSTANCE OF THE ALIEN
• We want to create an instance of Alien so we can see the first alien on the screen.
• Because it’s part of our setup work, we’ll add the code for this instance at the end of the
__init__() method in SpaceJet
• Finally, we’ll create an entire fleet of aliens, which will be quite a bit of work, so we’ll make a
new helper method called _create_fleet().
• Here are the updated import statements for space_jet.py:
space_jet.py
--snip--
from bullet import Bullet
from alien import Alien
• And here’s the updated __init__() method:
space_jet.py
def __init__(self):
--snip--
self.ship = Ship(self)
self.bullets = pygame.sprite.Group()
self.aliens = pygame.sprite.Group()
self._create_fleet() 7
CREATING AN INSTANCE OF THE ALIEN
• We create a group to hold the fleet of aliens, and we call _create_fleet(), which we’re
about to write. Here’s the new _create_fleet() method:
space_jet.py
def _create_fleet(self):
"""Create the fleet of aliens."""
# Make an alien.
alien = Alien(self)
self.aliens.add(alien)
• In this method, we’re creating one instance of Alien, and then adding it to the group that
will hold the fleet.
• The alien will be placed in the default upper-left area of the screen, which is perfect for the
first alien.
• To make the alien appear, we need to call the group’s draw() method in _update_screen():
space_jet.py
def _update_screen(self):
--snip--
for bullet in self.bullets.sprites():
bullet.draw_bullet() 8
self.aliens.draw(self.screen)
pygame.display.flip()
CREATING AN INSTANCE OF THE ALIEN
• When you call draw() on a group, Pygame draws each element in the group at
the position defined by its rect attribute. The draw() method requires one
argument: a surface on which to draw the elements from the group.
• The following figure shows the first alien on the screen.

9
BUILDING THE ALIEN FLEET
• To draw a fleet, we need to figure out how many aliens can fit across the screen and
how many rows of aliens can fit down the screen. We’ll first figure out the horizontal
spacing between aliens and create a row; then we’ll determine the vertical spacing
and create an entire fleet.

Determining How Many Aliens Fit in a Row


• To figure out how many aliens fit in a row, let’s look at how much horizontal space
we have. The screen width is stored in settings.screen_width, but we need an
empty margin on either side of the screen.
• We’ll make this margin the width of one alien. Because we have two margins, the
available space for aliens is the screen width minus two alien widths:

available_space_x = settings.screen_width – (2 * alien_width)

10
DETERMINING HOW MANY ALIENS FIT IN A ROW
• We also need to set the spacing between aliens;
• we’ll make it one alien width. The space needed to display one alien is twice its
width: one width for the alien and one width for the empty space to its right.
• To find the number of aliens that fit across the screen, we divide the available space
by two times the width of an alien.
• We use floor division (//), which divides two numbers and drops any remainder, so
we’ll get an integer number of aliens:

number_aliens_x = available_space_x // (2 * alien_width)

11
CREATING A ROW OF ALIENS
We’re ready to generate a full row of aliens. Because our code for making a single alien works,
we’ll rewrite _create_fleet() to make a whole row of aliens:
space_jet.py
def _create_fleet(self):
"""Create the fleet of aliens."""
# Create an alien and find the number of aliens in a row.
# Spacing between each alien is equal to one alien width.
1 alien = Alien(self)
2 alien_width = alien.rect.width
3 available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
# Create the first row of aliens.
4 for alien_number in range(number_aliens_x):
# Create an alien and place it in the row.
alien = Alien(self)
5 alien.x = alien_width + 2 * alien_width * alien_number
alien.rect.x = alien.x
self.aliens.add(alien)
12
CREATING A ROW OF ALIENS
• We’ve already thought through most of this code.
1• We need to know the alien’s width and height to place aliens, so we create an alien before
we perform calculations. This alien won’t be part of the fleet, so don’t add it to the group
aliens.

2• Here we get the alien’s width from its rect attribute and store this value in alien_width so we
don’t have to keep working through the rect attribute.

3• we calculate the horizontal space available for aliens and the number of aliens that can fit
into that space.

4• Next, we set up a loop that counts from 0 to the number of aliens we need to make.

5• In the main body of the loop, we create a new alien and then set its x-coordinate value to
place it in the row.

• Each alien is pushed to the right one alien width from the left margin. Next, we multiply the
alien width by 2 to account for the space each alien takes up, including the empty space to
its right, and we multiply this amount by the alien’s position in the row. We use the alien’s x
attribute to set the position of its rect. Then we add each new alien to the group aliens.
13
CREATING A ROW OF ALIENS
When you run Alien Invasion now, you should see the first row of aliens appear, as in this Figure

• The first row is offset to the left, which is actually good for gameplay. The reason is that we
want the fleet to move right until it hits the edge of the screen, then drop down a bit, then
move left, and so forth.
• this movement is more interesting than having the fleet drop straight down. We’ll continue
this motion until all aliens are shot down or until an alien hits the ship or the bottom of the
screen.
REFACTORING _CREATE_FLEET()
If the code we’ve written so far was all we need to create a fleet, we’d probably leave
_create_fleet() as is. But we have more work to do, so let’s clean up the method a bit. We’ll
add a new helper method, _create_alien(), and call it from _create_fleet():

space_jet.py
def _create_fleet(self):
• The method _create_alien() requires one
--snip--
parameter in addition to self: it needs the
# Create the first row of aliens.
alien number that’s currently being created.
for alien_number in range(number_aliens_x):
self._create_alien(alien_number)
• We use the same body we made for
_create_fleet() except that we get the
def _create_alien(self, alien_number):
width of an alien inside the method instead
"""Create an alien and place it in the row."""
of passing it as an argument.
alien = Alien(self)
alien_width = alien.rect.width
• This refactoring will make it easier to add
alien.x = alien_width + 2 * alien_width * alien_number
new rows and create an entire fleet.
alien.rect.x = alien.x
self.aliens.add(alien)
15
ADDING ROWS
• To finish the fleet, we’ll determine the number of rows that fit on the screen and then
repeat the loop for creating the aliens in one row until we have the correct number
of rows.
• To determine the number of rows, we find the available vertical space by subtracting
the alien height from the top, the ship height from the bottom, and two alien heights
from the bottom of the screen:
available_space_y = settings.screen_height – (3 * alien_height) – ship_height

• The result will create some empty space above the ship, so the player has
some time to start shooting aliens at the beginning of each level.
• Each row needs some empty space below it, which we’ll make equal to the
height of one alien. To find the number of rows, we divide the available
space by two times the height of an alien.
• We use floor division because we can only make an integer number of rows.

number_rows = available_height_y // (2 * alien_height)

16
ADDING ROWS
Now that we know how many rows fit in a fleet, we can repeat the code for creating a row
space_jet.py def _create_fleet(self):
--snip--
alien = Alien(self)
1 alien_width, alien_height = alien.rect.size
available_space_x = self.settings.screen_width - (2 * alien_width)
number_aliens_x = available_space_x // (2 * alien_width)
# Determine the number of rows of aliens that fit on the screen.
ship_height = self.ship.rect.height
2 available_space_y = (self.settings.screen_height -(3 * alien_height) - ship_height)
number_rows = available_space_y // (2 * alien_height)
# Create the full fleet of aliens.
3 for row_number in range(number_rows):
for alien_number in range(number_aliens_x):
self._create_alien(alien_number, row_number)
def _create_alien(self, alien_number, row_number):
"""Create an alien and place it in the row."""
alien = Alien(self)
alien_width, alien_height = alien.rect.size
alien.x = alien_width + 2 * alien_width * alien_number
alien.rect.x = alien.x
4 alien.rect.y = alien.rect.height + 2 * alien.rect.height * row_number
self.aliens.add(alien) 17
ADDING ROWS
1• We need the width and height of an alien, so we use the attribute size, which contains a
tuple with the width and height of a rect object.

2• To calculate the number of rows we can fit on the screen, we write our available
_space_y calculation right after the calculation for available_space_x .

3• To create multiple rows, we use two nested loops: one outer and one inner loop.
• The inner loop creates the aliens in one row. The outer loop counts from 0 to the number
of rows we want;
• Python uses the code for making a single row and repeats it number_rows times. To nest
the loops, write the new for loop and indent the code you want to repeat. Now when we
call _create_alien(), we include an argument for the row number so each row can be
placed farther down the screen.

4• The definition of _create_alien() needs a parameter to hold the row number. Within
_create_alien(), we change an alien’s y-coordinate value when it’s not in the first row x
by starting with one alien’s height to create empty space at the top of the screen. Each
row starts two alien heights below the previous row, so we multiply the alien height by two
and then by the row number.
• The first row number is 0, so the vertical placement of the first row is unchanged. All
subsequent rows are placed farther down the screen.
18

You might also like