0% found this document useful (0 votes)
12 views1 page

Creating a Ship Class in Pygame

Uploaded by

darkflux514
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)
12 views1 page

Creating a Ship Class in Pygame

Uploaded by

darkflux514
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

Figure 12-1: The ship for Alien Invasion

Creating the Ship Class


After choosing an image for the ship, we need to display it on the screen. To
use our ship, we’ll create a new ship module that will contain the class Ship.
This class will manage most of the behavior of the player’s ship:

[Link] import pygame

class Ship:
"""A class to manage the ship."""

def __init__(self, ai_game):


"""Initialize the ship and set its starting position."""
1 [Link] = ai_game.screen
2 self.screen_rect = ai_game.screen.get_rect()

# Load the ship image and get its rect.


3 [Link] = [Link]('images/[Link]')
[Link] = [Link].get_rect()

# Start each new ship at the bottom center of the screen.


4 [Link] = self.screen_rect.midbottom

5 def blitme(self):
"""Draw the ship at its current location."""
[Link]([Link], [Link])

Pygame is efficient because it lets you treat all game elements like rect-
angles (rects), even if they’re not exactly shaped like rectangles. Treating an
element as a rectangle is efficient because rectangles are simple geometric
shapes. When Pygame needs to figure out whether two game elements have
collided, for example, it can do this more quickly if it treats each object as a
rectangle. This approach usually works well enough that no one playing the

234 Chapter 12

You might also like