Skip to main content
 首页 » 编程设计

python之类型错误 : Argument must be rect style object in pygame

2024年10月24日9emanlee

一段时间以来,我一直在尝试自学如何在 pygame 中使用 Sprite ,但现在我被困在碰撞检测上。

我在代码中遇到问题的具体地方是标记为“此处错误”的注释部分,这就是不断给我“类型错误:参数必须是矩形样式对象”错误的代码以及该特定代码的目标是检测碰撞。

这段代码的目的是在玩家 block 进入非玩家 block 时在 shell 中打印一条消息,正如我之前所说,我一直无法实现这一点。

from pygame.locals import * 
import pygame 
 
pygame.init() 
 
SIZE = WIDTH, HEIGHT = 500, 700 
screen = pygame.display.set_mode(SIZE) 
 
plr_g = pygame.sprite.Group() 
h_box = pygame.sprite.Group() 
 
BLUE = (0, 206, 209) 
GREEN = (0, 255, 0) 
 
class Player(pygame.sprite.Sprite): 
    def __init__(self, width, height): 
        pygame.sprite.Sprite.__init__(self, plr_g) 
 
        self.image = pygame.Surface([width, height]) 
        self.image.fill(BLUE) 
        self.rect = self.image.get_rect() 
 
 
        self.rect.center = (WIDTH / 2, HEIGHT / 2) 
        #self.rect = (400, 200) 
 
 
    def x_pos(self): 
        self.rect.x 
    def y_pos(self): 
        self.rect.y 
    def move_l(self, pixels): 
        self.rect.x -= pixels 
    def move_r(self, pixels): 
        self.rect.x += pixels 
    def move_u(self, pixels): 
        self.rect.y -= pixels 
    def move_d(self, pixels): 
        self.rect.y += pixels 
 
 
class Hitbox(pygame.sprite.Sprite): 
    def __init__(self, bx, by): 
        pygame.sprite.Sprite.__init__(self, h_box) 
 
        self.image = pygame.Surface([100, 100]) 
        self.image.fill(GREEN) 
        self.rect = self.image.get_rect() 
 
        self.rect = (bx, by) 
 
 
hitbox = Hitbox(300, 300) 
hitbox = Hitbox(100, 500) 
player = Player(50, 50) 
 
 
while True: 
    for event in pygame.event.get(): 
        if event.type == pygame.QUIT: 
            sys.exit() 
 
        elif event.type==pygame.KEYDOWN: 
            if event.key==pygame.K_LEFT: 
                player.move_l(10) 
            if event.key==pygame.K_RIGHT: 
                player.move_r(10) 
            if event.key==pygame.K_UP: 
                player.move_u(10) 
            if event.key==pygame.K_DOWN: 
                player.move_d(10) 
 
 
    #error here 
    if plr_g.colliderect(h_box): 
        print("collide") 
    #---------------- 
 
    plr_g.update() 
    h_box.update() 
 
 
 
 
    screen.fill((50, 50, 50)) 
    h_box.draw(screen) 
    plr_g.draw(screen) 
    pygame.display.flip() 

请您参考如下方法:

h_box 是 Sprite 组,不是 Sprite ,也绝对不是矩形。必须在单个 Sprite 上调用 Sprite 的 collide_rect 函数。一个可能的解决方案如下所示,遍历 h_box 中的所有 Sprite :

if any([plr_g.colliderect(sp) for sp in h_box]): 
    print("collide")