python - 模糊的 Pygame 矩形错误

标签 python pygame rect

我在这里看到了一些带有错误的主题:“TypeError:参数必须是矩形样式对象”。我不断地遇到这个错误。

我已阅读文档:

Rect(left, top, width, height) -> Rect
Rect((left, top), (width, height)) -> Rect
Rect(object) -> Rect

我有一种从 pygame.Surface 中提取子表面的方法(它使用表面的原始方法):

def getSubSurface(self, rect):

    """
    Returns the subsurface of a specified rect area in the grict surface.
    """

    return self.surface.subsurface(rect)

问题是当我传递这个矩形时(我已经“整理”参数以使其更清晰):

sub = []
w = self.tileWidth
h = self.tileHeight
for i in range((self.heightInPixels/self.heightInTiles)):
    y = self.grid.getY(i)
    for j in range((self.widthInPixels/self.widthInTiles)):
        x = self.grid.getX(j)
        sub.append(self.tileset.getSubSurface(pygame.Rect(x,y,w,h)))

我已经明确传递了一个有效的 pygame.Rect,并且我没有任何地方进行 blitting,我得到:

sub.append(self.tileset.getSubSurface(pygame.Rect(x,y,w,h)))
TypeError: Argument must be rect style object

现在,有趣的部分是:如果我将参数更改为任意 int 值:

sub.append(self.tileset.getSubSurface((1,2,3,4)))

它工作得很好。 pygame subsurfaces 方法将其视为有效的矩形。问题是:我的所有实例变量都是有效的整数(即使它们不是,如果我显式转换它们也不起作用)。

这没有任何意义。

为什么它需要显式整数,但不接受我的变量? (如果值的类型不正确,我不会收到“rectstyle”错误,就好像我错误地传递了参数一样)。

最佳答案

如果传递给 Rect() 的任何参数不是数值,则会发生此错误。

要查看问题所在,请将以下代码添加到您的方法中:

import numbers
...
sub = []
w = self.tileWidth
h = self.tileHeight
for i in range((self.heightInPixels/self.heightInTiles)):
    y = self.grid.getY(i)
    for j in range((self.widthInPixels/self.widthInTiles)):
        x = self.grid.getX(j)
        # be 100% sure x,y,w and h are really numbers
        assert isinstance(x, numbers.Number)
        assert isinstance(y, numbers.Number)
        assert isinstance(w, numbers.Number)
        assert isinstance(h, numbers.Number)
        sub.append(self.tileset.getSubSurface(pygame.Rect(x,y,w,h)))

关于python - 模糊的 Pygame 矩形错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22472507/

相关文章:

python - 使用 os.walk 后加入会引发错误

Python:Pandas - 根据列值分隔数据框

java - 矩形碰撞检测系统不起作用

android rectF 警告

python - 将多个目标文档与多个源文档进行比较

python - python中如何使用__iter__动态创建对象

python - 移动度数 pygame

python - 由于 PyGame 错误需要帮助

python - 如何使用一个循环添加到多个组

java - Android RectF 坐标与触摸坐标不同吗?