创建 Sprite
# ……
# 初始Pygame及窗口
# ……
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
# 主循环
#……
all_sprites = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
while running:
# ……
Sprite 移动 sprite 精灵的矩形区域 rect
# ……
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((50, 50))
self.image.fill(GREEN)
self.rect = self.image.get_rect()
self.rect.center = (WIDTH / 2, HEIGHT / 2)
def update(self):
self.rect.x += 5
if self.rect.left > WIDTH:
self.rect.right = 0
主循环添加,调用Sprit 更新函数 Update
# 主循环
running = True
while running:
# ...
# 更新内容
all_sprites.update()
# 填充背景色
screen.fill(BLACK)
# 绘制所有精灵
all_sprites.draw(screen)
# 刷新
pygame.display.flip()
pygame.quit()