移动图像
本课属于 Coddy Pygame 学习旅程的“精灵与图像”单元。第 3 课,共 39 课。
飞船位于窗口底部。要让它向左或向右移动,用方向键移动它的 Rect,就像你在第 2 单元中移动正方形一样:
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
ship_rect.x -= 6
if keys[pygame.K_RIGHT]:
ship_rect.x += 6blit 这一行不需要改变:它会在 Rect 当前所在的位置绘制。
Rect 可以让自己保持在另一个 Rect 内。screen.get_rect() 是窗口的 Rect,(0, 0, 640, 480),而
ship_rect.clamp_ip(screen.get_rect())当 ship_rect 越界时,会将它移回窗口内。_ip 表示就地操作:它会直接改变 ship_rect。不带 _ip 的 ship_rect.clamp(...) 不会改变 ship_rect,而是返回一个新的 Rect。
挑战
简单让飞船向左和向右移动。
- 在循环中,绘制之前,按住 Left 会让
ship_rect向左移动 6 像素,按住 Right 会让它向右移动 6 像素。 - 然后使用
ship_rect.clamp_ip(screen.get_rect())将它限制在窗口内。
按“开始”并按住方向键:飞船会在边缘停下。然后按“检查”。
亲手试试
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Space Images")
clock = pygame.time.Clock()
ship = pygame.image.load("assets/images/ship.png").convert_alpha()
ship_rect = ship.get_rect(center=(320, 400))
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((20, 22, 40))
screen.blit(ship, ship_rect)
pygame.display.flip()
clock.tick(60)
pygame.quit()
精灵与图像中的所有课
自己练习: Pygame 在线编辑器