最小应用

一下通过一个最小应用来看一下pygame的运行效果,在执行以下代码之前,请先准备一张图片。

import sys import math import pygame import pygame.locals # 初始化pygame pygame.init() # 创建一个800×600的窗口 screen = pygame.display.set_mode((800, 600), 0, 32) # 设置窗口标题 pygame.display.set_caption('Hello World') # 加载一张图片 background = pygame.image.load('sample.jpg').convert() # 对图片进行缩放处理 (b_width, b_height) = background.get_size() ratio = b_width / 800 if b_width >= b_height else b_height / 600 scaled_background = pygame.transform.scale( background, (math.floor(b_width / ratio), math.floor(b_height / ratio)) ) while True: for event in pygame.event.get(): # 对应用中出现的事件进行处理,如果出现退出事件则结束程序 if event.type == pygame.locals.QUIT: sys.exit() # 将图片绘制到窗口中,居中绘制 (sb_width, sb_height) = scaled_background.get_size() screen.blit( scaled_background, (math.floor((800 - sb_width) / 2), math.floor((600 - sb_height) / 2)) ) # 刷新整个画面 pygame.display.update()