程序在运行期间会产生许许多多的事件,事件随时可能发生(如移动鼠标,点击鼠标,敲击键盘按键),Pygame的做法是将所有的事件都放到事件队列里,通过for循环语句迭代取出每一条事件,然后处理关注的事件即可。
下面的代码可以将程序运行过程中产生的所有事件都记录并存放到一个文件中:
import pygame import sys # 初始化Pygame pygame.init() size = width, height = 600, 400 screen = pygame.display.set_mode(size) pygame.display.set_caption("初次见面,请大家多多关照!") f = open("record.txt", 'w') while True: for event in pygame.event.get(): f.write(str(event) + '\n') if event.type == pygame.QUIT: f.close() sys.exit()
接下来我们想要将程序运行中产生的事件都显示在屏幕上。这就要涉及到在屏幕上显示文字的功能,或者说是在Surface上显示文字,但pygame并不能办法直接在Surface对象上面显示文字,因此需要调用font模块的render()方法,将文字渲染成为Surface对象,这样就可以调用blit()方法讲一个Surface对象放到另外一个上了。
import pygame import sys # 初始化Pygame pygame.init() size = width, height = 600, 400 screen = pygame.display.set_mode(size) pygame.display.set_caption("FishC Demo") bg = (0, 0, 0)#黑色的背景 #创建font对象 font = pygame.font.Font(None, 20) #第一个参数指定字体,第二个参数指定字体的尺寸 line_height = font.get_linesize() #调用get_linesize()方法获得每行文本的高度 position = 0 screen.fill(bg) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.blit(font.render(str(event), True, (0, 255, 0)), (0, position)) #render方法将文本渲染成Surface对象 #第一个参数是待渲染的文本 #第二个参数是指定是否消除锯齿 #第三个参数指定文本的颜色 position += line_height if position > height:#满屏时清屏 position = 0 screen.fill(bg) pygame.display.flip()
程序运行显示效果:
这里再列举Pygame常用的事件及其含义:
利用所学的关于事件的知识,这里将小乌龟设置成可以被控制移动。
import pygame import sys from pygame.locals import *#将pygame的所有常量名导入 # 初始化Pygame pygame.init() size = width, height = 600, 400 speed = [0, 0] bg = (255, 255, 255) # RGB # 创建指定大小的窗口 Surface screen = pygame.display.set_mode(size) # 设置窗口标题 pygame.display.set_caption("初次见面,请大家多多关照!") # 加在图片 turtle = pygame.image.load("turtle.png") # 获得图像的位置矩形 position = turtle.get_rect() l_head = turtle#左转 r_head = pygame.transform.flip(turtle, True, False)#右转 while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() if event.type == KEYDOWN: if event.key == K_LEFT: turtle = l_head speed = [-10, 0]#向左移动 if event.key == K_RIGHT: turtle = r_head speed = [10, 0]#向右移动 if event.key == K_UP: speed = [0, -10]#向上移动 if event.key == K_DOWN: speed = [0, 10]#向右移动 # 移动图像 position = position.move(speed) speed = [0, 0] if position.left < 0 or position.right > width: #翻转图像 turtle = pygame.transform.flip(turtle, True, False) # 反方向移动 speed[0] = -speed[0] if position.top < 0 or position.bottom > height: speed[1] = -speed[1] # 填充背景 screen.fill(bg) # 更新图像 screen.blit(turtle, position) # 更新界面 pygame.display.flip() # 延迟10毫秒 pygame.time.delay(10)