在事件监听前, 先对前一节的代码进行优化
指定帧率
死循环时, cpu性能越高, 则使用的资源越多, 电脑热量也增大
帧率, 指的是每秒刷新的次数, 我们指定60帧即可( 帧率越大, 性能消耗越多)
#创建时钟对象
clock = pg.time.Clock()
i = 0
在true循环中, 代码如下
clock.tick(60)
print(i)
i += 1
这样, 在true循环中, 每秒执行60次
更新已机位置
使用 rect 对象, 记录已方飞机的位置
hero_rect = pg.Rect(150, 300, 102, 126) #宽102, 高126是该图片的默认属性
在true循环中, 修改飞机 y 轴位置, 并绘制到主窗体中
hero_rect -= 2 #飞行速度
screen.blit(bg, (0,0) #重新绘制背景
screen.blit(hero, hero_rect)
pg.display.update()
如果不重新绘制背景, 则会留下飞行的残影, 通过调节帧数, 以及飞行速度控制画面的连贯
接下来, 设置已机不能飞出主窗体, 当它的 y 小于0是, 设置为700, 即回到底部, 这样飞机能循环飞行
if hero_rect.y <=0:
hero_rect.y = 700
捕获事件
pygame.event.get可以监听事件
event_list = pg.event.get()
if len(event_list > 0):
print(event_list)
接下来,我们对程序退出监听,当用户关闭窗口,程序关闭
for event in pg.event.get():
if event.type == pg.QUIT:
print("游戏结束")
pg.quit()
exit() #python内置函数,退出程序
代码小结
本小节,修改后的main.py代码如下:
import pygame as pg #导入pygame模块
pg.init() #pygame初始化
#实例化窗口
screen = pg.display.set_mode((480, 700))
#绘制背景
bg = pg.image.load("./images/background.png")
screen.blit(bg, (0,0)) #绘制, 第二个参数是图片位置
#绘制己方飞机
hero = pg.image.load("./images/me1.png")
screen.blit(hero, (200, 500))
pg.display.update() #刷新屏幕
#创建时钟对象
clock = pg.time.Clock()
#已机的位置
hero_rect = pg.Rect(200, 500, 102, 126) #宽102, 高126是该图片的默认属性
while True:
clock.tick(60)
for event in pg.event.get():
if event.type == pg.QUIT:
print("游戏结束")
pg.quit()
exit() # python内置函数,退出程序
hero_rect.y -= 2
if hero_rect.y <= -126:
hero_rect.y = 700
screen.blit(bg, (0, 0)) # 重新绘制背景
screen.blit(hero, hero_rect)
pg.display.update()
pg.quit() #pygame结束