如何在 Pygame 中使用精灵类参数作为 pygame.Surface.get_rect() 中的关键字参数?

问题描述 投票:0回答:1

我正在尝试创建一个 sprite 类,我可以为其分配大小、颜色、坐标和组。这是它的样子:


import pygame, sys
from pygame.locals import *

RED = (255,0,0)

class MapObject(pygame.sprite.Sprite):
    def __init__(self, size, color, originxy, group):
        super().__init__()
        self.surf = pygame.Surface(size)
        self.surf.fill(color)
        self.rect = self.surf.get_rect(bottomleft = originxy)
        group.add(self)

floors = pygame.sprite.Group()

#    MapObject(size, color, originxy, group)
PT1 = MapObject((5760, 150), RED, (-2880, 1080), floors)

它工作得很好,但我只能将坐标分配给精灵的 bottomleft,所以我尝试向它添加另一个参数以允许 originxy 成为例如它自身的中顶。

我认为我可以简单地用一个新的 MapObject() 参数替换 bottomleft,即 origin 并且它将设置该参数的坐标。


import pygame, sys
from pygame.locals import *

RED = (255,0,0)

class MapObject(pygame.sprite.Sprite):
    def __init__(self, size, color, origin, originxy, group):
        super().__init__()
        self.surf = pygame.Surface(size)
        self.surf.fill(color)
        self.rect = self.surf.get_rect(origin = originxy)
        group.add(self)

floors = pygame.sprite.Group()

#    MapObject(size, color, origin, originxy, group)
PT1 = MapObject((5760, 150), RED, midtop, (-2880, 1080), floors)

我希望 origin 参数取代通常的 bottomleft,但我得到了一个错误:

Traceback (most recent call last):
File "problem test2.py", line 17, in \<module\>
PT1 = MapObject((5760, 150), RED, midtop, (-2880, 1080), floors)
NameError: name 'midtop' is not defined

我知道我必须将 floors 定义为精灵组,但我不知道我必须将 midtop 定义为什么才能将其用作 get_rect 中的关键字参数。有谁知道我该怎么做?

python pygame pygame-surface
1个回答
0
投票

midtop
是虚拟属性的名称,但是没有称为
midtop
的常量。在任何情况下,您都不能用 and 参数指定关键字参数的关键字。您可以做的最好的事情是在元组中对方向进行编码。第一项是水平方向(-1 = 左,0 = 中心,1 = 右),第二项是垂直方向(-1 = 顶部,0 = 中心,1 = 底部):

class MapObject(pygame.sprite.Sprite):
    def __init__(self, size, color, orientation, pos, group):
        super().__init__()
        self.surf = pygame.Surface(size)
        self.surf.fill(color)
        cx = pos[0] + orientation[0] * size[0] // 2
        cy = pos[1] + orientation[1] * size[1] // 2
        self.rect = self.surf.get_rect(center = (cx, cy))
        group.add(self)
midtop = (0, -1)
PT1 = MapObject((5760, 150), RED, midtop, (-2880, 1080), floors)
© www.soinside.com 2019 - 2024. All rights reserved.