Python编程:从入门到实践(第2版)学习笔记
任务描述:
找一幅星星的图像,并在屏幕上显示一系列整齐排列的星星。
思路分析:
1、设置程序运行前提条件
2、创建星星类并配置相关属性
3、显示星星多行多列显示
编码结构分析:
1、设置主程序存放在类StarList中并存储在文件case13-1.py文件中
2、创建Starbas类存在stardemo.py中
程序源码如下:
1、主程序文件及星星显示 case13-1.py
import sys
import pygame
from stardemo import Starbas
class StarList:
"""
在屏幕上显示一行排列整齐的星星
需要计算好一行可以容纳几个星星
需要计算好一列可以容纳几个星星
"""
def __init__(self):
# 初始化pygame
pygame.init()
# 创建800x600px屏幕
self.screen = pygame.display.set_mode((800, 600))
# 设置窗口标题
pygame.display.set_caption(" Star Demo")
# 设置窗口图标,注意pygame只能对surface对象进行操作,上传窗口图标并设置为 surface对象
self.icon = pygame.image.load('images/star.png')
# 已经转化为surface对象,设置窗口图标
pygame.display.set_icon(self.icon)
# 定义屏幕宽度和屏幕高度变量 用来计算空间
self.screen_height = self.screen.get_height()
self.screen_width = self.screen.get_width()
# 借助 sprite 精灵组 预备对星星进行编组
self.starbas = pygame.sprite.Group()
# 设置背景颜色
self.screen.fill((247, 247, 247))
# 在此处运行生成星星 程序可避免 程序陷入死循环
self.generate_star()
# 按照屏幕进行 多行多列显示 星星
def generate_star(self):
# 实例化星星类
new_satr = Starbas(self)
# 计算 一行允许存放的图案 ,除去左右各空出一个星星图案间距 且 星星间间距为 一个一个星星
available_space_x = self.screen_width - 2 * new_satr.image_width
allow_number_x = available_space_x // ( 2 * new_satr.image_width)
available_space_y = self.screen_height - 2 * new_satr.image_height
allow_number_y = available_space_y // (2 * new_satr.image_height)
for number_y in range(allow_number_y):
for number_x in range(allow_number_x):
new_satr = Starbas(self)
new_satr.rect.x = new_satr.image_width + new_satr.image_width * 2 * number_x
new_satr.rect.y = new_satr.image_height + new_satr.image_height * 2 * number_y
self.starbas.add(new_satr)
new_satr.drawsatr()
print(number_x, end=' ')
print(number_y)
def run_game(self):
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
# 绘制屏幕
pygame.display.flip()
if __name__ == '__main__':
star = StarList()
star.run_game()
2、星星类属性 stardemo.py
import pygame
from pygame.sprite import Sprite
class Starbas(Sprite):
"""通过精灵类进行 编组实现"""
def __init__(self, ai_game):
# 继承类
super().__init__()
# 获取主程序屏幕
self.screen = ai_game.screen
# 获取主屏幕所在的矩形
self.screen_rect = self.screen.get_rect()
# 上传星星图片
self.image = pygame.image.load('images/star.png')
# 获取星星图标的width 宽度 height高度
self.image_width = self.image.get_width()
self.image_height = self.image.get_height()
# 获取星星 所在的矩形框
self.rect = self.image.get_rect()
def drawsatr(self):
# 画出星星图案,后面一个参数代表图像大小
self.screen.blit(self.image, self.rect)
# print("星星宽度为:"+str(self.image_width)) --46
# print("屏幕宽度为:" + str(self.screen.get_width())) --800
运行结果:
疑难点分析:
1、显示星星为什么要使用sprite精灵组?
①为了复习super()继承
②为了熟悉sprite
③以后可以把屏幕显示的星星删掉,只需将其从精灵组去掉即可
2、generate_star()函数必须要在 init中使用,不然放在while循环中使用 会导致系统一直在重复绘制星星图案。
3、一定要处理好 背景颜色和 显示图片的先后顺序,不然可能会导致空屏幕 或者一直只有一个图片显示
4、计算每行每列可显示星星个数的方法
①在星星类中 定义出两个变量image_width和image_height 来统计星星的长宽
②在主程序中 计算出 每行/每列 可使用的像素值px
③根据第②来计算出 每行/每列 可容纳的 个数
④根据第③步使用双重for循环在屏幕上绘制星星图案
5、需注意在generate_star()函数中 进行了两次同名实例类new_satr = Starbas(self)
第一次是为了计算出 每行/每列 可使用的空间和个数
第二次是为了 对具体每个星星实例进行属性设置