在照例程做pygame外星人小游戲時遇到精靈組碰撞檢測的問題,不是很明白。以下是pygame.sprite.
groupcollide
()的官方文檔
This will find collisions between all the Sprites in two groups. Collision is determined by comparing the Sprite.rect
attribute of each Sprite or by using the collided function if it is not None.
Every Sprite inside group1 is added to the return dictionary. The value for each item is the list of Sprites in group2 that intersect.
If either dokill argument is True, the colliding Sprites will be removed from their respective Group.
The collided argument is a callback function used to calculate if two sprites are colliding. It should take two sprites as values and return a bool value indicating if they are colliding. If collided is not passed, then all sprites must have a "rect" value, which is a rectangle of the sprite area, which will be used to calculate the collision.
說的我有點雲里霧里,運行游戲程序打印一下pygame.sprite.
groupcollide
()的輸出(為方便測試這里采用了大子彈)
1 {} 2 {<Bullet sprite(in 0 groups)>: [<Alien sprite(in 0 groups)>]} 3 {<Bullet sprite(in 0 groups)>: [<Alien sprite(in 0 groups)>, <Alien sprite(in 0 groups)>, <Alien sprite(in 0 groups)>, <Alien sprite(in 0 groups)>, <Alien sprite(in 0 groups)>, <Alien sprite(in 0 groups)>]}
可以看出pygame.sprite.
groupcollide
()的返回值會有這三種。精靈組無碰撞發生則返回空字典({}的布爾值是Flase),發生碰撞則返回字典,其中子彈為鍵,外星人為值。每當檢測到碰撞發生都會返回一個這樣的字典。這樣以下增加得分的代碼也就很好理解了。
1 collisions = pygame.sprite.groupcollide(bullets, aliens, True, True) 2 if collisions: 3 stats.score += ai_settings.alien_points