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

类型错误:参数1必须是pygame.Surface,而不是MyClass

  •  1
  • ScalaBoy  · 技术社区  · 6 年前

    我想制作一个精灵的动画 Worker 从左向右水平移动。另外,我还有一个精灵,它是一个静态背景图像。

    代码在第行失败 screen.blit(worker, (w_x,w_y)) 错误信息:

    类型错误:参数1必须是pygame.Surface,而不是Worker

    我知道只有浮雕表面是可能的,而不是 工人 . 但我怎么能 工人 为了给它做动画?

    我对PyGame很陌生。因此,我们将非常感谢您的帮助。

    代码:

    import pygame, random
    
    WHITE = (255, 255, 255)
    GREEN = (20, 255, 140)
    GREY = (210, 210 ,210)
    RED = (255, 0, 0)
    PURPLE = (255, 0, 255)
    
    SCREENWIDTH=1000
    SCREENHEIGHT=578
    
    class Worker(pygame.sprite.Sprite):
        def __init__(self, image_file, location):
            # Call the parent class (Sprite) constructor
            # super().__init__()
            self.image = pygame.image.load(image_file)
            self.rect = self.image.get_rect()
            self.rect.left, self.rect.top = location
    
    
    class Background(pygame.sprite.Sprite):
        def __init__(self, image_file, location):
            pygame.sprite.Sprite.__init__(self)
            self.image = pygame.image.load(image_file)
            self.rect = self.image.get_rect()
            self.rect.left, self.rect.top = location
    
    pygame.init()
    
    size = (SCREENWIDTH, SCREENHEIGHT)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("TEST")
    
    #all_sprites_list = pygame.sprite.Group()
    
    worker = Worker("worker.png", [0,0])
    w_x = worker.rect.left
    w_y = worker.rect.top
    
    bg = Background('bg.jpg', [0,0])
    
    carryOn = True
    
    while carryOn:
            for event in pygame.event.get():
                if event.type==pygame.QUIT:
                    carryOn=False
    
            screen.blit(pygame.transform.scale(bg.image, (SCREENWIDTH, SCREENHEIGHT)), bg.rect)
    
            #Draw geo-fences
            pygame.draw.rect(screen, GREEN, [510,150,75,52])
            pygame.draw.rect(screen, GREEN, [450,250,68,40])
    
            w_x += 5
            screen.blit(worker, (w_x,w_y))
    
            #Refresh Screen
            pygame.display.update()
    
    pygame.quit()
    quit()
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   skrx    6 年前

    pygame.Surface.blit 再拿一个 pygame.Surface 作为第一个论点,但是你通过了 Worker 反对。只要通过 image 工人属性:

    screen.blit(worker.image, (w_x,w_y))
    

    你也可以将你的精灵对象放入 pygame.sprite.Group 把所有的精灵和 draw 方法。

    while循环之外:

    sprite_group = pygame.sprite.Group()
    # Add the sprites.
    sprite_group.add(worker)
    

    在while循环中:

    sprite_group.update()  # Call the `update` methods of all sprites.
    
    sprite_group.draw(screen)  # Blit the sprite images at the `rect.topleft` coords.