代码之家  ›  专栏  ›  技术社区  ›  ajjanna12

PygameSprites即使在函数设置参数为

  •  1
  • ajjanna12  · 技术社区  · 7 年前

    因此,我有一个防止精灵离开屏幕的功能,即:`

    def move_extent(self, x, y):
        if self.rect.right > 700:
          self.rect.right = 700
        elif self.rect.left < 0:
          self.rect.left = 0
        elif self.rect.y < 275:
          self.rect.y = 275
        elif self.rect.y > 275:
          self.rect.y = 275`
    

    它可以防止精灵越过x坐标系,大部分情况下是y坐标系。但是,如果精灵位于最左侧或最右侧(0或700 x),它仍会向上或向下移动。

    以下是主要的游戏循环:

    while not done:
    
        for event in pygame.event.get():
          if event.type == pygame.QUIT:
            done = True
    
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
          protag.moveLeft(3)
        if keys[pygame.K_d]:
          protag.moveRight(3)
        if keys[pygame.K_w]:
          protag.moveUp(3)
        if keys[pygame.K_s]:
          protag.moveDown(3)
    
    
        all_sprites_list.update()
    
        screen.blit(background, (0, 0))
    
        all_sprites_list.draw(screen)
        move_extent(protag, x_coord, y_coord)
    
        pygame.display.flip()
    
        clock.tick(60)
    
    pygame.quit()
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   Patrick Artner    7 年前

    几乎:)将测试更改为:

    def move_extent(self, x, y):  # x and y are never used?
        if self.rect.right > 700:
            self.rect.right = 700
    
        if self.rect.left < 0:
            self.rect.left = 0
    
        if self.rect.y < 275:   # why y twice? this will limit y to be 275
            self.rect.y = 275   # and x is never checked ...
    
        if self.rect.y > 275:   # why y twice? this will limit y to be 275
            self.rect.y = 275`
    

    当前您的早期 if 已使用,所有其他测试将不再测试。

    您可以将其缩短为:

    def move_extent(self, x, y): 
        self.rect.right = min(700,self.rect.right) # take whatever is lower
        self.rect.left  = max(  0, self.rect.left) # take whatever is higher 
        self.rect.y = 275                          # fix y at 275
    

    https://docs.python.org/3/library/functions.html#max https://docs.python.org/3/library/functions.html#min