Python Pygame:精灵碰撞没有输出

Python Pygame:精灵碰撞没有输出,python,pygame,sprite,collision-detection,mask,Python,Pygame,Sprite,Collision Detection,Mask,我正在做一个游戏,你可以和精灵一起跳跃,障碍物正向你移动。我制作了一个精灵面具,并试图使用精灵碰撞功能,但什么也没发生:为了检查是否发生了碰撞,我制作了一个简单的打印语句。我试着把玩家精灵和它自己碰撞,结果它成功了。所以我在纠结什么是缺失或错误 导入pygame,随机 pygame.init() W、 H=800600 HW,HH=W/2,H/2 面积=W*H bg=pygame.image.load('Linn.png') bg=pygame.transform.scale(bg,(80

我正在做一个游戏,你可以和精灵一起跳跃,障碍物正向你移动。我制作了一个精灵面具,并试图使用精灵碰撞功能,但什么也没发生:为了检查是否发生了碰撞,我制作了一个简单的打印语句。我试着把玩家精灵和它自己碰撞,结果它成功了。所以我在纠结什么是缺失或错误



导入pygame,随机
pygame.init()
W、 H=800600
HW,HH=W/2,H/2
面积=W*H
bg=pygame.image.load('Linn.png')
bg=pygame.transform.scale(bg,(800600))
DS=pygame.display.set_模式((W,H))
clock=pygame.time.clock()
职业玩家(pygame.sprite.sprite):
定义初始值(self、x、y、py、paat、veerg、rida):
超级(玩家,自我)。\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu()
“Mangija huppamine”
self.x=x
self.y=y
自我跳跃=错误
self.platform_y=py
自速度指数=0
“雪碧床单”
self.paat=pygame.image.load('STlaev.png')。convert_alpha()35; pildi uleslaadimine
self.paat=pygame.transform.scale(self.paat,(300200))35; muutmaks-pilti-vaiksemaks
self.rect=self.paat.get_rect()
“Sprite sheeti piltide jaotamine pikslite jargi”
self.veerg=veerg
self.rida=rida
self.kokku=veerg*rida
W=self.veergL=self.rect.width/veerg
H=self.weegK=self.rect.height/rida
HW,HH=self.veergKeskel=(W/2,H/2)
self.veerg=list([(索引%veerg*W,int(索引/veerg)*H,W,H)用于范围内的索引(self.kokku)])
self.handle=list([#pildi paigutamise voimalikud PositionId
(0,0),(-HW,0),(-W,0),
(0,-HH),(-HW,-HH),(-W,-HH),
(0,-W),(-HW,-H),(-W,-H),]
self.mask=pygame.mask.from_surface(self.paat)
def do_跳线(自):
“Huppamine:kiirus,korgus,platvorm”
全球速度
如果自我跳跃:
self.y+=速度[自速度指数]
自速度指数+=1
如果self.velocity_index>=len(速度)-1:
self.velocity_index=len(velocity)-1
如果self.y>self.platform\u y:
self.y=self.platform\u y
自我跳跃=错误
自速度指数=0
def绘图(自、DS、veergindex、x、y、句柄=0):
blit(self.paat,(self.x+self.handle[handle][0],self.y+self.handle[handle][1]),self.veerg[veergindex])
def do(自我):
“Funktsioonide kokkupanek”
self.do_jumpt()
p、 提款(DS,指数%p.kokku,300300,0)
def更新(自我):
self.rect.center=self.x,self.y
p=球员(310200200,'STlaev.png',4,1)#曼吉亚·阿尔科纳迪德、胡佩·科格斯、皮尔特、斯皮特·瓦利克
速度=列表([(i/2.0)-14表示i在范围(0,50)])35; Huppe ulatus
指数=3
def键(播放器):
keys=pygame.key.get_pressed()
如果键[pygame.K_SPACE]或键[pygame.K_UP]和player.jumping==False:
player.jumping=正确
职业障碍(pygame.sprite.sprite):
''游戏障碍:*'''
#img=pygame.image.load(os.path.join('images','box.png'))
定义初始值(自、x、y、宽度、高度):
超级(障碍,自我)。\uuuu init\uuuuu()
self.img=pygame.image.load('box.png')。convert_alpha()
self.img=pygame.transform.scale(self.img,(64,64))
self.rect=self.img.get_rect()
self.x=x
self.y=y
self.width=宽度
自我高度=高度
self.mask=pygame.mask.from_surface(self.img)
def牵引(自,DS):
''淫秽图片布点和点击框''
DS.blit(self.img,(self.x,self.y))
def更新(自我):
self.rect.center=self.x,self.y
def redrawWindow():
“观察圈”
对于对象中的i:
i、 抽签(DS)
pygame.time.set_计时器(pygame.USEREVENT+2,random.choice([3000200001000800]))
对象=[]
“精灵”
sprites=pygame.sprite.Group()
障碍物=障碍物(832300,64,64)
p=播放器(310200200,'STlaev.png',4,1)
所有精灵=pygame.sprite.Group(p,obsticles)
ob=pygame.sprite.Group(障碍物)
x=0
尽管如此:
“游戏循环”
对于pygame.event.get()中的事件:
如果event.type==pygame.QUIT:
pygame.quit()
退出
如果event.type==pygame.USEREVENT+2:
r=随机。随机范围(0,2)
如果r==0:
附加对象(Obsticles(832300,64,64))
''障碍物速度和删除''
对于对象中的i:
i、 x-=5#障碍物的速度
如果i.x<-64:#从窗口删除障碍物
objects.pop(objects.index(i))
“背景运动”
back\u x=x%bg.get\u rect().width
blit(bg,(back\x-bg.get\rect().width,0))
如果返回x
问题在于,您只将障碍物精灵附加到
对象
列表中,而不附加到
所有精灵
ob
组中。行
all\u sprites.update()
调用所有包含的sprites的
update
方法,由于您的障碍物不在此组中,因此不会更新RECT。您还必须将它们添加到
ob
组,因为它用于碰撞检测

我建议删除
对象
列表,只需将障碍精灵添加到两个组中即可

class Obsticles(pygame.sprite.Sprite):

    def __init__(self, x, y):  # Removed width and height parameters.
        super(Obsticles, self).__init__()
        # Note that it would be more efficient to load the image
        # once in the global scope instead of loading it from the
        # hard disk again and again.
        # Also call the attribute `self.image`, then you can draw all
        # sprites by calling `all_sprites.draw(DS)` in the main loop.
        self.image = pygame.image.load('box.png').convert_alpha()
        self.image = pygame.transform.scale(self.image, (64, 64))
        self.rect = self.image.get_rect(center=(x, y))
        self.x = x
        self.y = y
        self.speed = -5
        self.mask = pygame.mask.from_surface(self.image)

    def draw(self, DS):
        '''Obsticle img blitting and hitbox'''
        DS.blit(self.img, (self.x, self.y))

    def update(self):
        self.x += self.speed  # Move the obstacle.
        # Update the rect because it's used to blit the 
        # sprite and for the collision detection.
        self.rect.center = self.x, self.y

        if self.x < -64:  # Delete the obstacle.
            # `kill()` removes this obstacle sprite from all sprite groups.
            self.kill()


def redrawWindow():
    """Draw the obstacles."""
    for i in ob:  # Uses the ob group now.
        i.draw(DS)


obsticles = Obsticles(832, 300)
# Use comprehensible variable names.
p = Player(310, 200, 200, 'STlaev.png', 4, 1)

all_sprites = pygame.sprite.Group(p, obsticles)
ob = pygame.sprite.Group(obsticles)

x = 0
done = False
while not done:
    # ---Handle the events.---
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.USEREVENT+2:
            r = random.randrange(0, 2)
            if r == 0:
                obsticles = Obsticles(832, 300)
                # Add the obstacle to both groups.
                ob.add(obsticles)
                all_sprites.add(obsticles)

    keys(p)

    # ---Game logic.---
    all_sprites.update()

    collided = pygame.sprite.spritecollide(p, ob, True, pygame.sprite.collide_mask)
    for i in collided:
        print('Collision.')

    index += 1
    # Background movement.
    x -= 1
    back_x = x % bg.get_rect().width

    # ---Draw everything.---
    DS.blit(bg, (back_x - bg.get_rect().width, 0))
    if back_x < W:
        DS.blit(bg, (back_x, 0))

    p.do()
    redrawWindow()

    pygame.display.update()
    clock.tick(60)


pygame.quit()
类障碍物(pygame.sprite.sprite):
def uu init(self,x,y):#删除了宽度和高度参数。
超级(障碍,自我)。\uuuu init\uuuuu()
#请注意,加载图像会更有效
#一次在全局范围内,而不是从
class Obsticles(pygame.sprite.Sprite):

    def __init__(self, x, y):  # Removed width and height parameters.
        super(Obsticles, self).__init__()
        # Note that it would be more efficient to load the image
        # once in the global scope instead of loading it from the
        # hard disk again and again.
        # Also call the attribute `self.image`, then you can draw all
        # sprites by calling `all_sprites.draw(DS)` in the main loop.
        self.image = pygame.image.load('box.png').convert_alpha()
        self.image = pygame.transform.scale(self.image, (64, 64))
        self.rect = self.image.get_rect(center=(x, y))
        self.x = x
        self.y = y
        self.speed = -5
        self.mask = pygame.mask.from_surface(self.image)

    def draw(self, DS):
        '''Obsticle img blitting and hitbox'''
        DS.blit(self.img, (self.x, self.y))

    def update(self):
        self.x += self.speed  # Move the obstacle.
        # Update the rect because it's used to blit the 
        # sprite and for the collision detection.
        self.rect.center = self.x, self.y

        if self.x < -64:  # Delete the obstacle.
            # `kill()` removes this obstacle sprite from all sprite groups.
            self.kill()


def redrawWindow():
    """Draw the obstacles."""
    for i in ob:  # Uses the ob group now.
        i.draw(DS)


obsticles = Obsticles(832, 300)
# Use comprehensible variable names.
p = Player(310, 200, 200, 'STlaev.png', 4, 1)

all_sprites = pygame.sprite.Group(p, obsticles)
ob = pygame.sprite.Group(obsticles)

x = 0
done = False
while not done:
    # ---Handle the events.---
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.USEREVENT+2:
            r = random.randrange(0, 2)
            if r == 0:
                obsticles = Obsticles(832, 300)
                # Add the obstacle to both groups.
                ob.add(obsticles)
                all_sprites.add(obsticles)

    keys(p)

    # ---Game logic.---
    all_sprites.update()

    collided = pygame.sprite.spritecollide(p, ob, True, pygame.sprite.collide_mask)
    for i in collided:
        print('Collision.')

    index += 1
    # Background movement.
    x -= 1
    back_x = x % bg.get_rect().width

    # ---Draw everything.---
    DS.blit(bg, (back_x - bg.get_rect().width, 0))
    if back_x < W:
        DS.blit(bg, (back_x, 0))

    p.do()
    redrawWindow()

    pygame.display.update()
    clock.tick(60)


pygame.quit()