太空射击第08课: 改进的碰撞( 三 )


代码改进版本
import pygameimport osimport sysimport random# 常量定义:游戏部分WIDTH = 360HEIGHT = 480FPS = 30# 颜色部分RED = (255, 0, 0)GREEN = (0, 255, 0)BLUE = (0, 0, 255)BLACK = (0, 0, 0)WHITE = (255, 255, 255)PURPLE = (255, 0, 255)YELLOW = (255, 255, 0)# 文件夹变量game_folder = os.path.dirname(__file__)img_dir = os.path.join(game_folder,'img')# 玩家类class Player(pygame.sprite.Sprite):def __init__(self, player_img, screen_width, screen_height, speedx=8, speedy=0):# super().__init__() # 也可这样初始化超类,只是没有参数selfpygame.sprite.Sprite.__init__(self)self.image = player_imgself.image.set_colorkey(BLACK)self.rect = self.image.get_rect()self.radius = 25# 注意:绘制图像时,在修改矩形位置之前pygame.draw.circle(self.image, RED, self.rect.center, self.radius)self.screen_width = screen_widthself.screen_height = screen_heightself.rect.centerx = screen_width // 2self.rect.bottom = screen_height - 10self.speedx = 0self.speedy = 0self.vx = speedxself.vy = speedydef update(self):self.speedx = 0keystate = pygame.key.get_pressed()if keystate[pygame.K_LEFT]:self.speedx = -self.vxif keystate[pygame.K_RIGHT]:self.speedx = self.vxself.rect.x += self.speedxif self.rect.right > self.screen_width:self.rect.right = self.screen_widthif self.rect.left < 0:self.rect.left = 0def shoot(self, bullet_img):bullet = Bullet(bullet_img,self.rect.centerx, self.rect.top)all_sprites.add(bullet)bullets.add(bullet)# 怪兽类class Mob(pygame.sprite.Sprite):def __init__(self, meteor_img, screen_width):pygame.sprite.Sprite.__init__(self)self.image = meteor_imgself.image.set_colorkey(BLACK)self.rect = self.image.get_rect()self.radius = int(self.rect.width / 2)pygame.draw.circle(self.image, RED, self.rect.center, self.radius)self.rect.x = random.randrange(screen_width - self.rect.width)self.rect.y = -random.randrange(40, 100)self.speedy = random.randrange(3, 8)self.speedx = random.randrange(1, 3) * (1 if random.random() < 0.5 else -1 )def update(self):self.rect.x += self.speedxself.rect.y += self.speedyif self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20:self.rect.x = random.randrange(WIDTH - self.rect.width)self.rect.y = random.randrange(-100, -40)self.speedy = random.randrange(1, 8)# 子弹类class Bullet(pygame.sprite.Sprite):def __init__(self,bullet_img, x, y):pygame.sprite.Sprite.__init__(self)self.image = bullet_imgself.image.set_colorkey(BLACK)self.rect = self.image.get_rect()self.rect.bottom = yself.rect.centerx = xself.speedy = -10def update(self):self.rect.y +=self.speedy# 如果子弹向上移出屏幕顶部,则删除它if self.rect.bottom < 0:self.kill()# 初始化pygame,创建窗口pygame.init()pygame.mixer.init()screen = pygame.display.set_mode((WIDTH, HEIGHT))pygame.display.set_caption("游戏窗口标题")clock = pygame.time.Clock()# 加载所有的图像background = pygame.image.load(os.path.join(img_dir,'starField.png')).convert()background_rect = background.get_rect()player_img = pygame.image.load(os.path.join(img_dir,'playerShip1_orange.png')).convert()meteor_img = pygame.image.load(os.path.join(img_dir,'meteorBrown_med1.png')).convert()bullet_img = pygame.image.load(os.path.join(img_dir,'laserRed16.png')).convert()all_sprites = pygame.sprite.Group()player = Player(player_img, WIDTH, HEIGHT,5)all_sprites.add(player)mobs = pygame.sprite.Group()for i in range(8):m = Mob(meteor_img,WIDTH)all_sprites.add(m)mobs.add(m)bullets = pygame.sprite.Group()# 游戏循环 running = Truewhile running:# 处理游戏事件for event in pygame.event.get():# 检查窗口关闭事件if event.type == pygame.QUIT:running = Falseelif event.type == pygame.KEYDOWN:if event.key == pygame.K_SPACE:player.shoot(bullet_img)# 更新屏幕上的对象all_sprites.update()# 检查是否有怪兽与玩家碰撞hits = pygame.sprite.spritecollide(player, mobs, False)if hits:ruuning = False# 检查子弹是否与怪兽碰撞hits = pygame.sprite.groupcollide(mobs,bullets, True, True)for hit in hits:m = Mob(meteor_img, WIDTH)all_sprites.add(m)mobs.add(m)# 渲染(绘制)screen.fill(BLACK)screen.blit(background,background_rect)all_sprites.draw(screen)# 渲染(绘制)后,翻转显示pygame.display.flip()# 游戏时钟clock.tick(FPS)pygame.quit()sys.exit()