import pygame
class StarSettings:
def __init__(self):
# 屏幕设置
self.screen_width = 1000
self.screen_height = 600
self.bg_color = (255, 255, 255)
import pygame
from pygame.sprite import Sprite
class StarImages(Sprite):
def __init__(self, image_attr):
super().__init__() #继承Sprite类
self.screen = image_attr.screen
self.settings = image_attr.settings
self.screen_rect = image_attr.screen.get_rect() #屏幕尺寸
self.image = pygame.image.load("images/star.bmp")
self.rect = self.image.get_rect() #图片尺寸
self.rect.x = self.rect.width #初始位置
self.rect.y = self.rect.height
# self.rect.x = 0
# self.rect.y = 0
# self.x = float(self.rect.x)
import sys
import pygame
from star_settings import StarSettings
from star_figure import StarImages
class StarMain:
def __init__(self):
pygame.init()
self.settings = StarSettings()
self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height))
pygame.display.set_caption("Star Display")
self.star_images = pygame.sprite.Group()
self._create_images()
def star_display(self):
while True:
self._check_events()
self._update_screen()
def _check_events(self): # 辅助方法
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
sys.exit()
def _update_screen(self):
#每次循环都重绘屏幕
self.screen.fill(self.settings.bg_color) #填充颜色
self.star_images.draw(self.screen)
# 让最近绘制的屏幕可见
pygame.display.flip()
def _create_images(self):
my_image = StarImages(self)
image_width, image_height = my_image.rect.size
available_space_x = self.settings.screen_width - (2 * image_width)
number_image_x = available_space_x // (2 * image_width)
available_space_y = self.settings.screen_height - (2 * image_height)
number_rows = available_space_y // (2 * image_height)
for all_row in range(number_rows):
for num_image in range(number_image_x):
self._create_one_image(num_image, all_row)
def _create_one_image(self, image_num, row_num):
image_attr = StarImages(self)
image_width, image_height = image_attr.rect.size
image_attr.x = image_width + 2 * image_width * image_num
image_attr.rect.x = image_attr.x
image_attr.rect.y = image_attr.rect.height + 2 * image_attr.rect.height * row_num
self.star_images.add(image_attr)
if __name__ == '__main__':
star = StarMain()
star.star_display()
主要学习 pygame 的应用,通过 Sprite 模块显示整齐排列的星星。先显示一颗星星,然后再通过循环创建星星阵列。