TypeError:参数1必须是pygame.Surface,而不是MyClass

时间:2018-08-06 15:26:53

标签: python pygame

我想为从左侧向右侧水平移动的Sprite Worker设置动画。另外,我还有另一个Sprite,它是静态背景图片。

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

  

TypeError:参数1必须是pygame.Surface,而不是Worker

我知道可以只对曲面进行钝化,而不能Worker。但是如何将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 个答案:

答案 0 :(得分:1)

pygame.Surface.blit将另一个pygame.Surface作为第一个参数,但是您要传递一个Worker对象。只需传递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.