2015-10-03 35 views
1

我想在pygame库的帮助下编写一个小型的滚动游戏。当我试图在运行时添加障碍时,我注意到pygame/python中有一些奇怪的行为。添加后列表的最后一项不会改变

class ObstaclesGroup(pygame.sprite.Group): 
    def update(self, offset):  
     lastSprite = self.sprites()[-1] 
     if lastSprite.rect.x < distance + 640: 
      # add obstacle with a distance of 300 px to the previous 
      self.add(Obstacle(distance + 940)) 
      sprite = self.sprites()[-1] 

      # often the values are the same, although the last one 
      # should be 300px bigger 
      # update: they even seem to be identical 
      if (lastSprite == sprite): 
       print (lastSprite.rect.x, " ", sprite.rect.x) 

后下部(后“如果”)被执行第二次,lastSprite和精灵的x坐标,似乎是同一不少。

下面是从控制台输出一些例子:

740  1043 
1043  1043 
1043  1043 
1043  1043 
1043  1344 
1344  1344 
1344  1648 
1648  1648 
1648  1648 
1648  1648 
1648  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  1953 
1953  2326 
2326  2326 
2326  2326 
2326  2326 
2326  2326 
2326  2326 
2326  2326 
2326  2326 
2326  2288 
2288  2288 
2288  2288 
2288  2288 
2288  2288 
2288  2288 
2288  2288 
2288  2288 
2288  2288 
2288  2288 
2288  2288 

精灵(Obstacle)似乎并没有被正确添加到spritegroup,虽然他们被吸引(我可以看到不同的偏移多重障碍,因为它在每个循环周期中增加)。
可能是什么问题?

UPDATE: 如果在它们结束时添加:两个精灵是相同的。

回答

3

source显示sprite.Group.sprites()的结果只是字典键的列表。字典是无序的,所以你不能确定那个列表中的最后一个精灵是你添加的最后一个精灵。
试试这个:

class ObstaclesGroup(pygame.sprite.Group): 
    def update(self, offset): 

     # function that returns the x-position of a sprite 
     def xPos(sprite): 
      return sprite.rect.x 

     # find the rightmost sprite 
     lastSprite = max(self.sprites(), key=xPos) 
     if xPos(lastSprite) < distance + 640: 
      # add obstacle with a distance of at least 300 px to the previous 
      self.add(Obstacle(distance + 940)) 

顺便说==检查的平等,而不是身份。如果你想知道你是否在处理同一个对象,你应该使用is;)

相关问题