提问者:小点点

Pygame:TypeError:源对象必须是曲面


下面是我的两个实现版本

#version 1 this one works fine when I call it
class Asset(pygame.sprite.Sprite):
    def __init__(self, x_pos, y_pos, path=None, paths=None):
        super().__init__()
        self.x_pos = x_pos
        self.y_pos = y_pos

        if path:
            # if only one image
            self.image = pygame.image.load(path).convert_alpha()

        else:
            self.images = paths
            self.images_index = 0
            self.image = self.images[self.images_index]


        self.rect = self.image.get_rect(midbottom=(x_pos, y_pos))

class Player(Asset):

    def __init__(self, x_pos, y_pos):
        walking = [pygame.image.load('Images/graphics/Player/player_walk_1.png'),
                   pygame.image.load('Images/graphics/Player/player_walk_2.png')]
        super().__init__(x_pos=x_pos, y_pos=y_pos, paths=walking)
        self.vert_speed = 0
        self.jumping_image = pygame.image.load(
            'Images/graphics/Player/player_jump.png')
        self.time_in_air = 0
        self.ground = y_pos


然而,当我调用它时,这个函数不起作用(返回“TypeError:源对象必须是曲面”)

*最近的调用是\pyplay\sprite.py,第546行,绘制surface.blits((spr.image,spr.rect)spr in sprites)

#version 2

class Asset(pygame.sprite.Sprite):
    def __init__(self, x_pos, y_pos, path=None, paths=None):
        super().__init__()
        self.x_pos = x_pos
        self.y_pos = y_pos

        if path:
            # if only one image
            self.image = pygame.image.load(path).convert_alpha()

        else:
            self.images = paths
            self.images_index = 0
            self.image = pygame.image.load(
                self.images[self.images_index]).convert_alpha()
            # The problem is right here

        self.rect = self.image.get_rect(midbottom=(x_pos, y_pos))


class Player(Asset):

    def __init__(self, x_pos, y_pos):
        walking = ['Images/graphics/Player/player_walk_1.png',
                   'Images/graphics/Player/player_walk_2.png']
        super().__init__(x_pos=x_pos, y_pos=y_pos, paths=walking)
        self.vert_speed = 0
        self.jumping_image = pygame.image.load(
            'Images/graphics/Player/player_jump.png')
        self.time_in_air = 0
        self.ground = y_pos

我期望这两个版本有相同的结果,但无法找出错误发生的原因。

有人能解释一下这两个版本的区别吗?我一直在寻找答案但真的找不到


共1个答案

匿名用户

您应该pygame中加载图像,并且在不加载图像的情况下不能使用图像
您甚至在类Assset\uuuu init\uuuu中加载了图像,如下所示:

[...]
if path:
         # if only one image
         self.image = pygame.image.load(path).convert_alpha() # <-----
[...]

因此,您应该在类播放器初始化中加载图像,如下所示:

[...]
walking = [pygame.image.load('Images/graphics/Player/player_walk_1.png'),
                   pygame.image.load('Images/graphics/Player/player_walk_2.png')]
[...]