主程序:
player = Player("player.png",[10,650])
players = pygame.sprite.Group()
players.add(player)
while True:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_RIGHT:
player.goright()
if event.key == K_LEFT:
player.goleft()
if event.type == KEYUP:
if event.key == K_RIGHT:
player.cangoright = False
if event.key == K_LEFT:
player.cangoleft = False
players.update()
players.draw(SCREEN)
pygame.display.update()
clock.tick(FPS)
相关精灵的功能:
def update(self):
if self.cangoright:
self.rect.left += self.speed
if self.cangoleft:
self.rect.left -= self.speed
def goright(self):
if self.rect.right <= 1024:
self.cangoright = True
else:
self.cangoright = False
def goleft(self):
if self.rect.left >= 0:
self.cangoleft = True
else:
self.cangoleft = False
问题是“cangoright”和“cangoleft”标志似乎不能正常工作。当精灵超出屏幕边缘时(左侧为 0,右侧为 1024),标志应设置为 false,因此更新函数中的 ifs 应返回 false,但这不会发生。