Jul-02-2018, 03:35 PM
alien.py import pygame from pygame.sprite import Sprite class Alien(Sprite): """a class to represent a single alien in the fleet""" def __init__(self, ai_settings, screen): """initialize the alien and set its starting position""" super(Alien, self).__init__() self.screen = screen self.ai_settings = ai_settings #load the alien image and set its rect attribute self.image = pygame.image.load('images/alien.png') self.image = pygame.transform.scale(self.image, (100, 75)) self.rect = self.image.get_rect() #start each new alien near the top of the screen self.rect.x = self.rect.width self.rect.y = self.rect.height #store the alien's exact position self.x = float(self.rect.x) def blitme(self): """draw the alien at its current location""" self.screen.blit(self.image, self.rect) def check_edges(self): """return true if alien is at edge of screen""" screen_rect = self.screen.get_rect() if self.rect.right >= screen_rect.right: return True elif self.rect.left <= 0: return True def update(self): """move the alien right or left""" self.x += (self.ai_settings.alien_speed_factor * self.ai_settings.fleet_direction) self.rect.x = self.x----------------------------------------------------------------------------------------------------------------------------
bullet. py
import pygame from pygame.sprite import Sprite class Bullet(Sprite): """A class to manage bullets fired from the ship """ def __init__(self, ai_settings, screen, ship): """create a bullet object at the ship's current position""" super(Bullet, self).__init__() self.screen = screen # create a bullet rect at (0, 0) and then set correct position self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height) self.rect.centerx = ship.rect.centerx self.rect.top = ship.rect.top #store the bullet's position as a decimal value self.y = float(self.rect.y) self.colour = ai_settings.bullet_colour self.speed_factor = ai_settings.bullet_speed_factor def update(self): """move the bullet up the screen""" # update the decimal position of the bullet self.y -= self.speed_factor # update rect position self.rect.y = self.y def draw_bullets(self): """draw the bullet on screen""" pygame.draw.rect(self.screen, self.colour, self.rect)