我正在try 创建一个Sprite类,我可以将其大小、 colored颜色 、坐标和组分配给它.下面是它看起来的样子:


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)

它工作得很好,但我只能将坐标分配给Sprite的左下角,所以我try 向它添加另一个参数,以允许Origxy是例如,它本身的中顶.

我想我可以简单地用一个新的MapObject()参数替换左下角,即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)

我原以为原点参数会取代通常的左下角参数,但我得到了一个错误:

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

我知道我必须将Floor定义为精灵组,但我不知道必须将Midtop定义为什么才能将其用作get_rect中的关键字参数.有人知道我是怎么做到的吗?

推荐答案

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)

Python相关问答推荐

多处理代码在while循环中不工作

Python daskValue错误:无法识别的区块管理器dask -必须是以下之一:[]

根据另一列中的nan重置值后重新加权Pandas列

查找两极rame中组之间的所有差异

无法通过python-jira访问jira工作日志(log)中的 comments

我对我应该做什么以及我如何做感到困惑'

pandas:在操作pandora之后将pandora列转换为int

mdates定位器在图表中显示不存在的时间间隔

在电影中向西北方向对齐""

如何在验证文本列表时使正则表达式无序?

如何反转一个框架中列的值?

如何使用加速广播主进程张量?

Django.core.exceptions.SynchronousOnlyOperation您不能从异步上下文中调用它-请使用线程或SYNC_TO_ASYNC

类型对象';敌人';没有属性';损害';

Django更新视图未更新

FileNotFoundError:[WinError 2]系统找不到指定的文件:在os.listdir中查找扩展名

对包含JSON列的DataFrame进行分组

Pandas ,快速从词典栏中提取信息到新栏

了解如何让库认识到我具有所需的依赖项

将参数从另一个python脚本中传递给main(argv