可发射子弹的最简太空飞船射击雏形.py

"""可发射子弹的最简太空飞船射击雏形.py 演示了图像的显示,音效的播放与跟随鼠标移动最简方案。玩家操控的飞船可以改成用类来实现."""


__author__ = "李兴球"
__date__ = "2018年12月"
__company__ = "风火轮少儿编程"

import pygame
 
# 定义颜色常量
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
CYAN = (0,255,255)

class Bullet(pygame.sprite.Sprite): 
    pass   # 子弹类的代码比较简单,相信读者根据上下文及参考其它文章可以自行编写:)
        
# 初始化派gei
pygame.init()
 
# 创建800x600的屏幕对象,它是一个surface
screen = pygame.display.set_mode([800, 600])
 
# 设置窗口的标题
pygame.display.set_caption('可发射子弹的最简太空飞船射击雏形_作者:李兴球,风火轮少儿编程')
 
clock = pygame.time.Clock()
 
# 生成声音对象
click_sound = pygame.mixer.Sound("laser5.ogg")
 
# 设置图像的坐标
background_position = [0, 0]
 
# 加载背景图像和玩家图像,把玩家图像的黑色设为不渲染颜色
background_image = pygame.image.load("saturn_family1.jpg").convert()
player_image = pygame.image.load("player.png").convert()
player_image.set_colorkey(BLACK)
player_rect = player_image.get_rect()

bullet_list = pygame.sprite.Group()

done = False
 
while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:done = True
        
    # 得到鼠标指针坐标     
    player_position = pygame.mouse.get_pos()
    x = player_position[0]
    y = player_position[1]
    player_rect.center = (x,y)

    # 单击左键发射
    if pygame.mouse.get_pressed()[0] :
        print("生成子弹,发射它")
        Bullet((x,y-36),bullet_list)
        click_sound.play()
    bullet_list.update()

    # 把背景图贴到screen上
    screen.blit(background_image, background_position)
    
    # 把玩家图贴到screen上
    screen.blit(player_image, player_rect)
    bullet_list.draw(screen)
    pygame.display.flip()
 
    clock.tick(60)
 
pygame.quit()