Pygame显示和处理图像的基础分别是Surface
和Rect
(Rectangle)。
精灵(
Spirite
)类将两者封装在一起,免去了手动处理surface和reactangle的麻烦。如果你对surface和rect的原理感兴趣,可以继续看下去。
Surfaces:一个包含图像的层(A layer that contains visuals)。Pygame有两种Surface。
我们基本上只会用下面这个函数创建Display Surface:
screen = pygame.display.set_mode((width, height))
display.set_mode文档[1]
Regular Surfaces 可以通过pygame.Surface((width, height))
创建:
# Regular Surface
second_surface = pygame.Surface((100, 200))
second_surface.fill((0, 255, 0))
或者通过pygame.image.load()
创建:
kitten = pygame.image.load("kitten.jpg")
Regular Surfaces 需要放置在Display Surfaces上, 可以通过 screen.blit(surface,(x,y) )
实现放置。
screen.blit(second_surface, (200, 200))
PyGame的坐标系以显示器的左上角为原点,向右为x轴正方向,向下为y轴正方向。
下面我们创建一个绿色长方形,并在屏幕上显示:
import sys
import pygame
pygame.init()
clock = pygame.time.Clock()
width, height = 800, 600
# Display surface
screen = pygame.display.set_mode((width, height))
# Regular Surface
second_surface = pygame.Surface((100, 200))
second_surface.fill((0, 255, 0))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((255, 255,255)) # 将screen填充为白色
screen.blit(second_surface, (200, 200)) # 将second_surface放置在screen上
pygame.display.flip() # 更新屏幕画面
clock.tick(60) # 控制游戏速率,每秒60帧
Rectangle:矩形 我们想要操作Surface时,需要使用Rect
(矩形)。 Rect
是一个矩形区域,可以借助Rect控制Surface的位置。
Rect
surface.get_rect()
会返回一个和surface形状一样的矩形,默认位置在(0,0)
(即屏幕的左上角)。然后screen.blit(kitten, kitten_rect)
会使用rect的左上角坐标放置surface。
kitten = pygame.image.load("kitten.jpg")
kitten_rect = kitten.get_rect(topleft=(100,100)) # 返回一个和kitten大小一样的矩形,topleft: 矩形左上角在屏幕上的位置
...
while True:
...
screen.blit(kitten, kitten_rect) # 将ketten放在 rect位置。
kitten_rect.x += 1 # 修改rect的位置 向右偏移一个像素。
下面我们通过Rect来移动Surface。
放置两个surface,并通过改变Rect移动其中的一个surface。
通过Rect移动Surface
import sys
import pygame
pygame.init()
clock = pygame.time.Clock()
width, height = 800, 600
# Display surface
screen = pygame.display.set_mode((width, height))
# Regular Surface
second_surface = pygame.Surface((100, 200))
second_surface.fill((0, 255, 0))
# img : also a surface
kitten = pygame.image.load("kitten.jpg")
kitten = pygame.transform.scale(kitten, (400, 400))
kitten_rect = kitten.get_rect(topleft=(100,100)) # 返回一个和kitten大小一样的矩形,topleft: 矩形左上角在屏幕上的位置
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
screen.fill((255, 255,255)) # 将screen填充为白色
screen.blit(second_surface, (200, 200)) # 将second_surface放置在screen上
screen.blit(kitten, kitten_rect)
kitten_rect.x += 1
pygame.display.flip() # 更新屏幕画面
clock.tick(60) # 控制游戏速率,每秒60帧
[1]
display.set_mode文档: https://www.pygame.org/docs/ref/display.html#pygame.display.set_mode