话接上回: https://www.cnblogs.com/yue-qian/p/14379618.html
实现这个小游戏需要玩家控制的飞船(ship),外星人(alien),开始按钮(button),玩家控制飞船射出的子弹(bullet)以及计分板。下面就依次实现各个模块。
ship模块如下:
import pygame from pygame.sprite import Sprite class Ship(Sprite): def __init__(self, ai_settings, screen): super(Ship, self).__init__() self.screen = screen
#获取飞船移动速率 self.ai_settings = ai_settings #设置飞船图像并且获取飞船外接矩形 self.image = pygame.image.load('images/ship.bmp') self.rect = self.image.get_rect() self.screen_rect = screen.get_rect() #飞船位置 self.rect.centerx = self.screen_rect.centerx self.rect.bottom = self.screen_rect.bottom self.center = float(self.rect.centerx) #移动标志 self.moving_right = False self.moving_left = False def center_ship(self): self.center = self.screen_rect.centerx def update(self): #更新飞船位置 if self.moving_right and self.rect.right < self.screen_rect.right: self.center += self.ai_settings.ship_speed_factor if self.moving_left and self.rect.left > 0: self.center -= self.ai_settings.ship_speed_factor self.rect.centerx = self.center #在指定位置绘制飞船 def blitme(self): self.screen.blit(self.image, self.rect)
bullet模块如下:
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): super(Bullet, self).__init__() self.screen = screen # 在(0,0)处创建一个表示子弹的矩形, 再设置正确的位置 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 #子弹位置设置为小数 self.y = float(self.rect.y) #设置子弹的一些参数 self.color = ai_settings.bullet_color self.speed_factor = ai_settings.bullet_speed_factor def update(self): """Move the bullet up the screen.""" #更新子弹位置 self.y -= self.speed_factor #更新子弹外接矩形 self.rect.y = self.y def draw_bullet(self): """Draw the bullet to the screen.""" pygame.draw.rect(self.screen, self.color, self.rect)
button模块如下:
import pygame.font class Button(): def __init__(self, ai_settings, screen, msg): self.screen = screen self.screen_rect = screen.get_rect() self.width, self.height = 200, 50 self.button_color = (0, 255, 0) self.text_color = (255, 255, 255) self.font = pygame.font.SysFont(None, 48) self.rect = pygame.Rect(0, 0, self.width, self.height) self.rect.center = self.screen_rect.center self.prep_msg(msg) def prep_msg(self, msg): self.msg_image = self.font.render(msg, True, self.text_color, self.button_color) self.msg_image_rect = self.msg_image.get_rect() self.msg_image_rect.center = self.rect.center def draw_button(self): self.screen.fill(self.button_color, self.rect) self.screen.blit(self.msg_image, self.msg_image_rect)