首页 > 解决方案 > Pygame 类型错误:参数必须是矩形样式对象

问题描述

我创建了这个类,所以我可以更好地工作

class Block:
  def __init__(self, top, left):
    self.Rect = pygame.Rect((top,left),(10,10))

然后我想创建一个像这样剪辑矩形的简单函数

def clip(rect_obj):
  return pygame.Rect.clip(rect_obj)

但是当我将 rect 传递给我的函数时,我在标题中得到了错误。我什至打印了类型

my_block = Block()
print(type(my_block.Rect))    --> <Class Pygame.Rect>
my_rect = clip(my_block.Rect) --> TypeError: Argument must be a rect style Object

我想知道矩形样式对象和矩形对象之间是否有区别,因为我很困惑。在屏幕上绘制矩形也是布局井字游戏 GUI 的最佳方式,还是更简单地绘制线条。

标签: pythonpygamegame-development

解决方案


错误是行pygame.Rect.clip(rect_obj)

def clip(rect_obj):
   return pygame.Rect.clip(rect_obj)  

这条线根本没有任何意义,因为pygame.Rect.clip它是一个实例方法。 pygame.Rect.clip()

返回一个被裁剪为完全在参数 Rect 内的新矩形。如果两个矩形开始时不重叠,则返回大小为 0 的 Rect。

pygame.Rect该方法与 2 个对象相交:

rect_1 = pygame.Rect(0, 0, 20, 20)
rect_2 = pygame.Rect(10, 10, 30, 30)
rect_and = rect_1.clip(rect_2 )

rect_and是 (10, 10) 处的矩形,大小为 (10, 10)。

可能您尝试将剪切区域设置为显示表面。这可以通过pygame.Surface.set_clip(). 例如:

screen = display.set_mode((width, height))

clip_rect = pygame.Rect(x, y, w, h)
screen.set_clip(clip_rect )

推荐阅读