1代码:
import pygame
from pygame.sprite import Sprite
def update(self):
self.x += (self.setting.spaceship_speed * self.setting.fleet_direction)
self.rect.x = self.x
def update(self):
if self.mv_right and self.rect.right < self.screen_rect.right: # 小飞机的有边框小于整个页面的有边框
self.center += self.setting.plane_speed # settings中的属性
if self.mv_left and self.rect.left > 0: # 小飞机的左边框大于0
self.center -= self.setting.plane_speed
self.rect.centerx = self.center
class Plane:
def __init__(self, screen, setting):
super().__init__()
self.screen = screen
self.setting = setting
self.img_plane = pygame.image.load("./imgs/plane.png")
self.rect = self.img_plane.get_rect() # 得到小飞机的的矩形区域
self.screen_rect = self.screen.get_rect() # 得到screen的矩形区域
# print(self.screen_rect)
self.rect.centerx = self.screen_rect.centerx # 水平居中
self.rect.bottom = self.screen_rect.bottom # 底部
self.center = float(self.rect.centerx)
self.mv_right = False
self.mv_left = False
def blitme(self):
self.screen.blit(self.img_plane, self.rect)
def center_plane(self):
self.center - self.screen_rect.centerx
class Bullet(Sprite): # 继承pygame.sprite中的Sprite类
def __init__(self, setting, screen, plane):
super().__init__()
self.screen = screen
# 在(0,0)处创建一个表示子弹的矩形
# pygame.Rect
# 用于存储直角坐标的pygame对象
self.rect = pygame.Rect(0,0, setting.bullet_width, setting.bullet_height)
# 设置显示的位置
self.rect.centerx = plane.rect.centerx
self.rect.top = plane.rect.top
self.y = float(self.rect.y)
self.speed = setting.bullet_speed
def update(self):
# 向上移动子弹
self.y -= self.speed
# 根据self.y的值更新self.rect.y
self.rect.y = self.y
def draw_bullet(self):
"""绘制子弹"""
# pygame.draw.rect()画一个矩形的形状
pygame.draw.rect(self.screen, self.color, self.rect)
class Spaceship(Sprite):
def __init__(self, setting, screen):
super().__init__()
self.screen = screen
self.setting = setting
self.img = pygame.image.load("./imgs/enemy.png")
self.rect = self.img.get_rect()
self.rect.x = self.rect.width
self.rect.y = self.rect.height
self.rect.w = self.rect.width
self.rect.h = int(self.rect.height / 2) # 将高度设置为一半
self.x = float(self.rect.x)
def blitme(self):
self.screen.blit(self.img, self.rect)
def check_edges(self):
screen_rect = self.screen.get_rect()
if self.rect.right >= screen_rect.right:
return True
elif self.rect.left <= 0:
return True