@yanglt7
2018-12-08T09:14:52.000000Z
字数 2026
阅读 916
Pygame
事件随时可能发生,Pygame 的做法是把所有的事件都存放到事件队列里。通过 for 语句迭代取出每一条事件,然后处理关注的时间事件即可。
例 2 将程序运行期间产生的所有事件记录并保存到一个文件中。
import pygameimport syspygame.init()size = width, height = 600, 600screen = pygame.display.set_mode(size)pygame.display.set_caption("FishC Demo")f = open("record.txt", 'w')while True:for event in pygame.event.get():f.write(str(event) + '\n')if event.type == pygame.QUIT:sys.exit()

Pygame 没有办法直接在一个 Surface 对象上面显示文字,因此需要调用 font 模块的 render() 方法,该方法是将要显示文字渲染成一个 Surface 对象,这样就可以调用 blit() 方法将一个 Surface 对象放到另一个上面。
例 2-1
import pygameimport syspygame.init()size = width, height = 600, 600bg = (0, 0, 0)screen = pygame.display.set_mode(size)pygame.display.set_caption("FishC Demo")event_texts = []# 要在 Pygame 中使用文本,必须创建 Font 对象# 第一个参数指定字体,第二个参数指定字体的尺寸font = pygame.font.Font(None, 20)# 调用 get_linesize() 方法获得每行文本的高度line_height = font.get_linesize()position = 0screen.fill(bg)while True:for event in pygame.event.get():if event.type == pygame.QUIT:sys.exit()# render() 方法将文本渲染成 Surface 对象# 第一个参数是待渲染的文本# 第二个参数是指定是否消除锯齿# 第三个参数指定文本的颜色screen.blit(font.render(str(event), True, (0, 255, 0)), (0, position))position += line_heightif position > height:# 满屏时清屏position = 0screen.fill(bg)pygame.display.flip()


import pygameimport sysfrom pygame.locals import * # 将 Pygame 的所有常量名导入pygame.init()size = width, height = 600, 600speed = [-2,1]bg = (255, 255, 255)clock = pygame.time.Clock()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_headspeed = [-1, 0]if event.key == K_RIGHT:turtle = r_headspeed = [1, 0]if event.key == K_UP:speed = [0, -1]if event.key == K_DOWN:speed == [0, 1]position = position.move(speed)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()clock.tick(30)

摘自《零基础入门学习Python》